@crewai-ts/core 0.1.12 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +174 -0
- package/dist/agent.d.ts +16 -18
- package/dist/auth.cjs +598 -0
- package/dist/auth.js +40 -0
- package/dist/{chunk-3PVW4JKT.js → chunk-C43UEMCX.js} +6712 -7268
- package/dist/chunk-CCOE6MLE.js +896 -0
- package/dist/chunk-HFQTF332.js +4455 -0
- package/dist/{chunk-BE4JYKSG.js → chunk-MM4ROIFG.js} +12 -1490
- package/dist/chunk-RH43TNKN.js +238 -0
- package/dist/chunk-S477WFUT.js +565 -0
- package/dist/chunk-SB7ADUQA.js +110 -0
- package/dist/chunk-T32G6KDW.js +40 -0
- package/dist/crew.d.ts +24 -26
- package/dist/events.cjs +7513 -0
- package/dist/events.js +406 -0
- package/dist/experimental-conversational.cjs +272 -0
- package/dist/experimental-conversational.js +26 -0
- package/dist/feature-hooks.cjs +149 -0
- package/dist/feature-hooks.d.ts +94 -0
- package/dist/feature-hooks.js +36 -0
- package/dist/index.cjs +33923 -64381
- package/dist/index.d.ts +2 -15
- package/dist/index.js +16720 -49562
- package/dist/input-provider.d.ts +3 -4
- package/dist/lite-agent.d.ts +4 -4
- package/dist/llm.cjs +7467 -0
- package/dist/llm.d.ts +0 -4
- package/dist/llm.js +225 -0
- package/dist/optional-yaml.d.ts +8 -0
- package/dist/project.d.ts +1 -1
- package/dist/schema-utils.cjs +968 -0
- package/dist/schema-utils.d.ts +1 -1
- package/dist/schema-utils.js +102 -0
- package/dist/state-provider-core.js +3 -2
- package/dist/task.d.ts +3 -4
- package/dist/tools.cjs +6872 -0
- package/dist/tools.d.ts +0 -60
- package/dist/tools.js +114 -0
- package/dist/types.cjs +68 -0
- package/dist/types.js +14 -0
- package/package.json +52 -111
- package/dist/a2a.d.ts +0 -1684
- package/dist/a2ui-schemas.d.ts +0 -3312
- package/dist/a2ui.d.ts +0 -379
- package/dist/flow-conversation.d.ts +0 -90
- package/dist/flow-definition.d.ts +0 -195
- package/dist/flow-persistence.d.ts +0 -107
- package/dist/flow-visualization.d.ts +0 -77
- package/dist/flow.d.ts +0 -927
- package/dist/knowledge.d.ts +0 -353
- package/dist/mcp-DS7UMYAM.js +0 -62
- package/dist/mcp.d.ts +0 -315
- package/dist/memory.d.ts +0 -915
- package/dist/openai-completion.d.ts +0 -327
- package/dist/provider-completions.d.ts +0 -596
- package/dist/rag.d.ts +0 -1074
|
@@ -1,19 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
InternalInstructor,
|
|
3
|
-
MCPConfigFetchFailedEvent,
|
|
4
|
-
MCPConnectionCompletedEvent,
|
|
5
|
-
MCPConnectionFailedEvent,
|
|
6
|
-
MCPConnectionStartedEvent,
|
|
7
|
-
MCPToolExecutionCompletedEvent,
|
|
8
|
-
MCPToolExecutionFailedEvent,
|
|
9
|
-
MCPToolExecutionStartedEvent,
|
|
10
3
|
ToolSelectionErrorEvent,
|
|
11
4
|
ToolUsageErrorEvent,
|
|
12
5
|
ToolUsageFinishedEvent,
|
|
13
6
|
ToolUsageStartedEvent,
|
|
14
7
|
ToolValidateInputErrorEvent,
|
|
15
8
|
crewaiEventBus
|
|
16
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-C43UEMCX.js";
|
|
17
10
|
import {
|
|
18
11
|
ToolCallHookContext,
|
|
19
12
|
getAfterToolCallHooks,
|
|
@@ -21,12 +14,9 @@ import {
|
|
|
21
14
|
runAfterToolCallHooks,
|
|
22
15
|
runBeforeToolCallHooks
|
|
23
16
|
} from "./chunk-LWD4QED4.js";
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
28
|
-
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
29
|
-
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
17
|
+
import {
|
|
18
|
+
extractRegisteredPDFText
|
|
19
|
+
} from "./chunk-SB7ADUQA.js";
|
|
30
20
|
|
|
31
21
|
// src/string-utils.ts
|
|
32
22
|
import { createHash } from "crypto";
|
|
@@ -1950,22 +1940,15 @@ Base64: ${encoded}`;
|
|
|
1950
1940
|
};
|
|
1951
1941
|
async function readPDFFileText(content, filename) {
|
|
1952
1942
|
try {
|
|
1953
|
-
const
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
try {
|
|
1957
|
-
const result = await parser.getText();
|
|
1958
|
-
const text = result.text?.trim() ?? "";
|
|
1943
|
+
const extractedText = await extractRegisteredPDFText(content, filename);
|
|
1944
|
+
if (extractedText !== null) {
|
|
1945
|
+
const text = extractedText.trim();
|
|
1959
1946
|
return text.length > 0 ? text : `[PDF file with no extractable text: ${filename}]`;
|
|
1960
|
-
} finally {
|
|
1961
|
-
await parser.destroy?.();
|
|
1962
1947
|
}
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
const encoded = content.toString("base64");
|
|
1966
|
-
return `[Binary file: ${filename} (application/pdf)]
|
|
1948
|
+
const encoded = content.toString("base64");
|
|
1949
|
+
return `[Binary file: ${filename} (application/pdf)]
|
|
1967
1950
|
Base64: ${encoded}`;
|
|
1968
|
-
|
|
1951
|
+
} catch (error) {
|
|
1969
1952
|
return `Unable to extract text from PDF '${filename}': ${error instanceof Error ? error.message : String(error)}`;
|
|
1970
1953
|
}
|
|
1971
1954
|
}
|
|
@@ -2122,215 +2105,6 @@ var CacheTools = class {
|
|
|
2122
2105
|
return this.hitCache(key);
|
|
2123
2106
|
}
|
|
2124
2107
|
};
|
|
2125
|
-
var MCPNativeTool = class extends BaseTool {
|
|
2126
|
-
clientFactory;
|
|
2127
|
-
originalToolNameValue;
|
|
2128
|
-
serverNameValue;
|
|
2129
|
-
constructor(optionsOrClientFactory, toolName, toolSchema = {}, serverName, originalToolName = null) {
|
|
2130
|
-
const options = typeof optionsOrClientFactory === "function" ? {
|
|
2131
|
-
clientFactory: optionsOrClientFactory,
|
|
2132
|
-
...toolName === void 0 ? {} : { toolName },
|
|
2133
|
-
toolSchema,
|
|
2134
|
-
...serverName === void 0 ? {} : { serverName },
|
|
2135
|
-
originalToolName
|
|
2136
|
-
} : optionsOrClientFactory;
|
|
2137
|
-
const resolvedToolName = options.toolName ?? options.tool_name;
|
|
2138
|
-
const resolvedServerName = options.serverName ?? options.server_name;
|
|
2139
|
-
const resolvedClientFactory = options.clientFactory ?? options.client_factory;
|
|
2140
|
-
if (!resolvedToolName || !resolvedServerName || !resolvedClientFactory) {
|
|
2141
|
-
throw new Error("MCPNativeTool requires clientFactory, toolName, and serverName.");
|
|
2142
|
-
}
|
|
2143
|
-
const schema = options.toolSchema ?? options.tool_schema ?? {};
|
|
2144
|
-
super({
|
|
2145
|
-
name: `${resolvedServerName}_${resolvedToolName}`,
|
|
2146
|
-
description: toolSchemaDescription(schema, resolvedToolName, resolvedServerName),
|
|
2147
|
-
argsSchema: toolSchemaArgs(schema)
|
|
2148
|
-
});
|
|
2149
|
-
this.clientFactory = resolvedClientFactory;
|
|
2150
|
-
this.originalToolNameValue = options.originalToolName ?? options.original_tool_name ?? resolvedToolName;
|
|
2151
|
-
this.serverNameValue = resolvedServerName;
|
|
2152
|
-
}
|
|
2153
|
-
get originalToolName() {
|
|
2154
|
-
return this.originalToolNameValue;
|
|
2155
|
-
}
|
|
2156
|
-
get original_tool_name() {
|
|
2157
|
-
return this.originalToolName;
|
|
2158
|
-
}
|
|
2159
|
-
get serverName() {
|
|
2160
|
-
return this.serverNameValue;
|
|
2161
|
-
}
|
|
2162
|
-
get server_name() {
|
|
2163
|
-
return this.serverName;
|
|
2164
|
-
}
|
|
2165
|
-
_run(args) {
|
|
2166
|
-
return this.runAsync(args);
|
|
2167
|
-
}
|
|
2168
|
-
async _arun(args) {
|
|
2169
|
-
return await this.runAsync(args);
|
|
2170
|
-
}
|
|
2171
|
-
async runAsync(args = {}) {
|
|
2172
|
-
const client = this.clientFactory();
|
|
2173
|
-
if (!isMCPClientLike(client)) {
|
|
2174
|
-
throw new Error("MCPNativeTool clientFactory must return an MCPClient-like object.");
|
|
2175
|
-
}
|
|
2176
|
-
await client.connect();
|
|
2177
|
-
try {
|
|
2178
|
-
return stringifyToolOutput(await client.callTool(this.originalToolName, args));
|
|
2179
|
-
} finally {
|
|
2180
|
-
await client.disconnect();
|
|
2181
|
-
}
|
|
2182
|
-
}
|
|
2183
|
-
async _run_async(args = {}) {
|
|
2184
|
-
return await this.runAsync(args);
|
|
2185
|
-
}
|
|
2186
|
-
};
|
|
2187
|
-
var MCP_WRAPPER_MAX_RETRIES = 3;
|
|
2188
|
-
var MCP_TOOL_EXECUTION_TIMEOUT_SECONDS = 60;
|
|
2189
|
-
var MCPToolWrapper = class extends BaseTool {
|
|
2190
|
-
mcpServerParamsValue;
|
|
2191
|
-
originalToolNameValue;
|
|
2192
|
-
serverNameValue;
|
|
2193
|
-
constructor(optionsOrServerParams, toolName, toolSchema = {}, serverName) {
|
|
2194
|
-
const options = isMCPToolWrapperOptions(optionsOrServerParams) ? optionsOrServerParams : {
|
|
2195
|
-
mcpServerParams: optionsOrServerParams,
|
|
2196
|
-
...toolName === void 0 ? {} : { toolName },
|
|
2197
|
-
toolSchema,
|
|
2198
|
-
...serverName === void 0 ? {} : { serverName }
|
|
2199
|
-
};
|
|
2200
|
-
const params = options.mcpServerParams ?? options.mcp_server_params;
|
|
2201
|
-
const resolvedToolName = options.toolName ?? options.tool_name;
|
|
2202
|
-
const resolvedServerName = options.serverName ?? options.server_name;
|
|
2203
|
-
if (!params || !resolvedToolName || !resolvedServerName) {
|
|
2204
|
-
throw new Error("MCPToolWrapper requires mcpServerParams, toolName, and serverName.");
|
|
2205
|
-
}
|
|
2206
|
-
const schema = options.toolSchema ?? options.tool_schema ?? {};
|
|
2207
|
-
super({
|
|
2208
|
-
name: `${resolvedServerName}_${resolvedToolName}`,
|
|
2209
|
-
description: toolSchemaDescription(schema, resolvedToolName, resolvedServerName),
|
|
2210
|
-
argsSchema: toolSchemaArgs(schema)
|
|
2211
|
-
});
|
|
2212
|
-
this.mcpServerParamsValue = { ...params };
|
|
2213
|
-
this.originalToolNameValue = resolvedToolName;
|
|
2214
|
-
this.serverNameValue = resolvedServerName;
|
|
2215
|
-
}
|
|
2216
|
-
get mcpServerParams() {
|
|
2217
|
-
return { ...this.mcpServerParamsValue };
|
|
2218
|
-
}
|
|
2219
|
-
get mcp_server_params() {
|
|
2220
|
-
return this.mcpServerParams;
|
|
2221
|
-
}
|
|
2222
|
-
get originalToolName() {
|
|
2223
|
-
return this.originalToolNameValue;
|
|
2224
|
-
}
|
|
2225
|
-
get original_tool_name() {
|
|
2226
|
-
return this.originalToolName;
|
|
2227
|
-
}
|
|
2228
|
-
get serverName() {
|
|
2229
|
-
return this.serverNameValue;
|
|
2230
|
-
}
|
|
2231
|
-
get server_name() {
|
|
2232
|
-
return this.serverName;
|
|
2233
|
-
}
|
|
2234
|
-
_run(args) {
|
|
2235
|
-
return this._run_async(args);
|
|
2236
|
-
}
|
|
2237
|
-
async _arun(args) {
|
|
2238
|
-
return await this._run_async(args);
|
|
2239
|
-
}
|
|
2240
|
-
async runAsync(args = {}) {
|
|
2241
|
-
return await this._execute_tool(args);
|
|
2242
|
-
}
|
|
2243
|
-
async _run_async(args = {}) {
|
|
2244
|
-
return await this._retry_with_exponential_backoff(this._execute_tool_with_timeout.bind(this), args);
|
|
2245
|
-
}
|
|
2246
|
-
async _retry_with_exponential_backoff(operationFunc, args = {}) {
|
|
2247
|
-
let lastError = "";
|
|
2248
|
-
for (let attempt = 0; attempt < MCP_WRAPPER_MAX_RETRIES; attempt += 1) {
|
|
2249
|
-
const [result, error, shouldRetry] = await this._execute_single_attempt(operationFunc, args);
|
|
2250
|
-
if (result !== null) {
|
|
2251
|
-
return result;
|
|
2252
|
-
}
|
|
2253
|
-
if (!shouldRetry) {
|
|
2254
|
-
return error;
|
|
2255
|
-
}
|
|
2256
|
-
lastError = error;
|
|
2257
|
-
if (attempt < MCP_WRAPPER_MAX_RETRIES - 1) {
|
|
2258
|
-
await waitForMCPWrapperRetry(2 ** attempt);
|
|
2259
|
-
}
|
|
2260
|
-
}
|
|
2261
|
-
return `MCP tool execution failed after ${String(MCP_WRAPPER_MAX_RETRIES)} attempts: ${lastError}`;
|
|
2262
|
-
}
|
|
2263
|
-
async _execute_single_attempt(operationFunc, args = {}) {
|
|
2264
|
-
try {
|
|
2265
|
-
return [await operationFunc(args), "", false];
|
|
2266
|
-
} catch (error) {
|
|
2267
|
-
const classified = classifyMCPWrapperError(error, this.originalToolName);
|
|
2268
|
-
return [null, classified.message, classified.retryable];
|
|
2269
|
-
}
|
|
2270
|
-
}
|
|
2271
|
-
async _execute_tool_with_timeout(args = {}) {
|
|
2272
|
-
return await withMCPWrapperTimeout(this._execute_tool(args));
|
|
2273
|
-
}
|
|
2274
|
-
async _execute_tool(args = {}) {
|
|
2275
|
-
return await this._do_mcp_call(args);
|
|
2276
|
-
}
|
|
2277
|
-
async _do_mcp_call(args = {}) {
|
|
2278
|
-
const { MCPClient: MCPClient2, HTTPTransport: HTTPTransport2 } = await import("./mcp-DS7UMYAM.js");
|
|
2279
|
-
const url = this.mcpServerParamsValue.url;
|
|
2280
|
-
if (typeof url !== "string") {
|
|
2281
|
-
throw new Error("MCPToolWrapper requires an mcpServerParams.url string.");
|
|
2282
|
-
}
|
|
2283
|
-
const client = new MCPClient2(new HTTPTransport2({ url }), {
|
|
2284
|
-
connectTimeout: 15,
|
|
2285
|
-
executionTimeout: 60,
|
|
2286
|
-
discoveryTimeout: 15,
|
|
2287
|
-
maxRetries: 3
|
|
2288
|
-
});
|
|
2289
|
-
await client.connect();
|
|
2290
|
-
try {
|
|
2291
|
-
return await client.callTool(this.originalToolName, args);
|
|
2292
|
-
} finally {
|
|
2293
|
-
await client.disconnect();
|
|
2294
|
-
}
|
|
2295
|
-
}
|
|
2296
|
-
};
|
|
2297
|
-
function classifyMCPWrapperError(error, toolName) {
|
|
2298
|
-
const message = error instanceof Error ? error.message : stringifyToolOutput(error);
|
|
2299
|
-
const lower = message.toLowerCase();
|
|
2300
|
-
if (lower.includes("authentication") || lower.includes("unauthorized")) {
|
|
2301
|
-
return { message: `Authentication failed for MCP server: ${message}`, retryable: false };
|
|
2302
|
-
}
|
|
2303
|
-
if (lower.includes("not found")) {
|
|
2304
|
-
return { message: `Tool '${toolName}' not found on MCP server`, retryable: false };
|
|
2305
|
-
}
|
|
2306
|
-
if (lower.includes("connection") || lower.includes("network")) {
|
|
2307
|
-
return { message: `Network connection failed: ${message}`, retryable: true };
|
|
2308
|
-
}
|
|
2309
|
-
if (lower.includes("json") || lower.includes("parsing")) {
|
|
2310
|
-
return { message: `Server response parsing error: ${message}`, retryable: true };
|
|
2311
|
-
}
|
|
2312
|
-
return { message: `MCP execution error: ${message}`, retryable: false };
|
|
2313
|
-
}
|
|
2314
|
-
async function waitForMCPWrapperRetry(seconds) {
|
|
2315
|
-
await new Promise((resolve) => {
|
|
2316
|
-
setTimeout(resolve, seconds * 1e3);
|
|
2317
|
-
});
|
|
2318
|
-
}
|
|
2319
|
-
async function withMCPWrapperTimeout(operation) {
|
|
2320
|
-
let timeout;
|
|
2321
|
-
try {
|
|
2322
|
-
return await Promise.race([
|
|
2323
|
-
operation,
|
|
2324
|
-
new Promise((_, reject) => {
|
|
2325
|
-
timeout = setTimeout(() => {
|
|
2326
|
-
reject(new Error(`Connection timed out after ${String(MCP_TOOL_EXECUTION_TIMEOUT_SECONDS)} seconds`));
|
|
2327
|
-
}, MCP_TOOL_EXECUTION_TIMEOUT_SECONDS * 1e3);
|
|
2328
|
-
})
|
|
2329
|
-
]);
|
|
2330
|
-
} finally {
|
|
2331
|
-
clearTimeout(timeout);
|
|
2332
|
-
}
|
|
2333
|
-
}
|
|
2334
2108
|
var ToolUsageError = class extends Error {
|
|
2335
2109
|
constructor(message) {
|
|
2336
2110
|
super(message);
|
|
@@ -3300,56 +3074,6 @@ function inferFunctionDescription(func, name) {
|
|
|
3300
3074
|
}
|
|
3301
3075
|
return `Tool generated from function ${name}.`;
|
|
3302
3076
|
}
|
|
3303
|
-
function isMCPClientLike(value) {
|
|
3304
|
-
return !!value && typeof value === "object" && typeof value.connect === "function" && typeof value.disconnect === "function" && typeof value.callTool === "function";
|
|
3305
|
-
}
|
|
3306
|
-
function isMCPToolWrapperOptions(value) {
|
|
3307
|
-
return "mcpServerParams" in value || "mcp_server_params" in value || "toolName" in value || "tool_name" in value || "toolSchema" in value || "tool_schema" in value || "serverName" in value || "server_name" in value;
|
|
3308
|
-
}
|
|
3309
|
-
function toolSchemaDescription(schema, toolName, serverName) {
|
|
3310
|
-
return typeof schema.description === "string" && schema.description.trim() ? schema.description : `Tool ${toolName} from ${serverName}`;
|
|
3311
|
-
}
|
|
3312
|
-
function toolSchemaArgs(schema) {
|
|
3313
|
-
const argsSchema = schema.argsSchema ?? schema.args_schema;
|
|
3314
|
-
if (argsSchema && typeof argsSchema === "object" && !Array.isArray(argsSchema)) {
|
|
3315
|
-
return argsSchema;
|
|
3316
|
-
}
|
|
3317
|
-
const inputSchema = schema.inputSchema ?? schema.input_schema;
|
|
3318
|
-
if (!inputSchema || typeof inputSchema !== "object" || Array.isArray(inputSchema)) {
|
|
3319
|
-
return {};
|
|
3320
|
-
}
|
|
3321
|
-
const record = inputSchema;
|
|
3322
|
-
const properties = record.properties;
|
|
3323
|
-
if (!properties || typeof properties !== "object" || Array.isArray(properties)) {
|
|
3324
|
-
return {};
|
|
3325
|
-
}
|
|
3326
|
-
const required = new Set(Array.isArray(record.required) ? record.required.filter((item) => typeof item === "string") : []);
|
|
3327
|
-
return Object.fromEntries(
|
|
3328
|
-
Object.entries(properties).map(([name, value]) => {
|
|
3329
|
-
const property = value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
3330
|
-
const spec = {
|
|
3331
|
-
type: normalizeJsonSchemaType(property.type),
|
|
3332
|
-
required: required.has(name)
|
|
3333
|
-
};
|
|
3334
|
-
if (typeof property.description === "string") {
|
|
3335
|
-
spec.description = property.description;
|
|
3336
|
-
}
|
|
3337
|
-
if ("default" in property) {
|
|
3338
|
-
spec.default = property.default;
|
|
3339
|
-
}
|
|
3340
|
-
return [name, spec];
|
|
3341
|
-
})
|
|
3342
|
-
);
|
|
3343
|
-
}
|
|
3344
|
-
function normalizeJsonSchemaType(value) {
|
|
3345
|
-
if (value === "string" || value === "number" || value === "boolean" || value === "object" || value === "array") {
|
|
3346
|
-
return value;
|
|
3347
|
-
}
|
|
3348
|
-
if (value === "integer") {
|
|
3349
|
-
return "number";
|
|
3350
|
-
}
|
|
3351
|
-
return "unknown";
|
|
3352
|
-
}
|
|
3353
3077
|
function stableStringify(value) {
|
|
3354
3078
|
if (Array.isArray(value)) {
|
|
3355
3079
|
return `[${value.map((item) => stableStringify(item)).join(",")}]`;
|
|
@@ -3360,1180 +3084,6 @@ function stableStringify(value) {
|
|
|
3360
3084
|
return JSON.stringify(value);
|
|
3361
3085
|
}
|
|
3362
3086
|
|
|
3363
|
-
// src/mcp.ts
|
|
3364
|
-
var TransportType = {
|
|
3365
|
-
STDIO: "stdio",
|
|
3366
|
-
HTTP: "http",
|
|
3367
|
-
STREAMABLE_HTTP: "streamable-http",
|
|
3368
|
-
SSE: "sse"
|
|
3369
|
-
};
|
|
3370
|
-
var MCPReadStream = Object.freeze({ kind: "MCPReadStream" });
|
|
3371
|
-
var MCPWriteStream = Object.freeze({ kind: "MCPWriteStream" });
|
|
3372
|
-
var ToolFilterContext = class {
|
|
3373
|
-
agent;
|
|
3374
|
-
serverName;
|
|
3375
|
-
server_name;
|
|
3376
|
-
runContext;
|
|
3377
|
-
run_context;
|
|
3378
|
-
constructor(options) {
|
|
3379
|
-
this.agent = options.agent;
|
|
3380
|
-
this.serverName = options.serverName ?? options.server_name ?? "";
|
|
3381
|
-
this.server_name = this.serverName;
|
|
3382
|
-
this.runContext = options.runContext ?? options.run_context ?? null;
|
|
3383
|
-
this.run_context = this.runContext;
|
|
3384
|
-
}
|
|
3385
|
-
};
|
|
3386
|
-
var ToolFilter = Object.freeze({ kind: "ToolFilter" });
|
|
3387
|
-
var StaticToolFilter = class {
|
|
3388
|
-
allowedToolNames;
|
|
3389
|
-
allowed_tool_names;
|
|
3390
|
-
blockedToolNames;
|
|
3391
|
-
blocked_tool_names;
|
|
3392
|
-
constructor(options = {}) {
|
|
3393
|
-
this.allowedToolNames = new Set(options.allowedToolNames ?? options.allowed_tool_names ?? []);
|
|
3394
|
-
this.allowed_tool_names = this.allowedToolNames;
|
|
3395
|
-
this.blockedToolNames = new Set(options.blockedToolNames ?? options.blocked_tool_names ?? []);
|
|
3396
|
-
this.blocked_tool_names = this.blockedToolNames;
|
|
3397
|
-
}
|
|
3398
|
-
filter(tool) {
|
|
3399
|
-
const toolName = typeof tool.name === "string" ? tool.name : "";
|
|
3400
|
-
if (this.blockedToolNames.size > 0 && this.blockedToolNames.has(toolName)) {
|
|
3401
|
-
return false;
|
|
3402
|
-
}
|
|
3403
|
-
if (this.allowedToolNames.size > 0) {
|
|
3404
|
-
return this.allowedToolNames.has(toolName);
|
|
3405
|
-
}
|
|
3406
|
-
return true;
|
|
3407
|
-
}
|
|
3408
|
-
call(tool) {
|
|
3409
|
-
return this.filter(tool);
|
|
3410
|
-
}
|
|
3411
|
-
__call__(tool) {
|
|
3412
|
-
return this.filter(tool);
|
|
3413
|
-
}
|
|
3414
|
-
};
|
|
3415
|
-
function createStaticToolFilter(allowedToolNames = null, blockedToolNames = null) {
|
|
3416
|
-
const filter = new StaticToolFilter({ allowedToolNames, blockedToolNames });
|
|
3417
|
-
return (tool) => filter.filter(tool);
|
|
3418
|
-
}
|
|
3419
|
-
var create_static_tool_filter = createStaticToolFilter;
|
|
3420
|
-
function createDynamicToolFilter(filterFunc) {
|
|
3421
|
-
return filterFunc;
|
|
3422
|
-
}
|
|
3423
|
-
var create_dynamic_tool_filter = createDynamicToolFilter;
|
|
3424
|
-
var MCPServerStdio = class {
|
|
3425
|
-
command;
|
|
3426
|
-
args;
|
|
3427
|
-
env;
|
|
3428
|
-
toolFilter;
|
|
3429
|
-
tool_filter;
|
|
3430
|
-
cacheToolsList;
|
|
3431
|
-
cache_tools_list;
|
|
3432
|
-
constructor(options) {
|
|
3433
|
-
this.command = options.command;
|
|
3434
|
-
this.args = options.args ? [...options.args] : [];
|
|
3435
|
-
this.env = options.env ? { ...options.env } : null;
|
|
3436
|
-
this.toolFilter = options.toolFilter ?? options.tool_filter ?? null;
|
|
3437
|
-
this.tool_filter = this.toolFilter;
|
|
3438
|
-
this.cacheToolsList = options.cacheToolsList ?? options.cache_tools_list ?? false;
|
|
3439
|
-
this.cache_tools_list = this.cacheToolsList;
|
|
3440
|
-
}
|
|
3441
|
-
};
|
|
3442
|
-
var MCPServerHTTP = class {
|
|
3443
|
-
url;
|
|
3444
|
-
headers;
|
|
3445
|
-
streamable;
|
|
3446
|
-
toolFilter;
|
|
3447
|
-
tool_filter;
|
|
3448
|
-
cacheToolsList;
|
|
3449
|
-
cache_tools_list;
|
|
3450
|
-
constructor(options) {
|
|
3451
|
-
this.url = options.url;
|
|
3452
|
-
this.headers = options.headers ? { ...options.headers } : null;
|
|
3453
|
-
this.streamable = options.streamable ?? true;
|
|
3454
|
-
this.toolFilter = options.toolFilter ?? options.tool_filter ?? null;
|
|
3455
|
-
this.tool_filter = this.toolFilter;
|
|
3456
|
-
this.cacheToolsList = options.cacheToolsList ?? options.cache_tools_list ?? false;
|
|
3457
|
-
this.cache_tools_list = this.cacheToolsList;
|
|
3458
|
-
}
|
|
3459
|
-
};
|
|
3460
|
-
var MCPServerSSE = class {
|
|
3461
|
-
url;
|
|
3462
|
-
headers;
|
|
3463
|
-
toolFilter;
|
|
3464
|
-
tool_filter;
|
|
3465
|
-
cacheToolsList;
|
|
3466
|
-
cache_tools_list;
|
|
3467
|
-
constructor(options) {
|
|
3468
|
-
this.url = options.url;
|
|
3469
|
-
this.headers = options.headers ? { ...options.headers } : null;
|
|
3470
|
-
this.toolFilter = options.toolFilter ?? options.tool_filter ?? null;
|
|
3471
|
-
this.tool_filter = this.toolFilter;
|
|
3472
|
-
this.cacheToolsList = options.cacheToolsList ?? options.cache_tools_list ?? false;
|
|
3473
|
-
this.cache_tools_list = this.cacheToolsList;
|
|
3474
|
-
}
|
|
3475
|
-
};
|
|
3476
|
-
var MCPServerConfig = Object.freeze({ kind: "MCPServerConfig" });
|
|
3477
|
-
var BaseTransport = class {
|
|
3478
|
-
readStreamValue = null;
|
|
3479
|
-
writeStreamValue = null;
|
|
3480
|
-
connectedValue = false;
|
|
3481
|
-
sdkTransportValue = null;
|
|
3482
|
-
get transport_type() {
|
|
3483
|
-
return this.transportType;
|
|
3484
|
-
}
|
|
3485
|
-
get connected() {
|
|
3486
|
-
return this.connectedValue;
|
|
3487
|
-
}
|
|
3488
|
-
get readStream() {
|
|
3489
|
-
if (this.readStreamValue === null) {
|
|
3490
|
-
throw new Error("Transport not connected. Call connect() first.");
|
|
3491
|
-
}
|
|
3492
|
-
return this.readStreamValue;
|
|
3493
|
-
}
|
|
3494
|
-
get read_stream() {
|
|
3495
|
-
return this.readStream;
|
|
3496
|
-
}
|
|
3497
|
-
get writeStream() {
|
|
3498
|
-
if (this.writeStreamValue === null) {
|
|
3499
|
-
throw new Error("Transport not connected. Call connect() first.");
|
|
3500
|
-
}
|
|
3501
|
-
return this.writeStreamValue;
|
|
3502
|
-
}
|
|
3503
|
-
get write_stream() {
|
|
3504
|
-
return this.writeStream;
|
|
3505
|
-
}
|
|
3506
|
-
async connect() {
|
|
3507
|
-
if (this.connectedValue) {
|
|
3508
|
-
return this;
|
|
3509
|
-
}
|
|
3510
|
-
const transport = this.getSdkTransport();
|
|
3511
|
-
await transport.start();
|
|
3512
|
-
this.setStreams(transport, transport);
|
|
3513
|
-
return this;
|
|
3514
|
-
}
|
|
3515
|
-
async disconnect() {
|
|
3516
|
-
const transport = this.sdkTransportValue;
|
|
3517
|
-
this.clearStreams();
|
|
3518
|
-
if (transport) {
|
|
3519
|
-
await transport.close();
|
|
3520
|
-
}
|
|
3521
|
-
}
|
|
3522
|
-
async aenter() {
|
|
3523
|
-
return await this.connect();
|
|
3524
|
-
}
|
|
3525
|
-
async __aenter__() {
|
|
3526
|
-
return await this.aenter();
|
|
3527
|
-
}
|
|
3528
|
-
async aexit(_excType = null, _excVal = null, _excTb = null) {
|
|
3529
|
-
void _excType;
|
|
3530
|
-
void _excVal;
|
|
3531
|
-
void _excTb;
|
|
3532
|
-
await this.disconnect();
|
|
3533
|
-
}
|
|
3534
|
-
async __aexit__(excType = null, excVal = null, excTb = null) {
|
|
3535
|
-
await this.aexit(excType, excVal, excTb);
|
|
3536
|
-
}
|
|
3537
|
-
setStreams(read, write) {
|
|
3538
|
-
this.readStreamValue = read;
|
|
3539
|
-
this.writeStreamValue = write;
|
|
3540
|
-
this.connectedValue = true;
|
|
3541
|
-
}
|
|
3542
|
-
_set_streams(read, write) {
|
|
3543
|
-
this.setStreams(read, write);
|
|
3544
|
-
}
|
|
3545
|
-
clearStreams() {
|
|
3546
|
-
this.readStreamValue = null;
|
|
3547
|
-
this.writeStreamValue = null;
|
|
3548
|
-
this.connectedValue = false;
|
|
3549
|
-
}
|
|
3550
|
-
_clear_streams() {
|
|
3551
|
-
this.clearStreams();
|
|
3552
|
-
}
|
|
3553
|
-
markConnectedForClient() {
|
|
3554
|
-
const transport = this.getSdkTransport();
|
|
3555
|
-
this.setStreams(transport, transport);
|
|
3556
|
-
}
|
|
3557
|
-
clearConnectedForClient() {
|
|
3558
|
-
this.clearStreams();
|
|
3559
|
-
this.sdkTransportValue = null;
|
|
3560
|
-
}
|
|
3561
|
-
getSdkTransport() {
|
|
3562
|
-
this.sdkTransportValue ??= this.createSdkTransport();
|
|
3563
|
-
return this.sdkTransportValue;
|
|
3564
|
-
}
|
|
3565
|
-
};
|
|
3566
|
-
var HTTPTransport = class extends BaseTransport {
|
|
3567
|
-
url;
|
|
3568
|
-
headers;
|
|
3569
|
-
streamable;
|
|
3570
|
-
constructor(options, headers = null, streamable = true) {
|
|
3571
|
-
super();
|
|
3572
|
-
if (typeof options === "string") {
|
|
3573
|
-
this.url = options;
|
|
3574
|
-
this.headers = headers ? { ...headers } : {};
|
|
3575
|
-
this.streamable = streamable;
|
|
3576
|
-
} else {
|
|
3577
|
-
this.url = options.url;
|
|
3578
|
-
this.headers = options.headers ? { ...options.headers } : {};
|
|
3579
|
-
this.streamable = options.streamable ?? true;
|
|
3580
|
-
}
|
|
3581
|
-
}
|
|
3582
|
-
get transportType() {
|
|
3583
|
-
return this.streamable ? TransportType.STREAMABLE_HTTP : TransportType.HTTP;
|
|
3584
|
-
}
|
|
3585
|
-
createSdkTransport() {
|
|
3586
|
-
const headers = { ...this.headers };
|
|
3587
|
-
const options = Object.keys(headers).length > 0 ? { requestInit: { headers } } : void 0;
|
|
3588
|
-
return new StreamableHTTPClientTransport(new URL(this.url), options);
|
|
3589
|
-
}
|
|
3590
|
-
};
|
|
3591
|
-
var SSETransport = class extends BaseTransport {
|
|
3592
|
-
url;
|
|
3593
|
-
headers;
|
|
3594
|
-
constructor(options, headers = null) {
|
|
3595
|
-
super();
|
|
3596
|
-
if (typeof options === "string") {
|
|
3597
|
-
this.url = options;
|
|
3598
|
-
this.headers = headers ? { ...headers } : {};
|
|
3599
|
-
} else {
|
|
3600
|
-
this.url = options.url;
|
|
3601
|
-
this.headers = options.headers ? { ...options.headers } : {};
|
|
3602
|
-
}
|
|
3603
|
-
}
|
|
3604
|
-
get transportType() {
|
|
3605
|
-
return TransportType.SSE;
|
|
3606
|
-
}
|
|
3607
|
-
createSdkTransport() {
|
|
3608
|
-
const headers = { ...this.headers };
|
|
3609
|
-
const options = Object.keys(headers).length > 0 ? {
|
|
3610
|
-
requestInit: { headers },
|
|
3611
|
-
eventSourceInit: {
|
|
3612
|
-
fetch: (url, init) => fetch(url, { ...init, headers: { ...headers, ...headersFromInit(init?.headers) } })
|
|
3613
|
-
}
|
|
3614
|
-
} : void 0;
|
|
3615
|
-
return new SSEClientTransport(new URL(this.url), options);
|
|
3616
|
-
}
|
|
3617
|
-
};
|
|
3618
|
-
var StdioTransport = class extends BaseTransport {
|
|
3619
|
-
command;
|
|
3620
|
-
args;
|
|
3621
|
-
env;
|
|
3622
|
-
constructor(options, args = null, env = null) {
|
|
3623
|
-
super();
|
|
3624
|
-
if (typeof options === "string") {
|
|
3625
|
-
this.command = options;
|
|
3626
|
-
this.args = args ? [...args] : [];
|
|
3627
|
-
this.env = env ? { ...env } : {};
|
|
3628
|
-
} else {
|
|
3629
|
-
this.command = options.command;
|
|
3630
|
-
this.args = options.args ? [...options.args] : [];
|
|
3631
|
-
this.env = options.env ? { ...options.env } : {};
|
|
3632
|
-
}
|
|
3633
|
-
}
|
|
3634
|
-
get transportType() {
|
|
3635
|
-
return TransportType.STDIO;
|
|
3636
|
-
}
|
|
3637
|
-
createSdkTransport() {
|
|
3638
|
-
return new StdioClientTransport({
|
|
3639
|
-
command: this.command,
|
|
3640
|
-
args: [...this.args],
|
|
3641
|
-
env: { ...this.env }
|
|
3642
|
-
});
|
|
3643
|
-
}
|
|
3644
|
-
};
|
|
3645
|
-
function isMCPServerConfig(value) {
|
|
3646
|
-
return value instanceof MCPServerStdio || value instanceof MCPServerHTTP || value instanceof MCPServerSSE;
|
|
3647
|
-
}
|
|
3648
|
-
var is_mcp_server_config = isMCPServerConfig;
|
|
3649
|
-
var MCP_CONNECTION_TIMEOUT = 30;
|
|
3650
|
-
var MCP_TOOL_EXECUTION_TIMEOUT = 30;
|
|
3651
|
-
var MCP_DISCOVERY_TIMEOUT = 30;
|
|
3652
|
-
var MCP_MAX_RETRIES = 3;
|
|
3653
|
-
var _MCPToolResult = class {
|
|
3654
|
-
content;
|
|
3655
|
-
isError;
|
|
3656
|
-
is_error;
|
|
3657
|
-
constructor(content, isError = false) {
|
|
3658
|
-
this.content = content;
|
|
3659
|
-
this.isError = isError;
|
|
3660
|
-
this.is_error = isError;
|
|
3661
|
-
}
|
|
3662
|
-
};
|
|
3663
|
-
var MCP_SCHEMA_CACHE_TTL_MS = 3e5;
|
|
3664
|
-
var mcpSchemaCache = /* @__PURE__ */ new Map();
|
|
3665
|
-
var MCPClient = class {
|
|
3666
|
-
transport;
|
|
3667
|
-
connectTimeout;
|
|
3668
|
-
connect_timeout;
|
|
3669
|
-
executionTimeout;
|
|
3670
|
-
execution_timeout;
|
|
3671
|
-
discoveryTimeout;
|
|
3672
|
-
discovery_timeout;
|
|
3673
|
-
maxRetries;
|
|
3674
|
-
max_retries;
|
|
3675
|
-
cacheToolsList;
|
|
3676
|
-
cache_tools_list;
|
|
3677
|
-
client = null;
|
|
3678
|
-
initialized = false;
|
|
3679
|
-
wasConnected = false;
|
|
3680
|
-
constructor(transport, options = {}) {
|
|
3681
|
-
this.transport = transport;
|
|
3682
|
-
this.connectTimeout = options.connectTimeout ?? options.connect_timeout ?? MCP_CONNECTION_TIMEOUT;
|
|
3683
|
-
this.connect_timeout = this.connectTimeout;
|
|
3684
|
-
this.executionTimeout = options.executionTimeout ?? options.execution_timeout ?? MCP_TOOL_EXECUTION_TIMEOUT;
|
|
3685
|
-
this.execution_timeout = this.executionTimeout;
|
|
3686
|
-
this.discoveryTimeout = options.discoveryTimeout ?? options.discovery_timeout ?? MCP_DISCOVERY_TIMEOUT;
|
|
3687
|
-
this.discovery_timeout = this.discoveryTimeout;
|
|
3688
|
-
this.maxRetries = options.maxRetries ?? options.max_retries ?? MCP_MAX_RETRIES;
|
|
3689
|
-
this.max_retries = this.maxRetries;
|
|
3690
|
-
this.cacheToolsList = options.cacheToolsList ?? options.cache_tools_list ?? false;
|
|
3691
|
-
this.cache_tools_list = this.cacheToolsList;
|
|
3692
|
-
}
|
|
3693
|
-
get connected() {
|
|
3694
|
-
return this.initialized;
|
|
3695
|
-
}
|
|
3696
|
-
get session() {
|
|
3697
|
-
if (!this.client || !this.initialized) {
|
|
3698
|
-
throw new Error("Client not connected. Call connect() first.");
|
|
3699
|
-
}
|
|
3700
|
-
return this.client;
|
|
3701
|
-
}
|
|
3702
|
-
async connect() {
|
|
3703
|
-
if (this.connected) {
|
|
3704
|
-
return this;
|
|
3705
|
-
}
|
|
3706
|
-
const [serverName, serverUrl, transportType] = this.getServerInfo();
|
|
3707
|
-
const startedAt = /* @__PURE__ */ new Date();
|
|
3708
|
-
const isReconnect = this.wasConnected;
|
|
3709
|
-
crewaiEventBus.emit(this, new MCPConnectionStartedEvent({
|
|
3710
|
-
server_name: serverName,
|
|
3711
|
-
server_url: serverUrl,
|
|
3712
|
-
transport_type: transportType,
|
|
3713
|
-
is_reconnect: isReconnect,
|
|
3714
|
-
connect_timeout: this.connectTimeout
|
|
3715
|
-
}));
|
|
3716
|
-
try {
|
|
3717
|
-
const client = new Client({ name: "@crewai-ts/core", version: "0.0.0" }, { capabilities: {} });
|
|
3718
|
-
await withTimeout(client.connect(this.transport.getSdkTransport()), this.connectTimeout, "MCP connection timed out");
|
|
3719
|
-
this.client = client;
|
|
3720
|
-
this.initialized = true;
|
|
3721
|
-
this.wasConnected = true;
|
|
3722
|
-
this.transport.markConnectedForClient();
|
|
3723
|
-
const completedAt = /* @__PURE__ */ new Date();
|
|
3724
|
-
crewaiEventBus.emit(this, new MCPConnectionCompletedEvent({
|
|
3725
|
-
server_name: serverName,
|
|
3726
|
-
server_url: serverUrl,
|
|
3727
|
-
transport_type: transportType,
|
|
3728
|
-
started_at: startedAt,
|
|
3729
|
-
completed_at: completedAt,
|
|
3730
|
-
connection_duration_ms: completedAt.getTime() - startedAt.getTime(),
|
|
3731
|
-
is_reconnect: isReconnect
|
|
3732
|
-
}));
|
|
3733
|
-
return this;
|
|
3734
|
-
} catch (error) {
|
|
3735
|
-
await this.cleanupOnError();
|
|
3736
|
-
const failedAt = /* @__PURE__ */ new Date();
|
|
3737
|
-
crewaiEventBus.emit(this, new MCPConnectionFailedEvent({
|
|
3738
|
-
server_name: serverName,
|
|
3739
|
-
server_url: serverUrl,
|
|
3740
|
-
transport_type: transportType,
|
|
3741
|
-
error,
|
|
3742
|
-
error_type: classifyMCPError(error),
|
|
3743
|
-
started_at: startedAt,
|
|
3744
|
-
failed_at: failedAt
|
|
3745
|
-
}));
|
|
3746
|
-
throw new Error(`Failed to connect to MCP server: ${formatMCPError(error)}`, { cause: error });
|
|
3747
|
-
}
|
|
3748
|
-
}
|
|
3749
|
-
async disconnect() {
|
|
3750
|
-
if (!this.client && !this.transport.connected) {
|
|
3751
|
-
return;
|
|
3752
|
-
}
|
|
3753
|
-
try {
|
|
3754
|
-
await this.client?.close();
|
|
3755
|
-
} finally {
|
|
3756
|
-
this.client = null;
|
|
3757
|
-
this.initialized = false;
|
|
3758
|
-
this.transport.clearConnectedForClient();
|
|
3759
|
-
}
|
|
3760
|
-
}
|
|
3761
|
-
async aenter() {
|
|
3762
|
-
return await this.connect();
|
|
3763
|
-
}
|
|
3764
|
-
async __aenter__() {
|
|
3765
|
-
return await this.aenter();
|
|
3766
|
-
}
|
|
3767
|
-
async aexit(_excType = null, _excVal = null, _excTb = null) {
|
|
3768
|
-
void _excType;
|
|
3769
|
-
void _excVal;
|
|
3770
|
-
void _excTb;
|
|
3771
|
-
await this.disconnect();
|
|
3772
|
-
}
|
|
3773
|
-
async __aexit__(excType = null, excVal = null, excTb = null) {
|
|
3774
|
-
await this.aexit(excType, excVal, excTb);
|
|
3775
|
-
}
|
|
3776
|
-
async listTools(useCache = null) {
|
|
3777
|
-
if (!this.connected) {
|
|
3778
|
-
await this.connect();
|
|
3779
|
-
}
|
|
3780
|
-
const shouldUseCache = useCache ?? this.cacheToolsList;
|
|
3781
|
-
const cacheKey = this.getCacheKey("tools");
|
|
3782
|
-
if (shouldUseCache) {
|
|
3783
|
-
const cached = mcpSchemaCache.get(cacheKey);
|
|
3784
|
-
if (cached && Date.now() - cached.createdAt < MCP_SCHEMA_CACHE_TTL_MS) {
|
|
3785
|
-
return cached.tools.map((tool) => ({ ...tool }));
|
|
3786
|
-
}
|
|
3787
|
-
}
|
|
3788
|
-
const tools = await this.retryOperation(async () => await this.listToolsImpl(), this.discoveryTimeout);
|
|
3789
|
-
if (shouldUseCache) {
|
|
3790
|
-
mcpSchemaCache.set(cacheKey, { tools, createdAt: Date.now() });
|
|
3791
|
-
}
|
|
3792
|
-
return tools;
|
|
3793
|
-
}
|
|
3794
|
-
async list_tools(useCache = null) {
|
|
3795
|
-
return await this.listTools(useCache);
|
|
3796
|
-
}
|
|
3797
|
-
async listToolsImpl() {
|
|
3798
|
-
const result = await withTimeout(this.session.listTools(), this.discoveryTimeout, "MCP tool discovery timed out");
|
|
3799
|
-
return result.tools.map((tool) => ({
|
|
3800
|
-
name: sanitizeToolName(tool.name),
|
|
3801
|
-
original_name: tool.name,
|
|
3802
|
-
description: tool.description ?? "",
|
|
3803
|
-
inputSchema: tool.inputSchema,
|
|
3804
|
-
...tool.outputSchema ? { outputSchema: tool.outputSchema } : {},
|
|
3805
|
-
...tool.annotations ? { annotations: tool.annotations } : {}
|
|
3806
|
-
}));
|
|
3807
|
-
}
|
|
3808
|
-
async _list_tools_impl() {
|
|
3809
|
-
return await this.listToolsImpl();
|
|
3810
|
-
}
|
|
3811
|
-
async callTool(toolName, args = null) {
|
|
3812
|
-
if (!this.connected) {
|
|
3813
|
-
await this.connect();
|
|
3814
|
-
}
|
|
3815
|
-
const cleanedArgs = cleanToolArguments(args ?? {});
|
|
3816
|
-
const [serverName, serverUrl, transportType] = this.getServerInfo();
|
|
3817
|
-
const startedAt = /* @__PURE__ */ new Date();
|
|
3818
|
-
crewaiEventBus.emit(this, new MCPToolExecutionStartedEvent({
|
|
3819
|
-
server_name: serverName,
|
|
3820
|
-
server_url: serverUrl,
|
|
3821
|
-
transport_type: transportType,
|
|
3822
|
-
tool_name: toolName,
|
|
3823
|
-
tool_args: cleanedArgs
|
|
3824
|
-
}));
|
|
3825
|
-
try {
|
|
3826
|
-
const toolResult = await this.retryOperation(
|
|
3827
|
-
async () => await this.callToolImpl(toolName, cleanedArgs),
|
|
3828
|
-
this.executionTimeout
|
|
3829
|
-
);
|
|
3830
|
-
const content = toolResult.content;
|
|
3831
|
-
const finishedAt = /* @__PURE__ */ new Date();
|
|
3832
|
-
if (toolResult.isError) {
|
|
3833
|
-
crewaiEventBus.emit(this, new MCPToolExecutionFailedEvent({
|
|
3834
|
-
server_name: serverName,
|
|
3835
|
-
server_url: serverUrl,
|
|
3836
|
-
transport_type: transportType,
|
|
3837
|
-
tool_name: toolName,
|
|
3838
|
-
tool_args: cleanedArgs,
|
|
3839
|
-
error: content,
|
|
3840
|
-
error_type: "tool_error",
|
|
3841
|
-
started_at: startedAt,
|
|
3842
|
-
failed_at: finishedAt
|
|
3843
|
-
}));
|
|
3844
|
-
} else {
|
|
3845
|
-
crewaiEventBus.emit(this, new MCPToolExecutionCompletedEvent({
|
|
3846
|
-
server_name: serverName,
|
|
3847
|
-
server_url: serverUrl,
|
|
3848
|
-
transport_type: transportType,
|
|
3849
|
-
tool_name: toolName,
|
|
3850
|
-
tool_args: cleanedArgs,
|
|
3851
|
-
result: content,
|
|
3852
|
-
started_at: startedAt,
|
|
3853
|
-
completed_at: finishedAt,
|
|
3854
|
-
execution_duration_ms: finishedAt.getTime() - startedAt.getTime()
|
|
3855
|
-
}));
|
|
3856
|
-
}
|
|
3857
|
-
return content;
|
|
3858
|
-
} catch (error) {
|
|
3859
|
-
const failedAt = /* @__PURE__ */ new Date();
|
|
3860
|
-
crewaiEventBus.emit(this, new MCPToolExecutionFailedEvent({
|
|
3861
|
-
server_name: serverName,
|
|
3862
|
-
server_url: serverUrl,
|
|
3863
|
-
transport_type: transportType,
|
|
3864
|
-
tool_name: toolName,
|
|
3865
|
-
tool_args: cleanedArgs,
|
|
3866
|
-
error,
|
|
3867
|
-
error_type: classifyMCPError(error),
|
|
3868
|
-
started_at: startedAt,
|
|
3869
|
-
failed_at: failedAt
|
|
3870
|
-
}));
|
|
3871
|
-
throw error;
|
|
3872
|
-
}
|
|
3873
|
-
}
|
|
3874
|
-
async call_tool(toolName, args = null) {
|
|
3875
|
-
return await this.callTool(toolName, args);
|
|
3876
|
-
}
|
|
3877
|
-
cleanToolArguments(args) {
|
|
3878
|
-
return cleanToolArguments(args);
|
|
3879
|
-
}
|
|
3880
|
-
_clean_tool_arguments(args) {
|
|
3881
|
-
return this.cleanToolArguments(args);
|
|
3882
|
-
}
|
|
3883
|
-
async callToolImpl(toolName, args) {
|
|
3884
|
-
const result = await withTimeout(
|
|
3885
|
-
this.session.callTool({ name: toolName, arguments: args }),
|
|
3886
|
-
this.executionTimeout,
|
|
3887
|
-
"MCP tool execution timed out"
|
|
3888
|
-
);
|
|
3889
|
-
return new _MCPToolResult(stringifyMCPToolResult(result), isErrorMCPToolResult(result));
|
|
3890
|
-
}
|
|
3891
|
-
async _call_tool_impl(toolName, args) {
|
|
3892
|
-
return await this.callToolImpl(toolName, args);
|
|
3893
|
-
}
|
|
3894
|
-
emitConnectionFailed(serverName, serverUrl, transportType, error, errorType, startedAt) {
|
|
3895
|
-
crewaiEventBus.emit(this, new MCPConnectionFailedEvent({
|
|
3896
|
-
server_name: serverName,
|
|
3897
|
-
server_url: serverUrl,
|
|
3898
|
-
transport_type: transportType,
|
|
3899
|
-
error,
|
|
3900
|
-
error_type: errorType,
|
|
3901
|
-
started_at: startedAt,
|
|
3902
|
-
failed_at: /* @__PURE__ */ new Date()
|
|
3903
|
-
}));
|
|
3904
|
-
}
|
|
3905
|
-
_emit_connection_failed(serverName, serverUrl, transportType, error, errorType, startedAt) {
|
|
3906
|
-
this.emitConnectionFailed(serverName, serverUrl, transportType, error, errorType, startedAt);
|
|
3907
|
-
}
|
|
3908
|
-
async listPrompts() {
|
|
3909
|
-
if (!this.connected) {
|
|
3910
|
-
await this.connect();
|
|
3911
|
-
}
|
|
3912
|
-
return await this.retryOperation(async () => await this.listPromptsImpl(), this.discoveryTimeout);
|
|
3913
|
-
}
|
|
3914
|
-
async listPromptsImpl() {
|
|
3915
|
-
const result = await withTimeout(this.session.listPrompts(), this.discoveryTimeout, "MCP prompt discovery timed out");
|
|
3916
|
-
return result.prompts.map((prompt) => ({
|
|
3917
|
-
name: typeof prompt.name === "string" ? prompt.name : "",
|
|
3918
|
-
description: typeof prompt.description === "string" ? prompt.description : "",
|
|
3919
|
-
arguments: Array.isArray(prompt.arguments) ? prompt.arguments : []
|
|
3920
|
-
}));
|
|
3921
|
-
}
|
|
3922
|
-
async _list_prompts_impl() {
|
|
3923
|
-
return await this.listPromptsImpl();
|
|
3924
|
-
}
|
|
3925
|
-
async list_prompts() {
|
|
3926
|
-
return await this.listPrompts();
|
|
3927
|
-
}
|
|
3928
|
-
async getPrompt(name, args = null) {
|
|
3929
|
-
if (!this.connected) {
|
|
3930
|
-
await this.connect();
|
|
3931
|
-
}
|
|
3932
|
-
const argumentsObject = args ?? {};
|
|
3933
|
-
return await this.retryOperation(
|
|
3934
|
-
async () => await this.getPromptImpl(name, argumentsObject),
|
|
3935
|
-
this.executionTimeout
|
|
3936
|
-
);
|
|
3937
|
-
}
|
|
3938
|
-
async getPromptImpl(name, args) {
|
|
3939
|
-
const result = await withTimeout(
|
|
3940
|
-
this.session.getPrompt({ name, arguments: args }),
|
|
3941
|
-
this.executionTimeout,
|
|
3942
|
-
"MCP prompt retrieval timed out"
|
|
3943
|
-
);
|
|
3944
|
-
const messages = isPlainRecord(result) && Array.isArray(result.messages) ? result.messages.map((message) => normalizePromptMessage(message)) : [];
|
|
3945
|
-
return {
|
|
3946
|
-
name,
|
|
3947
|
-
messages,
|
|
3948
|
-
arguments: args
|
|
3949
|
-
};
|
|
3950
|
-
}
|
|
3951
|
-
async get_prompt(name, args = null) {
|
|
3952
|
-
return await this.getPrompt(name, args);
|
|
3953
|
-
}
|
|
3954
|
-
async _get_prompt_impl(name, args) {
|
|
3955
|
-
return await this.getPromptImpl(name, args);
|
|
3956
|
-
}
|
|
3957
|
-
async listResources() {
|
|
3958
|
-
if (!this.connected) {
|
|
3959
|
-
await this.connect();
|
|
3960
|
-
}
|
|
3961
|
-
const result = await this.retryOperation(async () => await this.session.listResources());
|
|
3962
|
-
return result.resources.map((resource) => ({ ...resource }));
|
|
3963
|
-
}
|
|
3964
|
-
async list_resources() {
|
|
3965
|
-
return await this.listResources();
|
|
3966
|
-
}
|
|
3967
|
-
async readResource(uri) {
|
|
3968
|
-
if (!this.connected) {
|
|
3969
|
-
await this.connect();
|
|
3970
|
-
}
|
|
3971
|
-
return await this.retryOperation(async () => await this.session.readResource({ uri }));
|
|
3972
|
-
}
|
|
3973
|
-
async read_resource(uri) {
|
|
3974
|
-
return await this.readResource(uri);
|
|
3975
|
-
}
|
|
3976
|
-
getServerInfo() {
|
|
3977
|
-
if (this.transport instanceof StdioTransport) {
|
|
3978
|
-
return [[this.transport.command, ...this.transport.args].join(" "), null, this.transport.transportType];
|
|
3979
|
-
}
|
|
3980
|
-
if (this.transport instanceof HTTPTransport || this.transport instanceof SSETransport) {
|
|
3981
|
-
return [this.transport.url, this.transport.url, this.transport.transportType];
|
|
3982
|
-
}
|
|
3983
|
-
return ["Unknown MCP Server", null, this.transport.transportType];
|
|
3984
|
-
}
|
|
3985
|
-
_get_server_info() {
|
|
3986
|
-
return this.getServerInfo();
|
|
3987
|
-
}
|
|
3988
|
-
getCacheKey(kind) {
|
|
3989
|
-
const [serverName, serverUrl, transportType] = this.getServerInfo();
|
|
3990
|
-
return JSON.stringify([kind, transportType, serverName, serverUrl]);
|
|
3991
|
-
}
|
|
3992
|
-
_get_cache_key(kind) {
|
|
3993
|
-
return this.getCacheKey(kind);
|
|
3994
|
-
}
|
|
3995
|
-
async retryOperation(operation, timeout = null) {
|
|
3996
|
-
let lastError;
|
|
3997
|
-
for (let attempt = 0; attempt < this.maxRetries; attempt += 1) {
|
|
3998
|
-
try {
|
|
3999
|
-
return timeout && timeout > 0 ? await withTimeout(operation(), timeout, `MCP operation timed out`) : await operation();
|
|
4000
|
-
} catch (error) {
|
|
4001
|
-
const errorMessage = formatMCPError(error).toLowerCase();
|
|
4002
|
-
if (errorMessage.includes("authentication") || errorMessage.includes("unauthorized")) {
|
|
4003
|
-
throw new Error(`Authentication failed: ${formatMCPError(error)}`, { cause: error });
|
|
4004
|
-
}
|
|
4005
|
-
if (errorMessage.includes("not found")) {
|
|
4006
|
-
throw new Error(`Resource not found: ${formatMCPError(error)}`, { cause: error });
|
|
4007
|
-
}
|
|
4008
|
-
lastError = error;
|
|
4009
|
-
if (attempt < this.maxRetries - 1) {
|
|
4010
|
-
await delay(Math.min(100 * 2 ** attempt, 1e3));
|
|
4011
|
-
}
|
|
4012
|
-
}
|
|
4013
|
-
}
|
|
4014
|
-
throw lastError;
|
|
4015
|
-
}
|
|
4016
|
-
async _retry_operation(operation, timeout = null) {
|
|
4017
|
-
return await this.retryOperation(operation, timeout);
|
|
4018
|
-
}
|
|
4019
|
-
async cleanupOnError() {
|
|
4020
|
-
this.client = null;
|
|
4021
|
-
this.initialized = false;
|
|
4022
|
-
await this.transport.disconnect();
|
|
4023
|
-
}
|
|
4024
|
-
async _cleanup_on_error() {
|
|
4025
|
-
await this.cleanupOnError();
|
|
4026
|
-
}
|
|
4027
|
-
};
|
|
4028
|
-
var MCPToolResolver = class _MCPToolResolver {
|
|
4029
|
-
agent;
|
|
4030
|
-
logger;
|
|
4031
|
-
clientsValue = [];
|
|
4032
|
-
constructor(optionsOrAgent = {}, logger = null) {
|
|
4033
|
-
if (isResolverOptions(optionsOrAgent)) {
|
|
4034
|
-
this.agent = optionsOrAgent.agent;
|
|
4035
|
-
this.logger = optionsOrAgent.logger ?? null;
|
|
4036
|
-
} else {
|
|
4037
|
-
this.agent = optionsOrAgent;
|
|
4038
|
-
this.logger = logger;
|
|
4039
|
-
}
|
|
4040
|
-
}
|
|
4041
|
-
get clients() {
|
|
4042
|
-
return [...this.clientsValue];
|
|
4043
|
-
}
|
|
4044
|
-
async resolve(mcps) {
|
|
4045
|
-
if (!mcps) {
|
|
4046
|
-
return [];
|
|
4047
|
-
}
|
|
4048
|
-
const tools = [];
|
|
4049
|
-
const ampRefs = [];
|
|
4050
|
-
for (const config of mcps) {
|
|
4051
|
-
if (typeof config === "string") {
|
|
4052
|
-
if (config.startsWith("https://")) {
|
|
4053
|
-
tools.push(...await this.resolveExternal(config));
|
|
4054
|
-
} else {
|
|
4055
|
-
ampRefs.push(this.parseAmpRef(config));
|
|
4056
|
-
}
|
|
4057
|
-
continue;
|
|
4058
|
-
}
|
|
4059
|
-
tools.push(...await this.resolveNative(config));
|
|
4060
|
-
}
|
|
4061
|
-
if (ampRefs.length > 0) {
|
|
4062
|
-
const [ampTools, ampClients] = await this._resolve_amp(ampRefs);
|
|
4063
|
-
tools.push(...ampTools);
|
|
4064
|
-
this.clientsValue.push(...ampClients);
|
|
4065
|
-
}
|
|
4066
|
-
return tools;
|
|
4067
|
-
}
|
|
4068
|
-
async cleanup() {
|
|
4069
|
-
const clients = this.clientsValue.splice(0);
|
|
4070
|
-
for (const client of clients) {
|
|
4071
|
-
try {
|
|
4072
|
-
await client.disconnect();
|
|
4073
|
-
} catch (error) {
|
|
4074
|
-
this.log("error", `Error during MCP client cleanup: ${formatMCPError(error)}`);
|
|
4075
|
-
}
|
|
4076
|
-
}
|
|
4077
|
-
}
|
|
4078
|
-
async disconnectAll() {
|
|
4079
|
-
await this.cleanup();
|
|
4080
|
-
}
|
|
4081
|
-
async _disconnect_all() {
|
|
4082
|
-
await this.disconnectAll();
|
|
4083
|
-
}
|
|
4084
|
-
static parseAmpRef(mcpConfig) {
|
|
4085
|
-
const bare = mcpConfig.startsWith("crewai-amp:") ? mcpConfig.slice("crewai-amp:".length) : mcpConfig;
|
|
4086
|
-
const [slug = "", specificTool = ""] = bare.split("#", 2);
|
|
4087
|
-
return [slug, specificTool || null];
|
|
4088
|
-
}
|
|
4089
|
-
static _parse_amp_ref(mcpConfig) {
|
|
4090
|
-
return _MCPToolResolver.parseAmpRef(mcpConfig);
|
|
4091
|
-
}
|
|
4092
|
-
parseAmpRef(mcpConfig) {
|
|
4093
|
-
return _MCPToolResolver.parseAmpRef(mcpConfig);
|
|
4094
|
-
}
|
|
4095
|
-
_parse_amp_ref(mcpConfig) {
|
|
4096
|
-
return this.parseAmpRef(mcpConfig);
|
|
4097
|
-
}
|
|
4098
|
-
fetchAmpMcpConfigs(slugs) {
|
|
4099
|
-
void slugs;
|
|
4100
|
-
this.log("debug", "AMP MCP config fetching is not available in the local TypeScript runtime.");
|
|
4101
|
-
return {};
|
|
4102
|
-
}
|
|
4103
|
-
_fetch_amp_mcp_configs(slugs) {
|
|
4104
|
-
return this.fetchAmpMcpConfigs(slugs);
|
|
4105
|
-
}
|
|
4106
|
-
async resolveAmp(ampRefs) {
|
|
4107
|
-
const uniqueSlugs = [...new Set(ampRefs.map(([slug]) => slug))];
|
|
4108
|
-
const ampConfigs = this._fetch_amp_mcp_configs(uniqueSlugs);
|
|
4109
|
-
const resolved = /* @__PURE__ */ new Map();
|
|
4110
|
-
const clients = [];
|
|
4111
|
-
for (const slug of uniqueSlugs) {
|
|
4112
|
-
const config = ampConfigs[slug];
|
|
4113
|
-
if (!isPlainRecord(config)) {
|
|
4114
|
-
crewaiEventBus.emit(this, new MCPConfigFetchFailedEvent({
|
|
4115
|
-
slug,
|
|
4116
|
-
error: `Config for '${slug}' not found. Make sure it is connected in your account.`,
|
|
4117
|
-
error_type: "not_connected"
|
|
4118
|
-
}));
|
|
4119
|
-
continue;
|
|
4120
|
-
}
|
|
4121
|
-
try {
|
|
4122
|
-
const nativeResult = await this._resolve_native(this._build_mcp_config_from_dict(config));
|
|
4123
|
-
resolved.set(slug, nativeResult);
|
|
4124
|
-
clients.push(...nativeResult[1]);
|
|
4125
|
-
} catch (error) {
|
|
4126
|
-
crewaiEventBus.emit(this, new MCPConfigFetchFailedEvent({
|
|
4127
|
-
slug,
|
|
4128
|
-
error: formatMCPError(error),
|
|
4129
|
-
error_type: "connection_failed"
|
|
4130
|
-
}));
|
|
4131
|
-
}
|
|
4132
|
-
}
|
|
4133
|
-
const tools = [];
|
|
4134
|
-
for (const [slug, specificTool] of ampRefs) {
|
|
4135
|
-
const cached = resolved.get(slug);
|
|
4136
|
-
if (!cached) {
|
|
4137
|
-
continue;
|
|
4138
|
-
}
|
|
4139
|
-
const [slugTools] = cached;
|
|
4140
|
-
if (!specificTool) {
|
|
4141
|
-
tools.push(...slugTools);
|
|
4142
|
-
continue;
|
|
4143
|
-
}
|
|
4144
|
-
const sanitized = sanitizeToolName(specificTool);
|
|
4145
|
-
tools.push(...slugTools.filter((tool) => tool.name.endsWith(`_${sanitized}`)));
|
|
4146
|
-
}
|
|
4147
|
-
return [tools, clients];
|
|
4148
|
-
}
|
|
4149
|
-
async _resolve_amp(ampRefs) {
|
|
4150
|
-
return await this.resolveAmp(ampRefs);
|
|
4151
|
-
}
|
|
4152
|
-
async resolveNative(config) {
|
|
4153
|
-
const serverName = serverNameForConfig(config);
|
|
4154
|
-
const clientOptions = {
|
|
4155
|
-
cacheToolsList: config.cacheToolsList,
|
|
4156
|
-
cache_tools_list: config.cache_tools_list
|
|
4157
|
-
};
|
|
4158
|
-
const discoveryClient = new MCPClient(transportForConfig(config), clientOptions);
|
|
4159
|
-
try {
|
|
4160
|
-
await discoveryClient.connect();
|
|
4161
|
-
const definitions = await discoveryClient.listTools();
|
|
4162
|
-
const tools = [];
|
|
4163
|
-
for (const definition of definitions) {
|
|
4164
|
-
if (!await passesToolFilter(config, definition, this.agent)) {
|
|
4165
|
-
continue;
|
|
4166
|
-
}
|
|
4167
|
-
const originalName = typeof definition.original_name === "string" ? definition.original_name : typeof definition.name === "string" ? definition.name : "";
|
|
4168
|
-
const sanitizedName = sanitizeToolName(originalName);
|
|
4169
|
-
tools.push(new MCPNativeTool({
|
|
4170
|
-
clientFactory: () => new MCPClient(transportForConfig(config), clientOptions),
|
|
4171
|
-
toolName: sanitizedName,
|
|
4172
|
-
originalToolName: originalName,
|
|
4173
|
-
toolSchema: definition,
|
|
4174
|
-
serverName
|
|
4175
|
-
}));
|
|
4176
|
-
}
|
|
4177
|
-
if (tools.length === 0) {
|
|
4178
|
-
this.log("warning", `No tools discovered from MCP server '${serverName}'.`);
|
|
4179
|
-
}
|
|
4180
|
-
return tools;
|
|
4181
|
-
} catch (error) {
|
|
4182
|
-
throw new Error(`Failed to get native MCP tools: ${formatMCPError(error)}`, { cause: error });
|
|
4183
|
-
} finally {
|
|
4184
|
-
await discoveryClient.disconnect();
|
|
4185
|
-
}
|
|
4186
|
-
}
|
|
4187
|
-
async _resolve_native(config) {
|
|
4188
|
-
return [await this.resolveNative(config), []];
|
|
4189
|
-
}
|
|
4190
|
-
async resolveExternal(mcpRef) {
|
|
4191
|
-
const [serverUrl, specificTool] = splitMCPRef(mcpRef);
|
|
4192
|
-
const serverName = extractServerName(serverUrl);
|
|
4193
|
-
const client = new MCPClient(new HTTPTransport({ url: serverUrl }));
|
|
4194
|
-
try {
|
|
4195
|
-
await client.connect();
|
|
4196
|
-
const definitions = await client.listTools();
|
|
4197
|
-
const sanitizedSpecificTool = specificTool ? sanitizeToolName(specificTool) : null;
|
|
4198
|
-
return definitions.filter((definition) => {
|
|
4199
|
-
const toolName = typeof definition.name === "string" ? definition.name : "";
|
|
4200
|
-
return !sanitizedSpecificTool || sanitizeToolName(toolName) === sanitizedSpecificTool;
|
|
4201
|
-
}).map((definition) => {
|
|
4202
|
-
const originalName = typeof definition.original_name === "string" ? definition.original_name : typeof definition.name === "string" ? definition.name : "";
|
|
4203
|
-
return new MCPToolWrapper({
|
|
4204
|
-
mcpServerParams: { url: serverUrl },
|
|
4205
|
-
toolName: sanitizeToolName(originalName),
|
|
4206
|
-
toolSchema: definition,
|
|
4207
|
-
serverName
|
|
4208
|
-
});
|
|
4209
|
-
});
|
|
4210
|
-
} finally {
|
|
4211
|
-
await client.disconnect();
|
|
4212
|
-
}
|
|
4213
|
-
}
|
|
4214
|
-
async _resolve_external(mcpRef) {
|
|
4215
|
-
return await this.resolveExternal(mcpRef);
|
|
4216
|
-
}
|
|
4217
|
-
static createTransport(config) {
|
|
4218
|
-
return [transportForConfig(config), serverNameForConfig(config)];
|
|
4219
|
-
}
|
|
4220
|
-
static _create_transport(config) {
|
|
4221
|
-
return _MCPToolResolver.createTransport(config);
|
|
4222
|
-
}
|
|
4223
|
-
createTransport(config) {
|
|
4224
|
-
return _MCPToolResolver.createTransport(config);
|
|
4225
|
-
}
|
|
4226
|
-
_create_transport(config) {
|
|
4227
|
-
return this.createTransport(config);
|
|
4228
|
-
}
|
|
4229
|
-
static buildMcpConfigFromDict(config) {
|
|
4230
|
-
const type = typeof config.type === "string" ? config.type : "http";
|
|
4231
|
-
const url = typeof config.url === "string" ? config.url : "";
|
|
4232
|
-
const headers = isPlainRecord(config.headers) ? stringRecord(config.headers) : null;
|
|
4233
|
-
const cacheToolsList = config.cache_tools_list === true || config.cacheToolsList === true;
|
|
4234
|
-
if (type === "sse") {
|
|
4235
|
-
return new MCPServerSSE({ url, headers, cacheToolsList });
|
|
4236
|
-
}
|
|
4237
|
-
return new MCPServerHTTP({
|
|
4238
|
-
url,
|
|
4239
|
-
headers,
|
|
4240
|
-
streamable: config.streamable !== false,
|
|
4241
|
-
cacheToolsList
|
|
4242
|
-
});
|
|
4243
|
-
}
|
|
4244
|
-
static _build_mcp_config_from_dict(config) {
|
|
4245
|
-
return _MCPToolResolver.buildMcpConfigFromDict(config);
|
|
4246
|
-
}
|
|
4247
|
-
buildMcpConfigFromDict(config) {
|
|
4248
|
-
return _MCPToolResolver.buildMcpConfigFromDict(config);
|
|
4249
|
-
}
|
|
4250
|
-
_build_mcp_config_from_dict(config) {
|
|
4251
|
-
return this.buildMcpConfigFromDict(config);
|
|
4252
|
-
}
|
|
4253
|
-
static extractServerName(serverUrl) {
|
|
4254
|
-
return extractServerName(serverUrl);
|
|
4255
|
-
}
|
|
4256
|
-
static _extract_server_name(serverUrl) {
|
|
4257
|
-
return extractServerName(serverUrl);
|
|
4258
|
-
}
|
|
4259
|
-
extractServerName(serverUrl) {
|
|
4260
|
-
return extractServerName(serverUrl);
|
|
4261
|
-
}
|
|
4262
|
-
_extract_server_name(serverUrl) {
|
|
4263
|
-
return this.extractServerName(serverUrl);
|
|
4264
|
-
}
|
|
4265
|
-
async setupClientAndListTools(client) {
|
|
4266
|
-
if (!client.connected) {
|
|
4267
|
-
await client.connect();
|
|
4268
|
-
}
|
|
4269
|
-
try {
|
|
4270
|
-
return await client.listTools();
|
|
4271
|
-
} finally {
|
|
4272
|
-
await client.disconnect();
|
|
4273
|
-
}
|
|
4274
|
-
}
|
|
4275
|
-
async _setup_client_and_list_tools(client) {
|
|
4276
|
-
return await this.setupClientAndListTools(client);
|
|
4277
|
-
}
|
|
4278
|
-
getMcpToolSchemas(serverParams) {
|
|
4279
|
-
const url = typeof serverParams.url === "string" ? serverParams.url : "";
|
|
4280
|
-
if (!url) {
|
|
4281
|
-
return {};
|
|
4282
|
-
}
|
|
4283
|
-
const cached = mcpSchemaCache.get(url);
|
|
4284
|
-
if (cached && Date.now() - cached.createdAt < MCP_SCHEMA_CACHE_TTL_MS) {
|
|
4285
|
-
return Object.fromEntries(cached.tools.map((tool) => [tool.name ?? "", tool]));
|
|
4286
|
-
}
|
|
4287
|
-
return {};
|
|
4288
|
-
}
|
|
4289
|
-
_get_mcp_tool_schemas(serverParams) {
|
|
4290
|
-
return this.getMcpToolSchemas(serverParams);
|
|
4291
|
-
}
|
|
4292
|
-
async getMcpToolSchemasAsync(serverParams) {
|
|
4293
|
-
return await Promise.resolve(this.getMcpToolSchemas(serverParams));
|
|
4294
|
-
}
|
|
4295
|
-
async _get_mcp_tool_schemas_async(serverParams) {
|
|
4296
|
-
return await this.getMcpToolSchemasAsync(serverParams);
|
|
4297
|
-
}
|
|
4298
|
-
async retryMcpDiscovery(operation, serverUrl) {
|
|
4299
|
-
return await operation(serverUrl);
|
|
4300
|
-
}
|
|
4301
|
-
async _retry_mcp_discovery(operation, serverUrl) {
|
|
4302
|
-
return await this.retryMcpDiscovery(operation, serverUrl);
|
|
4303
|
-
}
|
|
4304
|
-
async attemptMcpDiscovery(operation, serverUrl) {
|
|
4305
|
-
try {
|
|
4306
|
-
return [await operation(serverUrl), "", false];
|
|
4307
|
-
} catch (error) {
|
|
4308
|
-
const message = formatMCPError(error);
|
|
4309
|
-
const lower = message.toLowerCase();
|
|
4310
|
-
if (lower.includes("authentication") || lower.includes("unauthorized")) {
|
|
4311
|
-
return [null, `Authentication failed for MCP server: ${message}`, false];
|
|
4312
|
-
}
|
|
4313
|
-
if (lower.includes("connection") || lower.includes("network") || lower.includes("timeout")) {
|
|
4314
|
-
return [null, `Network connection failed: ${message}`, true];
|
|
4315
|
-
}
|
|
4316
|
-
return [null, `MCP discovery error: ${message}`, false];
|
|
4317
|
-
}
|
|
4318
|
-
}
|
|
4319
|
-
async _attempt_mcp_discovery(operation, serverUrl) {
|
|
4320
|
-
return await this.attemptMcpDiscovery(operation, serverUrl);
|
|
4321
|
-
}
|
|
4322
|
-
async discoverMcpToolsWithTimeout(serverUrl) {
|
|
4323
|
-
return await withTimeout(this.discoverMcpTools(serverUrl), MCP_DISCOVERY_TIMEOUT, "MCP discovery timed out");
|
|
4324
|
-
}
|
|
4325
|
-
async _discover_mcp_tools_with_timeout(serverUrl) {
|
|
4326
|
-
return await this.discoverMcpToolsWithTimeout(serverUrl);
|
|
4327
|
-
}
|
|
4328
|
-
async discoverMcpTools(serverUrl) {
|
|
4329
|
-
await Promise.resolve();
|
|
4330
|
-
void serverUrl;
|
|
4331
|
-
return {};
|
|
4332
|
-
}
|
|
4333
|
-
async _discover_mcp_tools(serverUrl) {
|
|
4334
|
-
return await this.discoverMcpTools(serverUrl);
|
|
4335
|
-
}
|
|
4336
|
-
jsonSchemaToPydantic(toolName, jsonSchema) {
|
|
4337
|
-
return {
|
|
4338
|
-
name: `${toolName.replaceAll("-", "_").replaceAll(" ", "_")}Schema`,
|
|
4339
|
-
schema: jsonSchema
|
|
4340
|
-
};
|
|
4341
|
-
}
|
|
4342
|
-
_json_schema_to_pydantic(toolName, jsonSchema) {
|
|
4343
|
-
return this.jsonSchemaToPydantic(toolName, jsonSchema);
|
|
4344
|
-
}
|
|
4345
|
-
log(level, message) {
|
|
4346
|
-
this.logger?.log(level, message);
|
|
4347
|
-
}
|
|
4348
|
-
};
|
|
4349
|
-
var mcp_schema_cache = mcpSchemaCache;
|
|
4350
|
-
function delay(ms) {
|
|
4351
|
-
return new Promise((resolve) => {
|
|
4352
|
-
setTimeout(resolve, ms);
|
|
4353
|
-
});
|
|
4354
|
-
}
|
|
4355
|
-
async function withTimeout(promise, timeoutSeconds, message) {
|
|
4356
|
-
const timeoutRef = {};
|
|
4357
|
-
try {
|
|
4358
|
-
return await Promise.race([
|
|
4359
|
-
promise,
|
|
4360
|
-
new Promise((_resolve, reject) => {
|
|
4361
|
-
timeoutRef.current = setTimeout(() => {
|
|
4362
|
-
reject(new Error(`${message} after ${String(timeoutSeconds)} seconds.`));
|
|
4363
|
-
}, timeoutSeconds * 1e3);
|
|
4364
|
-
})
|
|
4365
|
-
]);
|
|
4366
|
-
} finally {
|
|
4367
|
-
if (timeoutRef.current) {
|
|
4368
|
-
clearTimeout(timeoutRef.current);
|
|
4369
|
-
}
|
|
4370
|
-
}
|
|
4371
|
-
}
|
|
4372
|
-
function cleanToolArguments(argumentsObject) {
|
|
4373
|
-
const cleaned = {};
|
|
4374
|
-
for (const [key, value] of Object.entries(argumentsObject)) {
|
|
4375
|
-
if (value === null || value === void 0) {
|
|
4376
|
-
continue;
|
|
4377
|
-
}
|
|
4378
|
-
if (key === "sources" && Array.isArray(value)) {
|
|
4379
|
-
const sourceValues = value;
|
|
4380
|
-
const sources = sourceValues.filter((item) => item !== null && item !== void 0).map((item) => typeof item === "string" ? { type: item } : item);
|
|
4381
|
-
if (sources.length > 0) {
|
|
4382
|
-
cleaned[key] = sources;
|
|
4383
|
-
}
|
|
4384
|
-
continue;
|
|
4385
|
-
}
|
|
4386
|
-
if (Array.isArray(value)) {
|
|
4387
|
-
const listValues = value;
|
|
4388
|
-
const values = listValues.filter((item) => item !== null && item !== void 0).map((item) => isPlainRecord(item) ? cleanToolArguments(item) : item).filter((item) => !isPlainRecord(item) || Object.keys(item).length > 0);
|
|
4389
|
-
if (values.length > 0) {
|
|
4390
|
-
cleaned[key] = values;
|
|
4391
|
-
}
|
|
4392
|
-
continue;
|
|
4393
|
-
}
|
|
4394
|
-
if (isPlainRecord(value)) {
|
|
4395
|
-
const nested = cleanToolArguments(value);
|
|
4396
|
-
if (Object.keys(nested).length > 0) {
|
|
4397
|
-
cleaned[key] = nested;
|
|
4398
|
-
}
|
|
4399
|
-
continue;
|
|
4400
|
-
}
|
|
4401
|
-
cleaned[key] = value;
|
|
4402
|
-
}
|
|
4403
|
-
return cleaned;
|
|
4404
|
-
}
|
|
4405
|
-
function isPlainRecord(value) {
|
|
4406
|
-
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
4407
|
-
}
|
|
4408
|
-
function stringRecord(value) {
|
|
4409
|
-
return Object.fromEntries(
|
|
4410
|
-
Object.entries(value).filter((entry) => typeof entry[1] === "string")
|
|
4411
|
-
);
|
|
4412
|
-
}
|
|
4413
|
-
function stringifyMCPToolResult(result) {
|
|
4414
|
-
if (isPlainRecord(result) && Array.isArray(result.content) && result.content.length > 0) {
|
|
4415
|
-
const content = result.content;
|
|
4416
|
-
const first = content[0];
|
|
4417
|
-
if (isPlainRecord(first) && typeof first.text === "string") {
|
|
4418
|
-
return first.text;
|
|
4419
|
-
}
|
|
4420
|
-
return stringifyUnknown(first);
|
|
4421
|
-
}
|
|
4422
|
-
if (isPlainRecord(result) && "toolResult" in result) {
|
|
4423
|
-
return stringifyUnknown(result.toolResult);
|
|
4424
|
-
}
|
|
4425
|
-
return stringifyUnknown(result);
|
|
4426
|
-
}
|
|
4427
|
-
function normalizePromptMessage(message) {
|
|
4428
|
-
if (!isPlainRecord(message)) {
|
|
4429
|
-
return { role: "", content: message };
|
|
4430
|
-
}
|
|
4431
|
-
return {
|
|
4432
|
-
role: typeof message.role === "string" ? message.role : "",
|
|
4433
|
-
content: message.content
|
|
4434
|
-
};
|
|
4435
|
-
}
|
|
4436
|
-
function stringifyUnknown(value) {
|
|
4437
|
-
if (typeof value === "string") {
|
|
4438
|
-
return value;
|
|
4439
|
-
}
|
|
4440
|
-
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
|
|
4441
|
-
return value.toString();
|
|
4442
|
-
}
|
|
4443
|
-
if (value === null || value === void 0) {
|
|
4444
|
-
return "";
|
|
4445
|
-
}
|
|
4446
|
-
try {
|
|
4447
|
-
return JSON.stringify(value);
|
|
4448
|
-
} catch {
|
|
4449
|
-
return Object.prototype.toString.call(value);
|
|
4450
|
-
}
|
|
4451
|
-
}
|
|
4452
|
-
function isErrorMCPToolResult(result) {
|
|
4453
|
-
return isPlainRecord(result) && result.isError === true;
|
|
4454
|
-
}
|
|
4455
|
-
function classifyMCPError(error) {
|
|
4456
|
-
const message = formatMCPError(error).toLowerCase();
|
|
4457
|
-
if (message.includes("timeout") || message.includes("timed out")) {
|
|
4458
|
-
return "timeout";
|
|
4459
|
-
}
|
|
4460
|
-
if (message.includes("401") || message.includes("unauthorized") || message.includes("auth")) {
|
|
4461
|
-
return "authentication";
|
|
4462
|
-
}
|
|
4463
|
-
return "network";
|
|
4464
|
-
}
|
|
4465
|
-
function formatMCPError(error) {
|
|
4466
|
-
return error instanceof Error ? error.message : stringifyUnknown(error);
|
|
4467
|
-
}
|
|
4468
|
-
function isResolverOptions(value) {
|
|
4469
|
-
return !!value && typeof value === "object" && ("agent" in value || "logger" in value);
|
|
4470
|
-
}
|
|
4471
|
-
function transportForConfig(config) {
|
|
4472
|
-
if (config instanceof MCPServerStdio) {
|
|
4473
|
-
return new StdioTransport(config);
|
|
4474
|
-
}
|
|
4475
|
-
if (config instanceof MCPServerSSE) {
|
|
4476
|
-
return new SSETransport(config);
|
|
4477
|
-
}
|
|
4478
|
-
return new HTTPTransport(config);
|
|
4479
|
-
}
|
|
4480
|
-
function serverNameForConfig(config) {
|
|
4481
|
-
if (config instanceof MCPServerStdio) {
|
|
4482
|
-
return sanitizeToolName([config.command, ...config.args].join("_"));
|
|
4483
|
-
}
|
|
4484
|
-
if (config instanceof MCPServerHTTP || config instanceof MCPServerSSE) {
|
|
4485
|
-
return extractServerName(config.url);
|
|
4486
|
-
}
|
|
4487
|
-
return "mcp_server";
|
|
4488
|
-
}
|
|
4489
|
-
function extractServerName(url) {
|
|
4490
|
-
try {
|
|
4491
|
-
const parsed = new URL(url);
|
|
4492
|
-
const domain = parsed.hostname.replace(/^www\./, "").replaceAll(".", "_");
|
|
4493
|
-
const path = parsed.pathname.replaceAll("/", "_").replace(/^_+|_+$/g, "");
|
|
4494
|
-
return sanitizeToolName(path ? `${domain}_${path}` : domain);
|
|
4495
|
-
} catch {
|
|
4496
|
-
return sanitizeToolName(url.split("/").filter(Boolean).at(-1) ?? "mcp_server");
|
|
4497
|
-
}
|
|
4498
|
-
}
|
|
4499
|
-
function splitMCPRef(ref) {
|
|
4500
|
-
const markerIndex = ref.indexOf("#");
|
|
4501
|
-
if (markerIndex === -1) {
|
|
4502
|
-
return [ref, null];
|
|
4503
|
-
}
|
|
4504
|
-
return [ref.slice(0, markerIndex), ref.slice(markerIndex + 1) || null];
|
|
4505
|
-
}
|
|
4506
|
-
async function passesToolFilter(config, definition, agent) {
|
|
4507
|
-
const filter = config.toolFilter ?? config.tool_filter;
|
|
4508
|
-
if (!filter) {
|
|
4509
|
-
return true;
|
|
4510
|
-
}
|
|
4511
|
-
if (filter.length >= 2) {
|
|
4512
|
-
return await filter(
|
|
4513
|
-
new ToolFilterContext({ agent, serverName: serverNameForConfig(config) }),
|
|
4514
|
-
definition
|
|
4515
|
-
);
|
|
4516
|
-
}
|
|
4517
|
-
return await filter(definition);
|
|
4518
|
-
}
|
|
4519
|
-
function headersFromInit(headers) {
|
|
4520
|
-
if (!headers) {
|
|
4521
|
-
return {};
|
|
4522
|
-
}
|
|
4523
|
-
if (headers instanceof Headers) {
|
|
4524
|
-
return Object.fromEntries(headers.entries());
|
|
4525
|
-
}
|
|
4526
|
-
if (Array.isArray(headers)) {
|
|
4527
|
-
return Object.fromEntries(headers);
|
|
4528
|
-
}
|
|
4529
|
-
if (typeof headers === "object") {
|
|
4530
|
-
return Object.fromEntries(
|
|
4531
|
-
Object.entries(headers).filter((entry) => typeof entry[1] === "string")
|
|
4532
|
-
);
|
|
4533
|
-
}
|
|
4534
|
-
return {};
|
|
4535
|
-
}
|
|
4536
|
-
|
|
4537
3087
|
export {
|
|
4538
3088
|
I18N,
|
|
4539
3089
|
getI18N,
|
|
@@ -4594,34 +3144,6 @@ export {
|
|
|
4594
3144
|
coerceSecurityConfig,
|
|
4595
3145
|
validateMetadata,
|
|
4596
3146
|
_validate_metadata,
|
|
4597
|
-
TransportType,
|
|
4598
|
-
MCPReadStream,
|
|
4599
|
-
MCPWriteStream,
|
|
4600
|
-
ToolFilterContext,
|
|
4601
|
-
ToolFilter,
|
|
4602
|
-
StaticToolFilter,
|
|
4603
|
-
createStaticToolFilter,
|
|
4604
|
-
create_static_tool_filter,
|
|
4605
|
-
createDynamicToolFilter,
|
|
4606
|
-
create_dynamic_tool_filter,
|
|
4607
|
-
MCPServerStdio,
|
|
4608
|
-
MCPServerHTTP,
|
|
4609
|
-
MCPServerSSE,
|
|
4610
|
-
MCPServerConfig,
|
|
4611
|
-
BaseTransport,
|
|
4612
|
-
HTTPTransport,
|
|
4613
|
-
SSETransport,
|
|
4614
|
-
StdioTransport,
|
|
4615
|
-
isMCPServerConfig,
|
|
4616
|
-
is_mcp_server_config,
|
|
4617
|
-
MCP_CONNECTION_TIMEOUT,
|
|
4618
|
-
MCP_TOOL_EXECUTION_TIMEOUT,
|
|
4619
|
-
MCP_DISCOVERY_TIMEOUT,
|
|
4620
|
-
MCP_MAX_RETRIES,
|
|
4621
|
-
_MCPToolResult,
|
|
4622
|
-
MCPClient,
|
|
4623
|
-
MCPToolResolver,
|
|
4624
|
-
mcp_schema_cache,
|
|
4625
3147
|
OPENAI_BIGGER_MODELS,
|
|
4626
3148
|
EnvVar,
|
|
4627
3149
|
ToolCalling,
|
|
@@ -4654,17 +3176,17 @@ export {
|
|
|
4654
3176
|
DelegateWorkTool,
|
|
4655
3177
|
AgentTools,
|
|
4656
3178
|
CacheTools,
|
|
4657
|
-
MCPNativeTool,
|
|
4658
|
-
MCPToolWrapper,
|
|
4659
3179
|
ToolUsageError,
|
|
4660
3180
|
ToolUsage,
|
|
4661
3181
|
createTool,
|
|
3182
|
+
functionTool,
|
|
4662
3183
|
create_tool,
|
|
4663
3184
|
createFunctionTool,
|
|
4664
3185
|
create_function_tool,
|
|
4665
3186
|
_make_tool,
|
|
4666
3187
|
_make_with_name,
|
|
4667
3188
|
_resolve_tool_dict,
|
|
3189
|
+
isToolCalling,
|
|
4668
3190
|
normalizeToolCalling,
|
|
4669
3191
|
aexecuteToolAndCheckFinality,
|
|
4670
3192
|
aexecute_tool_and_check_finality,
|