mcp-use 1.9.1-canary.1 → 1.10.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.
Files changed (145) hide show
  1. package/README.md +9 -6
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/{chunk-QREDNTLS.js → chunk-5S5DWSKI.js} +1 -1
  4. package/dist/{chunk-MUZ5WYE3.js → chunk-5UB2K5L6.js} +72 -14
  5. package/dist/{chunk-33U4IA4N.js → chunk-B5N3LQQU.js} +99 -5
  6. package/dist/{chunk-3R5PDYIN.js → chunk-J75I2C26.js} +39 -11
  7. package/dist/{chunk-U5BX3ISQ.js → chunk-KMTBWOVS.js} +22 -408
  8. package/dist/{chunk-D22NUQTL.js → chunk-LXYUQEEE.js} +235 -12
  9. package/dist/{chunk-ZQUCGISK.js → chunk-NNQUSDFU.js} +21 -5
  10. package/dist/chunk-PESKSVLQ.js +1129 -0
  11. package/dist/index.cjs +1190 -200
  12. package/dist/index.d.ts +6 -4
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +63 -23
  15. package/dist/src/adapters/langchain_adapter.d.ts +1 -1
  16. package/dist/src/adapters/langchain_adapter.d.ts.map +1 -1
  17. package/dist/src/agents/index.cjs +2263 -1626
  18. package/dist/src/agents/index.js +4 -4
  19. package/dist/src/agents/mcp_agent.d.ts +5 -0
  20. package/dist/src/agents/mcp_agent.d.ts.map +1 -1
  21. package/dist/src/auth/browser-provider.d.ts +2 -2
  22. package/dist/src/auth/browser-provider.d.ts.map +1 -1
  23. package/dist/src/auth/callback.d.ts.map +1 -1
  24. package/dist/src/auth/index.cjs +39 -11
  25. package/dist/src/auth/index.js +1 -1
  26. package/dist/src/auth/types.d.ts +1 -1
  27. package/dist/src/auth/types.d.ts.map +1 -1
  28. package/dist/src/browser.cjs +2672 -1754
  29. package/dist/src/browser.d.ts +5 -1
  30. package/dist/src/browser.d.ts.map +1 -1
  31. package/dist/src/browser.js +18 -5
  32. package/dist/src/client/base.d.ts.map +1 -1
  33. package/dist/src/client/browser.d.ts +6 -0
  34. package/dist/src/client/browser.d.ts.map +1 -1
  35. package/dist/src/client/connectors/codeMode.d.ts +1 -1
  36. package/dist/src/client/connectors/codeMode.d.ts.map +1 -1
  37. package/dist/src/client/executors/base.d.ts +1 -1
  38. package/dist/src/client/executors/base.d.ts.map +1 -1
  39. package/dist/src/client/prompts.cjs +4 -1
  40. package/dist/src/client/prompts.js +3 -2
  41. package/dist/src/client.d.ts +7 -1
  42. package/dist/src/client.d.ts.map +1 -1
  43. package/dist/src/connectors/base.d.ts +56 -6
  44. package/dist/src/connectors/base.d.ts.map +1 -1
  45. package/dist/src/connectors/http.d.ts.map +1 -1
  46. package/dist/src/connectors/stdio.d.ts.map +1 -1
  47. package/dist/src/connectors/websocket.d.ts +1 -1
  48. package/dist/src/connectors/websocket.d.ts.map +1 -1
  49. package/dist/src/oauth-helper.d.ts.map +1 -1
  50. package/dist/src/react/WidgetControls.d.ts.map +1 -1
  51. package/dist/src/react/index.cjs +1357 -43
  52. package/dist/src/react/index.d.ts +4 -1
  53. package/dist/src/react/index.d.ts.map +1 -1
  54. package/dist/src/react/index.js +14 -5
  55. package/dist/src/react/types.d.ts +1 -1
  56. package/dist/src/react/types.d.ts.map +1 -1
  57. package/dist/src/react/useMcp.d.ts.map +1 -1
  58. package/dist/src/server/endpoints/mount-mcp.d.ts +4 -1
  59. package/dist/src/server/endpoints/mount-mcp.d.ts.map +1 -1
  60. package/dist/src/server/index.cjs +1923 -287
  61. package/dist/src/server/index.d.ts +3 -2
  62. package/dist/src/server/index.d.ts.map +1 -1
  63. package/dist/src/server/index.js +488 -245
  64. package/dist/src/server/mcp-server.d.ts +77 -27
  65. package/dist/src/server/mcp-server.d.ts.map +1 -1
  66. package/dist/src/server/oauth/middleware.d.ts.map +1 -1
  67. package/dist/src/server/oauth/providers/auth0.d.ts +1 -1
  68. package/dist/src/server/oauth/providers/auth0.d.ts.map +1 -1
  69. package/dist/src/server/oauth/providers/custom.d.ts +4 -2
  70. package/dist/src/server/oauth/providers/custom.d.ts.map +1 -1
  71. package/dist/src/server/oauth/providers/keycloak.d.ts +1 -1
  72. package/dist/src/server/oauth/providers/keycloak.d.ts.map +1 -1
  73. package/dist/src/server/oauth/providers/supabase.d.ts +1 -1
  74. package/dist/src/server/oauth/providers/supabase.d.ts.map +1 -1
  75. package/dist/src/server/oauth/providers/types.d.ts +9 -5
  76. package/dist/src/server/oauth/providers/types.d.ts.map +1 -1
  77. package/dist/src/server/oauth/providers.d.ts +27 -9
  78. package/dist/src/server/oauth/providers.d.ts.map +1 -1
  79. package/dist/src/server/oauth/setup.d.ts +5 -4
  80. package/dist/src/server/oauth/setup.d.ts.map +1 -1
  81. package/dist/src/server/oauth/utils.d.ts +3 -2
  82. package/dist/src/server/oauth/utils.d.ts.map +1 -1
  83. package/dist/src/server/prompts/conversion.d.ts +1 -1
  84. package/dist/src/server/prompts/conversion.d.ts.map +1 -1
  85. package/dist/src/server/prompts/index.d.ts +6 -5
  86. package/dist/src/server/prompts/index.d.ts.map +1 -1
  87. package/dist/src/server/resources/conversion.d.ts +1 -1
  88. package/dist/src/server/resources/conversion.d.ts.map +1 -1
  89. package/dist/src/server/resources/index.d.ts +44 -25
  90. package/dist/src/server/resources/index.d.ts.map +1 -1
  91. package/dist/src/server/resources/subscriptions.d.ts +1 -1
  92. package/dist/src/server/resources/subscriptions.d.ts.map +1 -1
  93. package/dist/src/server/sessions/session-manager.d.ts +11 -5
  94. package/dist/src/server/sessions/session-manager.d.ts.map +1 -1
  95. package/dist/src/server/tools/tool-execution-helpers.d.ts +31 -8
  96. package/dist/src/server/tools/tool-execution-helpers.d.ts.map +1 -1
  97. package/dist/src/server/tools/tool-registration.d.ts +21 -7
  98. package/dist/src/server/tools/tool-registration.d.ts.map +1 -1
  99. package/dist/src/server/types/common.d.ts +25 -9
  100. package/dist/src/server/types/common.d.ts.map +1 -1
  101. package/dist/src/server/types/index.d.ts +3 -3
  102. package/dist/src/server/types/index.d.ts.map +1 -1
  103. package/dist/src/server/types/prompt.d.ts +3 -2
  104. package/dist/src/server/types/prompt.d.ts.map +1 -1
  105. package/dist/src/server/types/resource.d.ts +60 -10
  106. package/dist/src/server/types/resource.d.ts.map +1 -1
  107. package/dist/src/server/types/tool-context.d.ts +116 -1
  108. package/dist/src/server/types/tool-context.d.ts.map +1 -1
  109. package/dist/src/server/types/tool.d.ts +43 -2
  110. package/dist/src/server/types/tool.d.ts.map +1 -1
  111. package/dist/src/server/types/widget.d.ts +11 -1
  112. package/dist/src/server/types/widget.d.ts.map +1 -1
  113. package/dist/src/server/utils/response-helpers.d.ts +17 -29
  114. package/dist/src/server/utils/response-helpers.d.ts.map +1 -1
  115. package/dist/src/server/widgets/index.d.ts +3 -3
  116. package/dist/src/server/widgets/index.d.ts.map +1 -1
  117. package/dist/src/server/widgets/mount-widgets-dev.d.ts.map +1 -1
  118. package/dist/src/server/widgets/ui-resource-registration.d.ts +13 -25
  119. package/dist/src/server/widgets/ui-resource-registration.d.ts.map +1 -1
  120. package/dist/src/server/widgets/widget-helpers.d.ts +11 -6
  121. package/dist/src/server/widgets/widget-helpers.d.ts.map +1 -1
  122. package/dist/src/server/widgets/widget-types.d.ts +3 -3
  123. package/dist/src/server/widgets/widget-types.d.ts.map +1 -1
  124. package/dist/src/session.d.ts +372 -2
  125. package/dist/src/session.d.ts.map +1 -1
  126. package/dist/src/task_managers/sse.d.ts +2 -2
  127. package/dist/src/task_managers/sse.d.ts.map +1 -1
  128. package/dist/src/task_managers/stdio.d.ts +2 -2
  129. package/dist/src/task_managers/stdio.d.ts.map +1 -1
  130. package/dist/src/task_managers/streamable_http.d.ts +2 -2
  131. package/dist/src/task_managers/streamable_http.d.ts.map +1 -1
  132. package/dist/src/telemetry/events.d.ts +247 -0
  133. package/dist/src/telemetry/events.d.ts.map +1 -1
  134. package/dist/src/telemetry/index.d.ts +4 -4
  135. package/dist/src/telemetry/index.d.ts.map +1 -1
  136. package/dist/src/telemetry/telemetry.d.ts +122 -4
  137. package/dist/src/telemetry/telemetry.d.ts.map +1 -1
  138. package/dist/src/telemetry/utils.d.ts +1 -1
  139. package/dist/src/telemetry/utils.d.ts.map +1 -1
  140. package/dist/src/version.d.ts +8 -0
  141. package/dist/src/version.d.ts.map +1 -0
  142. package/dist/{tool-execution-helpers-BQJTPWPN.js → tool-execution-helpers-OOVLOJYH.js} +3 -2
  143. package/dist/tsup.config.d.ts.map +1 -1
  144. package/package.json +7 -5
  145. package/dist/chunk-MTHLLDCX.js +0 -97
@@ -35,9 +35,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
35
35
  async function getNodeModules() {
36
36
  if (typeof process !== "undefined" && process.platform) {
37
37
  try {
38
- const fs3 = await import("fs");
39
- const path3 = await import("path");
40
- return { fs: fs3.default, path: path3.default };
38
+ const fs = await import("fs");
39
+ const path = await import("path");
40
+ return { fs: fs.default, path: path.default };
41
41
  } catch {
42
42
  return { fs: null, path: null };
43
43
  }
@@ -1055,1929 +1055,2555 @@ __export(agents_exports, {
1055
1055
  module.exports = __toCommonJS(agents_exports);
1056
1056
 
1057
1057
  // src/connectors/base.ts
1058
- var import_types = require("@modelcontextprotocol/sdk/types.js");
1058
+ var import_types = require("@mcp-use/modelcontextprotocol-sdk/types.js");
1059
1059
  init_logging();
1060
1060
 
1061
- // src/client/connectors/codeMode.ts
1062
- var CODE_MODE_AGENT_PROMPT = `
1063
- ## MCP Code Mode Tool Usage Guide
1064
-
1065
- You have access to an MCP Code Mode Client that allows you to execute JavaScript/TypeScript code with access to registered tools. Follow this workflow:
1066
-
1067
- ### 1. Tool Discovery Phase
1068
- **Always start by discovering available tools:**
1069
- - Tools are organized by server namespace (e.g., \`server_name.tool_name\`)
1070
- - Use the \`search_tools(query, detail_level)\` function to find available tools
1071
- - You can access \`__tool_namespaces\` to see all available server namespaces
1072
-
1073
- \`\`\`javascript
1074
- // Find all GitHub-related tools
1075
- const tools = await search_tools("github");
1076
- for (const tool of tools) {
1077
- console.log(\`\${tool.server}.\${tool.name}: \${tool.description}\`);
1061
+ // src/telemetry/events.ts
1062
+ var BaseTelemetryEvent = class {
1063
+ static {
1064
+ __name(this, "BaseTelemetryEvent");
1065
+ }
1066
+ };
1067
+ var MCPAgentExecutionEvent = class extends BaseTelemetryEvent {
1068
+ constructor(data) {
1069
+ super();
1070
+ this.data = data;
1071
+ }
1072
+ static {
1073
+ __name(this, "MCPAgentExecutionEvent");
1074
+ }
1075
+ get name() {
1076
+ return "mcp_agent_execution";
1077
+ }
1078
+ get properties() {
1079
+ return {
1080
+ // Core execution info
1081
+ execution_method: this.data.executionMethod,
1082
+ query: this.data.query,
1083
+ query_length: this.data.query.length,
1084
+ success: this.data.success,
1085
+ // Agent configuration
1086
+ model_provider: this.data.modelProvider,
1087
+ model_name: this.data.modelName,
1088
+ server_count: this.data.serverCount,
1089
+ server_identifiers: this.data.serverIdentifiers,
1090
+ total_tools_available: this.data.totalToolsAvailable,
1091
+ tools_available_names: this.data.toolsAvailableNames,
1092
+ max_steps_configured: this.data.maxStepsConfigured,
1093
+ memory_enabled: this.data.memoryEnabled,
1094
+ use_server_manager: this.data.useServerManager,
1095
+ // Execution parameters (always include, even if null)
1096
+ max_steps_used: this.data.maxStepsUsed,
1097
+ manage_connector: this.data.manageConnector,
1098
+ external_history_used: this.data.externalHistoryUsed,
1099
+ // Execution results (always include, even if null)
1100
+ steps_taken: this.data.stepsTaken ?? null,
1101
+ tools_used_count: this.data.toolsUsedCount ?? null,
1102
+ tools_used_names: this.data.toolsUsedNames ?? null,
1103
+ response: this.data.response ?? null,
1104
+ response_length: this.data.response ? this.data.response.length : null,
1105
+ execution_time_ms: this.data.executionTimeMs ?? null,
1106
+ error_type: this.data.errorType ?? null,
1107
+ conversation_history_length: this.data.conversationHistoryLength ?? null
1108
+ };
1109
+ }
1110
+ };
1111
+ function createServerRunEventData(server, transport) {
1112
+ const toolRegistrations = Array.from(server.registrations.tools.values());
1113
+ const promptRegistrations = Array.from(server.registrations.prompts.values());
1114
+ const resourceRegistrations = Array.from(
1115
+ server.registrations.resources.values()
1116
+ );
1117
+ const templateRegistrations = Array.from(
1118
+ server.registrations.resourceTemplates.values()
1119
+ );
1120
+ const allResources = resourceRegistrations.map((r) => ({
1121
+ name: r.config.name,
1122
+ title: r.config.title ?? null,
1123
+ description: r.config.description ?? null,
1124
+ uri: r.config.uri ?? null,
1125
+ mime_type: r.config.mimeType ?? null
1126
+ }));
1127
+ const appsSdkResources = allResources.filter(
1128
+ (r) => r.mime_type === "text/html+skybridge"
1129
+ );
1130
+ const mcpUiResources = allResources.filter(
1131
+ (r) => r.mime_type === "text/uri-list" || r.mime_type === "text/html"
1132
+ );
1133
+ const mcpAppsResources = allResources.filter(
1134
+ (r) => r.mime_type === "text/html+mcp"
1135
+ );
1136
+ return {
1137
+ transport,
1138
+ toolsNumber: server.registeredTools.length,
1139
+ resourcesNumber: server.registeredResources.length,
1140
+ promptsNumber: server.registeredPrompts.length,
1141
+ auth: !!server.oauthProvider,
1142
+ name: server.config.name,
1143
+ description: server.config.description ?? null,
1144
+ baseUrl: server.serverBaseUrl ?? null,
1145
+ toolNames: server.registeredTools.length > 0 ? server.registeredTools : null,
1146
+ resourceNames: server.registeredResources.length > 0 ? server.registeredResources : null,
1147
+ promptNames: server.registeredPrompts.length > 0 ? server.registeredPrompts : null,
1148
+ tools: toolRegistrations.length > 0 ? toolRegistrations.map((r) => ({
1149
+ name: r.config.name,
1150
+ title: r.config.title ?? null,
1151
+ description: r.config.description ?? null,
1152
+ input_schema: r.config.schema ? JSON.stringify(r.config.schema) : null,
1153
+ output_schema: r.config.outputSchema ? JSON.stringify(r.config.outputSchema) : null
1154
+ })) : null,
1155
+ resources: allResources.length > 0 ? allResources : null,
1156
+ prompts: promptRegistrations.length > 0 ? promptRegistrations.map((r) => ({
1157
+ name: r.config.name,
1158
+ title: r.config.title ?? null,
1159
+ description: r.config.description ?? null,
1160
+ args: r.config.args ? JSON.stringify(r.config.args) : null
1161
+ })) : null,
1162
+ templates: templateRegistrations.length > 0 ? templateRegistrations.map((r) => ({
1163
+ name: r.config.name,
1164
+ title: r.config.title ?? null,
1165
+ description: r.config.description ?? null
1166
+ })) : null,
1167
+ capabilities: {
1168
+ logging: true,
1169
+ resources: { subscribe: true, listChanged: true }
1170
+ },
1171
+ appsSdkResources: appsSdkResources.length > 0 ? appsSdkResources : null,
1172
+ appsSdkResourcesNumber: appsSdkResources.length,
1173
+ mcpUiResources: mcpUiResources.length > 0 ? mcpUiResources : null,
1174
+ mcpUiResourcesNumber: mcpUiResources.length,
1175
+ mcpAppsResources: mcpAppsResources.length > 0 ? mcpAppsResources : null,
1176
+ mcpAppsResourcesNumber: mcpAppsResources.length
1177
+ };
1078
1178
  }
1179
+ __name(createServerRunEventData, "createServerRunEventData");
1180
+ var ServerRunEvent = class extends BaseTelemetryEvent {
1181
+ constructor(data) {
1182
+ super();
1183
+ this.data = data;
1184
+ }
1185
+ static {
1186
+ __name(this, "ServerRunEvent");
1187
+ }
1188
+ get name() {
1189
+ return "server_run";
1190
+ }
1191
+ get properties() {
1192
+ return {
1193
+ transport: this.data.transport,
1194
+ tools_number: this.data.toolsNumber,
1195
+ resources_number: this.data.resourcesNumber,
1196
+ prompts_number: this.data.promptsNumber,
1197
+ auth: this.data.auth,
1198
+ name: this.data.name,
1199
+ description: this.data.description ?? null,
1200
+ base_url: this.data.baseUrl ?? null,
1201
+ tool_names: this.data.toolNames ?? null,
1202
+ resource_names: this.data.resourceNames ?? null,
1203
+ prompt_names: this.data.promptNames ?? null,
1204
+ tools: this.data.tools ?? null,
1205
+ resources: this.data.resources ?? null,
1206
+ prompts: this.data.prompts ?? null,
1207
+ templates: this.data.templates ?? null,
1208
+ capabilities: this.data.capabilities ? JSON.stringify(this.data.capabilities) : null,
1209
+ apps_sdk_resources: this.data.appsSdkResources ? JSON.stringify(this.data.appsSdkResources) : null,
1210
+ apps_sdk_resources_number: this.data.appsSdkResourcesNumber ?? 0,
1211
+ mcp_ui_resources: this.data.mcpUiResources ? JSON.stringify(this.data.mcpUiResources) : null,
1212
+ mcp_ui_resources_number: this.data.mcpUiResourcesNumber ?? 0,
1213
+ mcp_apps_resources: this.data.mcpAppsResources ? JSON.stringify(this.data.mcpAppsResources) : null,
1214
+ mcp_apps_resources_number: this.data.mcpAppsResourcesNumber ?? 0
1215
+ };
1216
+ }
1217
+ };
1218
+ var ServerInitializeEvent = class extends BaseTelemetryEvent {
1219
+ constructor(data) {
1220
+ super();
1221
+ this.data = data;
1222
+ }
1223
+ static {
1224
+ __name(this, "ServerInitializeEvent");
1225
+ }
1226
+ get name() {
1227
+ return "server_initialize_call";
1228
+ }
1229
+ get properties() {
1230
+ return {
1231
+ protocol_version: this.data.protocolVersion,
1232
+ client_info: JSON.stringify(this.data.clientInfo),
1233
+ client_capabilities: JSON.stringify(this.data.clientCapabilities),
1234
+ session_id: this.data.sessionId ?? null
1235
+ };
1236
+ }
1237
+ };
1238
+ var ServerToolCallEvent = class extends BaseTelemetryEvent {
1239
+ constructor(data) {
1240
+ super();
1241
+ this.data = data;
1242
+ }
1243
+ static {
1244
+ __name(this, "ServerToolCallEvent");
1245
+ }
1246
+ get name() {
1247
+ return "server_tool_call";
1248
+ }
1249
+ get properties() {
1250
+ return {
1251
+ tool_name: this.data.toolName,
1252
+ length_input_argument: this.data.lengthInputArgument,
1253
+ success: this.data.success,
1254
+ error_type: this.data.errorType ?? null,
1255
+ execution_time_ms: this.data.executionTimeMs ?? null
1256
+ };
1257
+ }
1258
+ };
1259
+ var ServerResourceCallEvent = class extends BaseTelemetryEvent {
1260
+ constructor(data) {
1261
+ super();
1262
+ this.data = data;
1263
+ }
1264
+ static {
1265
+ __name(this, "ServerResourceCallEvent");
1266
+ }
1267
+ get name() {
1268
+ return "server_resource_call";
1269
+ }
1270
+ get properties() {
1271
+ return {
1272
+ name: this.data.name,
1273
+ description: this.data.description,
1274
+ contents: this.data.contents,
1275
+ success: this.data.success,
1276
+ error_type: this.data.errorType ?? null
1277
+ };
1278
+ }
1279
+ };
1280
+ var ServerPromptCallEvent = class extends BaseTelemetryEvent {
1281
+ constructor(data) {
1282
+ super();
1283
+ this.data = data;
1284
+ }
1285
+ static {
1286
+ __name(this, "ServerPromptCallEvent");
1287
+ }
1288
+ get name() {
1289
+ return "server_prompt_call";
1290
+ }
1291
+ get properties() {
1292
+ return {
1293
+ name: this.data.name,
1294
+ description: this.data.description,
1295
+ success: this.data.success,
1296
+ error_type: this.data.errorType ?? null
1297
+ };
1298
+ }
1299
+ };
1300
+ var ServerContextEvent = class extends BaseTelemetryEvent {
1301
+ constructor(data) {
1302
+ super();
1303
+ this.data = data;
1304
+ }
1305
+ static {
1306
+ __name(this, "ServerContextEvent");
1307
+ }
1308
+ get name() {
1309
+ return `server_context_${this.data.contextType}`;
1310
+ }
1311
+ get properties() {
1312
+ return {
1313
+ context_type: this.data.contextType,
1314
+ notification_type: this.data.notificationType ?? null
1315
+ };
1316
+ }
1317
+ };
1318
+ var MCPClientInitEvent = class extends BaseTelemetryEvent {
1319
+ constructor(data) {
1320
+ super();
1321
+ this.data = data;
1322
+ }
1323
+ static {
1324
+ __name(this, "MCPClientInitEvent");
1325
+ }
1326
+ get name() {
1327
+ return "mcpclient_init";
1328
+ }
1329
+ get properties() {
1330
+ return {
1331
+ code_mode: this.data.codeMode,
1332
+ sandbox: this.data.sandbox,
1333
+ all_callbacks: this.data.allCallbacks,
1334
+ verify: this.data.verify,
1335
+ servers: this.data.servers,
1336
+ num_servers: this.data.numServers,
1337
+ is_browser: this.data.isBrowser
1338
+ };
1339
+ }
1340
+ };
1341
+ var ConnectorInitEvent = class extends BaseTelemetryEvent {
1342
+ constructor(data) {
1343
+ super();
1344
+ this.data = data;
1345
+ }
1346
+ static {
1347
+ __name(this, "ConnectorInitEvent");
1348
+ }
1349
+ get name() {
1350
+ return "connector_init";
1351
+ }
1352
+ get properties() {
1353
+ return {
1354
+ connector_type: this.data.connectorType,
1355
+ server_command: this.data.serverCommand ?? null,
1356
+ server_args: this.data.serverArgs ?? null,
1357
+ server_url: this.data.serverUrl ?? null,
1358
+ public_identifier: this.data.publicIdentifier ?? null
1359
+ };
1360
+ }
1361
+ };
1362
+ var ClientAddServerEvent = class extends BaseTelemetryEvent {
1363
+ constructor(data) {
1364
+ super();
1365
+ this.data = data;
1366
+ }
1367
+ static {
1368
+ __name(this, "ClientAddServerEvent");
1369
+ }
1370
+ get name() {
1371
+ return "client_add_server";
1372
+ }
1373
+ get properties() {
1374
+ const { serverName, serverConfig } = this.data;
1375
+ const url = serverConfig.url;
1376
+ return {
1377
+ server_name: serverName,
1378
+ server_url_domain: url ? this._extractHostname(url) : null,
1379
+ transport: serverConfig.transport ?? null,
1380
+ has_auth: !!(serverConfig.authToken || serverConfig.authProvider)
1381
+ };
1382
+ }
1383
+ _extractHostname(url) {
1384
+ try {
1385
+ return new URL(url).hostname;
1386
+ } catch {
1387
+ return null;
1388
+ }
1389
+ }
1390
+ };
1391
+ var ClientRemoveServerEvent = class extends BaseTelemetryEvent {
1392
+ constructor(data) {
1393
+ super();
1394
+ this.data = data;
1395
+ }
1396
+ static {
1397
+ __name(this, "ClientRemoveServerEvent");
1398
+ }
1399
+ get name() {
1400
+ return "client_remove_server";
1401
+ }
1402
+ get properties() {
1403
+ return {
1404
+ server_name: this.data.serverName
1405
+ };
1406
+ }
1407
+ };
1079
1408
 
1080
- // Get only tool names for quick overview
1081
- const tools = await search_tools("", "names");
1082
- \`\`\`
1083
-
1084
- ### 2. Interface Introspection
1085
- **Understand tool contracts before using them:**
1086
- - Use \`search_tools\` to get tool descriptions and input schemas
1087
- - Look for "Access as: server.tool(args)" patterns in descriptions
1088
-
1089
- ### 3. Code Execution Guidelines
1090
- **When writing code:**
1091
- - Use \`await server.tool({ param: value })\` syntax for all tool calls
1092
- - Tools are async functions that return promises
1093
- - You have access to standard JavaScript globals: \`console\`, \`JSON\`, \`Math\`, \`Date\`, etc.
1094
- - All console output (\`console.log\`, \`console.error\`, etc.) is automatically captured and returned
1095
- - Build properly structured input objects based on interface definitions
1096
- - Handle errors appropriately with try/catch blocks
1097
- - Chain tool calls by using results from previous calls
1098
-
1099
- ### 4. Best Practices
1100
- - **Discover first, code second**: Always explore available tools before writing execution code
1101
- - **Respect namespaces**: Use full \`server.tool\` names to avoid conflicts
1102
- - **Minimize Context**: Process large data in code, return only essential results
1103
- - **Error handling**: Wrap tool calls in try/catch for robustness
1104
- - **Data flow**: Chain tools by passing outputs as inputs to subsequent tools
1105
-
1106
- ### 5. Available Runtime Context
1107
- - \`search_tools(query, detail_level)\`: Function to discover tools
1108
- - \`__tool_namespaces\`: Array of available server namespaces
1109
- - All registered tools as \`server.tool\` functions
1110
- - Standard JavaScript built-ins for data processing
1111
-
1112
- ### Example Workflow
1113
-
1114
- \`\`\`javascript
1115
- // 1. Discover available tools
1116
- const github_tools = await search_tools("github pull request");
1117
- console.log(\`Available GitHub PR tools: \${github_tools.map(t => t.name)}\`);
1118
-
1119
- // 2. Call tools with proper parameters
1120
- const pr = await github.get_pull_request({
1121
- owner: "facebook",
1122
- repo: "react",
1123
- number: 12345
1124
- });
1125
-
1126
- // 3. Process results
1127
- let result;
1128
- if (pr.state === 'open' && pr.labels.some(l => l.name === 'bug')) {
1129
- // 4. Chain with other tools
1130
- await slack.post_message({
1131
- channel: "#bugs",
1132
- text: \`\u{1F41B} Bug PR needs review: \${pr.title}\`
1133
- });
1134
- result = "Notification sent";
1135
- } else {
1136
- result = "No action needed";
1409
+ // src/server/utils/runtime.ts
1410
+ var isDeno = typeof globalThis.Deno !== "undefined";
1411
+ function generateUUID() {
1412
+ return globalThis.crypto.randomUUID();
1137
1413
  }
1414
+ __name(generateUUID, "generateUUID");
1138
1415
 
1139
- // 5. Return structured results
1140
- return {
1141
- pr_number: pr.number,
1142
- pr_title: pr.title,
1143
- action_taken: result
1144
- };
1145
- \`\`\`
1416
+ // src/telemetry/telemetry.ts
1417
+ init_logging();
1146
1418
 
1147
- Remember: Always discover and understand available tools before attempting to use them in code execution.
1148
- `;
1419
+ // src/version.ts
1420
+ var VERSION = "1.10.0-canary.11";
1421
+ function getPackageVersion() {
1422
+ return VERSION;
1423
+ }
1424
+ __name(getPackageVersion, "getPackageVersion");
1149
1425
 
1150
- // src/client/prompts.ts
1151
- var PROMPTS = {
1152
- CODE_MODE: CODE_MODE_AGENT_PROMPT
1153
- };
1426
+ // src/telemetry/utils.ts
1427
+ function getModelProvider(llm) {
1428
+ return llm._llm_type || llm.constructor.name.toLowerCase();
1429
+ }
1430
+ __name(getModelProvider, "getModelProvider");
1431
+ function getModelName(llm) {
1432
+ if ("_identifyingParams" in llm) {
1433
+ const identifyingParams = llm._identifyingParams;
1434
+ if (typeof identifyingParams === "object" && identifyingParams !== null) {
1435
+ for (const key of [
1436
+ "model",
1437
+ "modelName",
1438
+ "model_name",
1439
+ "modelId",
1440
+ "model_id",
1441
+ "deploymentName",
1442
+ "deployment_name"
1443
+ ]) {
1444
+ if (key in identifyingParams) {
1445
+ return String(identifyingParams[key]);
1446
+ }
1447
+ }
1448
+ }
1449
+ }
1450
+ return llm.model || llm.modelName || llm.constructor.name;
1451
+ }
1452
+ __name(getModelName, "getModelName");
1453
+ function extractModelInfo(llm) {
1454
+ return [getModelProvider(llm), getModelName(llm)];
1455
+ }
1456
+ __name(extractModelInfo, "extractModelInfo");
1154
1457
 
1155
- // src/agents/base.ts
1156
- var BaseAgent = class {
1458
+ // src/telemetry/telemetry.ts
1459
+ var USER_ID_STORAGE_KEY = "mcp_use_user_id";
1460
+ function detectRuntimeEnvironment() {
1461
+ try {
1462
+ if (typeof globalThis.Bun !== "undefined") {
1463
+ return "bun";
1464
+ }
1465
+ if (typeof globalThis.Deno !== "undefined") {
1466
+ return "deno";
1467
+ }
1468
+ if (typeof navigator !== "undefined" && navigator.userAgent?.includes("Cloudflare-Workers")) {
1469
+ return "cloudflare-workers";
1470
+ }
1471
+ if (typeof globalThis.EdgeRuntime !== "undefined") {
1472
+ return "edge";
1473
+ }
1474
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
1475
+ return "browser";
1476
+ }
1477
+ if (typeof process !== "undefined" && typeof process.versions?.node !== "undefined") {
1478
+ return "node";
1479
+ }
1480
+ return "unknown";
1481
+ } catch {
1482
+ return "unknown";
1483
+ }
1484
+ }
1485
+ __name(detectRuntimeEnvironment, "detectRuntimeEnvironment");
1486
+ function getStorageCapability(env) {
1487
+ switch (env) {
1488
+ case "node":
1489
+ case "bun":
1490
+ return "filesystem";
1491
+ case "browser":
1492
+ try {
1493
+ if (typeof localStorage !== "undefined") {
1494
+ localStorage.setItem("__mcp_use_test__", "1");
1495
+ localStorage.removeItem("__mcp_use_test__");
1496
+ return "localStorage";
1497
+ }
1498
+ } catch {
1499
+ }
1500
+ return "session-only";
1501
+ case "deno":
1502
+ return "session-only";
1503
+ default:
1504
+ return "session-only";
1505
+ }
1506
+ }
1507
+ __name(getStorageCapability, "getStorageCapability");
1508
+ var cachedEnvironment = null;
1509
+ function getRuntimeEnvironment() {
1510
+ if (cachedEnvironment === null) {
1511
+ cachedEnvironment = detectRuntimeEnvironment();
1512
+ }
1513
+ return cachedEnvironment;
1514
+ }
1515
+ __name(getRuntimeEnvironment, "getRuntimeEnvironment");
1516
+ var ScarfEventLogger = class {
1157
1517
  static {
1158
- __name(this, "BaseAgent");
1518
+ __name(this, "ScarfEventLogger");
1159
1519
  }
1160
- session;
1161
- /**
1162
- * @param session MCP session used for tool invocation
1163
- */
1164
- constructor(session) {
1165
- this.session = session;
1520
+ endpoint;
1521
+ timeout;
1522
+ constructor(endpoint, timeout = 3e3) {
1523
+ this.endpoint = endpoint;
1524
+ this.timeout = timeout;
1525
+ }
1526
+ async logEvent(properties) {
1527
+ try {
1528
+ const controller = new AbortController();
1529
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
1530
+ const response = await fetch(this.endpoint, {
1531
+ method: "POST",
1532
+ headers: {
1533
+ "Content-Type": "application/json"
1534
+ },
1535
+ body: JSON.stringify(properties),
1536
+ signal: controller.signal
1537
+ });
1538
+ clearTimeout(timeoutId);
1539
+ if (!response.ok) {
1540
+ throw new Error(`HTTP error! status: ${response.status}`);
1541
+ }
1542
+ } catch (error) {
1543
+ logger.debug(`Failed to send Scarf event: ${error}`);
1544
+ }
1166
1545
  }
1167
1546
  };
1168
-
1169
- // src/agents/mcp_agent.ts
1170
- var import_langchain2 = require("langchain");
1171
- var import_zod9 = require("zod");
1172
-
1173
- // src/utils/json-schema-to-zod/JSONSchemaToZod.ts
1174
- var import_zod = require("zod");
1175
- var JSONSchemaToZod = class {
1547
+ var Telemetry = class _Telemetry {
1176
1548
  static {
1177
- __name(this, "JSONSchemaToZod");
1549
+ __name(this, "Telemetry");
1178
1550
  }
1179
- /**
1180
- * Converts a JSON schema to a Zod schema.
1181
- *
1182
- * @param {JSONSchema} schema - The JSON schema.
1183
- * @returns {ZodSchema} - The Zod schema.
1184
- */
1185
- static convert(schema) {
1186
- return this.parseSchema(schema);
1551
+ static instance = null;
1552
+ PROJECT_API_KEY = "phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";
1553
+ HOST = "https://eu.i.posthog.com";
1554
+ SCARF_GATEWAY_URL = "https://mcpuse.gateway.scarf.sh/events-ts";
1555
+ UNKNOWN_USER_ID = "UNKNOWN_USER_ID";
1556
+ _currUserId = null;
1557
+ _posthogNodeClient = null;
1558
+ _posthogBrowserClient = null;
1559
+ _posthogLoading = null;
1560
+ _scarfClient = null;
1561
+ _runtimeEnvironment;
1562
+ _storageCapability;
1563
+ _source;
1564
+ // Node.js specific paths (lazily computed)
1565
+ _userIdPath = null;
1566
+ _versionDownloadPath = null;
1567
+ constructor() {
1568
+ this._runtimeEnvironment = getRuntimeEnvironment();
1569
+ this._storageCapability = getStorageCapability(this._runtimeEnvironment);
1570
+ this._source = typeof process !== "undefined" && process.env?.MCP_USE_TELEMETRY_SOURCE || this._runtimeEnvironment;
1571
+ const telemetryDisabled = this._checkTelemetryDisabled();
1572
+ const canSupportTelemetry = this._runtimeEnvironment !== "unknown";
1573
+ if (telemetryDisabled) {
1574
+ this._posthogNodeClient = null;
1575
+ this._posthogBrowserClient = null;
1576
+ this._scarfClient = null;
1577
+ logger.debug("Telemetry disabled via environment/localStorage");
1578
+ } else if (!canSupportTelemetry) {
1579
+ this._posthogNodeClient = null;
1580
+ this._posthogBrowserClient = null;
1581
+ this._scarfClient = null;
1582
+ logger.debug(
1583
+ `Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`
1584
+ );
1585
+ } else {
1586
+ logger.info(
1587
+ "Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."
1588
+ );
1589
+ this._posthogLoading = this._initPostHog();
1590
+ try {
1591
+ this._scarfClient = new ScarfEventLogger(this.SCARF_GATEWAY_URL, 3e3);
1592
+ } catch (e) {
1593
+ logger.warn(`Failed to initialize Scarf telemetry: ${e}`);
1594
+ this._scarfClient = null;
1595
+ }
1596
+ }
1187
1597
  }
1188
- /**
1189
- * Checks if data matches a condition schema.
1190
- *
1191
- * @param {JSONValue} data - The data to check.
1192
- * @param {JSONSchema} condition - The condition schema.
1193
- * @returns {boolean} - Whether the data matches the condition.
1194
- */
1195
- static matchesCondition(data, condition) {
1196
- if (!condition.properties) {
1598
+ _checkTelemetryDisabled() {
1599
+ if (typeof process !== "undefined" && process.env?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase() === "false") {
1197
1600
  return true;
1198
1601
  }
1199
- if (typeof data !== "object" || data === null || Array.isArray(data)) {
1200
- return false;
1602
+ if (typeof localStorage !== "undefined" && localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY") === "false") {
1603
+ return true;
1201
1604
  }
1202
- const objectData = data;
1203
- for (const [key, propCondition] of Object.entries(condition.properties)) {
1204
- if (!(key in objectData)) {
1205
- if ("const" in propCondition) {
1206
- return false;
1207
- }
1208
- continue;
1209
- }
1210
- const value = objectData[key];
1211
- if ("const" in propCondition && value !== propCondition["const"]) {
1212
- return false;
1213
- }
1214
- if ("minimum" in propCondition && typeof value === "number" && value < propCondition["minimum"]) {
1215
- return false;
1216
- }
1217
- if ("maximum" in propCondition && typeof value === "number" && value > propCondition["maximum"]) {
1218
- return false;
1605
+ return false;
1606
+ }
1607
+ async _initPostHog() {
1608
+ const isBrowser = this._runtimeEnvironment === "browser";
1609
+ if (isBrowser) {
1610
+ await this._initPostHogBrowser();
1611
+ } else {
1612
+ await this._initPostHogNode();
1613
+ }
1614
+ }
1615
+ async _initPostHogBrowser() {
1616
+ try {
1617
+ const posthogModule = await import("posthog-js");
1618
+ const posthog = posthogModule.default || posthogModule.posthog;
1619
+ if (!posthog || typeof posthog.init !== "function") {
1620
+ throw new Error("posthog-js module did not export expected interface");
1621
+ }
1622
+ posthog.init(this.PROJECT_API_KEY, {
1623
+ api_host: this.HOST,
1624
+ persistence: "localStorage",
1625
+ autocapture: false,
1626
+ // We only want explicit captures
1627
+ capture_pageview: false,
1628
+ // We don't want automatic pageview tracking
1629
+ disable_session_recording: true,
1630
+ // No session recording
1631
+ loaded: /* @__PURE__ */ __name(() => {
1632
+ logger.debug("PostHog browser client initialized");
1633
+ }, "loaded")
1634
+ });
1635
+ this._posthogBrowserClient = posthog;
1636
+ } catch (e) {
1637
+ logger.warn(`Failed to initialize PostHog browser telemetry: ${e}`);
1638
+ this._posthogBrowserClient = null;
1639
+ }
1640
+ }
1641
+ async _initPostHogNode() {
1642
+ try {
1643
+ const { PostHog } = await import("posthog-node");
1644
+ const isServerlessEnvironment = [
1645
+ "cloudflare-workers",
1646
+ "edge",
1647
+ "deno"
1648
+ ].includes(this._runtimeEnvironment);
1649
+ const posthogOptions = {
1650
+ host: this.HOST,
1651
+ disableGeoip: false
1652
+ };
1653
+ if (isServerlessEnvironment) {
1654
+ posthogOptions.flushAt = 1;
1655
+ posthogOptions.flushInterval = 0;
1219
1656
  }
1657
+ this._posthogNodeClient = new PostHog(
1658
+ this.PROJECT_API_KEY,
1659
+ posthogOptions
1660
+ );
1661
+ logger.debug("PostHog Node.js client initialized");
1662
+ } catch (e) {
1663
+ logger.warn(`Failed to initialize PostHog Node.js telemetry: ${e}`);
1664
+ this._posthogNodeClient = null;
1665
+ }
1666
+ }
1667
+ /**
1668
+ * Get the detected runtime environment
1669
+ */
1670
+ get runtimeEnvironment() {
1671
+ return this._runtimeEnvironment;
1672
+ }
1673
+ /**
1674
+ * Get the storage capability for this environment
1675
+ */
1676
+ get storageCapability() {
1677
+ return this._storageCapability;
1678
+ }
1679
+ static getInstance() {
1680
+ if (!_Telemetry.instance) {
1681
+ _Telemetry.instance = new _Telemetry();
1220
1682
  }
1221
- return true;
1683
+ return _Telemetry.instance;
1222
1684
  }
1223
1685
  /**
1224
- * Validates data against a conditional schema and adds issues to context if validation fails.
1225
- *
1226
- * @param {JSONValue} data - The data to validate.
1227
- * @param {JSONSchema} schema - The conditional schema.
1228
- * @param {z.RefinementCtx} ctx - The Zod refinement context.
1686
+ * Set the source identifier for telemetry events.
1687
+ * This allows tracking usage from different applications.
1688
+ * @param source - The source identifier (e.g., "my-app", "cli", "vs-code-extension")
1229
1689
  */
1230
- static validateConditionalSchema(data, schema, ctx) {
1231
- this.validateRequiredProperties(data, schema, ctx);
1232
- this.validatePropertyPatterns(data, schema, ctx);
1233
- this.validateNestedConditions(data, schema, ctx);
1690
+ setSource(source) {
1691
+ this._source = source;
1692
+ logger.debug(`Telemetry source set to: ${source}`);
1234
1693
  }
1235
1694
  /**
1236
- * Validates that all required properties are present in the data.
1237
- *
1238
- * @param {JSONValue} data - The data to validate.
1239
- * @param {JSONSchema} schema - The schema containing required properties.
1240
- * @param {z.RefinementCtx} ctx - The Zod refinement context.
1695
+ * Get the current source identifier.
1241
1696
  */
1242
- static validateRequiredProperties(data, schema, ctx) {
1243
- if (!schema.required) {
1244
- return;
1245
- }
1246
- if (typeof data !== "object" || data === null) {
1247
- for (const requiredProp of schema.required) {
1248
- ctx.addIssue({
1249
- code: import_zod.z.ZodIssueCode.custom,
1250
- message: `Required property '${requiredProp}' is missing`,
1251
- path: [requiredProp]
1252
- });
1253
- }
1254
- return;
1255
- }
1256
- for (const requiredProp of schema.required) {
1257
- if (!(requiredProp in data)) {
1258
- ctx.addIssue({
1259
- code: import_zod.z.ZodIssueCode.custom,
1260
- message: `Required property '${requiredProp}' is missing`,
1261
- path: [requiredProp]
1262
- });
1263
- }
1264
- }
1697
+ getSource() {
1698
+ return this._source;
1265
1699
  }
1266
1700
  /**
1267
- * Validates property patterns for string properties.
1268
- *
1269
- * @param {JSONValue} data - The data to validate.
1270
- * @param {JSONSchema} schema - The schema containing property patterns.
1271
- * @param {z.RefinementCtx} ctx - The Zod refinement context.
1701
+ * Check if telemetry is enabled.
1272
1702
  */
1273
- static validatePropertyPatterns(data, schema, ctx) {
1274
- if (!schema.properties) {
1275
- return;
1276
- }
1277
- if (typeof data !== "object" || data === null) {
1278
- return;
1279
- }
1280
- if (Array.isArray(data)) {
1281
- return;
1703
+ get isEnabled() {
1704
+ return this._posthogNodeClient !== null || this._posthogBrowserClient !== null || this._scarfClient !== null;
1705
+ }
1706
+ get userId() {
1707
+ if (this._currUserId) {
1708
+ return this._currUserId;
1282
1709
  }
1283
- const objectData = data;
1284
- for (const [key, propSchema] of Object.entries(schema.properties)) {
1285
- if (!(key in objectData)) {
1286
- continue;
1710
+ try {
1711
+ switch (this._storageCapability) {
1712
+ case "filesystem":
1713
+ this._currUserId = this._getUserIdFromFilesystem();
1714
+ break;
1715
+ case "localStorage":
1716
+ this._currUserId = this._getUserIdFromLocalStorage();
1717
+ break;
1718
+ case "session-only":
1719
+ default:
1720
+ this._currUserId = `session-${generateUUID()}`;
1721
+ logger.debug(
1722
+ `Using session-based user ID (${this._runtimeEnvironment} environment)`
1723
+ );
1724
+ break;
1287
1725
  }
1288
- const value = objectData[key];
1289
- if (propSchema["pattern"] && typeof value === "string") {
1290
- const regex = new RegExp(propSchema["pattern"]);
1291
- if (!regex.test(value)) {
1292
- ctx.addIssue({
1293
- code: import_zod.z.ZodIssueCode.custom,
1294
- message: `String '${value}' does not match pattern '${propSchema["pattern"]}'`,
1295
- path: [key]
1296
- });
1297
- }
1726
+ if (this._storageCapability === "filesystem" && this._currUserId) {
1727
+ this._trackPackageDownloadInternal(this._currUserId, {
1728
+ triggered_by: "user_id_property"
1729
+ }).catch((e) => logger.debug(`Failed to track package download: ${e}`));
1298
1730
  }
1731
+ } catch (e) {
1732
+ logger.debug(`Failed to get/create user ID: ${e}`);
1733
+ this._currUserId = this.UNKNOWN_USER_ID;
1299
1734
  }
1735
+ return this._currUserId;
1300
1736
  }
1301
1737
  /**
1302
- * Validates nested if-then-else conditions.
1303
- *
1304
- * @param {JSONValue} data - The data to validate.
1305
- * @param {JSONSchema} schema - The schema containing if-then-else conditions.
1306
- * @param {z.RefinementCtx} ctx - The Zod refinement context.
1738
+ * Get or create user ID from filesystem (Node.js/Bun)
1307
1739
  */
1308
- static validateNestedConditions(data, schema, ctx) {
1309
- if (!schema["if"] || !schema["then"]) {
1310
- return;
1740
+ _getUserIdFromFilesystem() {
1741
+ const fs = require("fs");
1742
+ const os = require("os");
1743
+ const path = require("path");
1744
+ if (!this._userIdPath) {
1745
+ this._userIdPath = path.join(
1746
+ this._getCacheHome(os, path),
1747
+ "mcp_use_3",
1748
+ "telemetry_user_id"
1749
+ );
1311
1750
  }
1312
- const matchesIf = this.matchesCondition(data, schema["if"]);
1313
- if (matchesIf) {
1314
- this.validateConditionalSchema(data, schema["then"], ctx);
1315
- } else if (schema["else"]) {
1316
- this.validateConditionalSchema(data, schema["else"], ctx);
1751
+ const isFirstTime = !fs.existsSync(this._userIdPath);
1752
+ if (isFirstTime) {
1753
+ logger.debug(`Creating user ID path: ${this._userIdPath}`);
1754
+ fs.mkdirSync(path.dirname(this._userIdPath), { recursive: true });
1755
+ const newUserId = generateUUID();
1756
+ fs.writeFileSync(this._userIdPath, newUserId);
1757
+ logger.debug(`User ID path created: ${this._userIdPath}`);
1758
+ return newUserId;
1317
1759
  }
1760
+ return fs.readFileSync(this._userIdPath, "utf-8").trim();
1318
1761
  }
1319
1762
  /**
1320
- * Parses a JSON schema and returns the corresponding Zod schema.
1321
- * This is the main entry point for schema conversion.
1322
- *
1323
- * @param {JSONSchema} schema - The JSON schema.
1324
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
1763
+ * Get or create user ID from localStorage (Browser)
1325
1764
  */
1326
- static parseSchema(schema) {
1327
- if (Array.isArray(schema.type)) {
1328
- return this.handleTypeArray(schema);
1329
- }
1330
- if (schema.oneOf || schema.anyOf || schema.allOf) {
1331
- return this.parseCombinator(schema);
1765
+ _getUserIdFromLocalStorage() {
1766
+ try {
1767
+ let userId = localStorage.getItem(USER_ID_STORAGE_KEY);
1768
+ if (!userId) {
1769
+ userId = generateUUID();
1770
+ localStorage.setItem(USER_ID_STORAGE_KEY, userId);
1771
+ logger.debug(`Created new browser user ID`);
1772
+ }
1773
+ return userId;
1774
+ } catch (e) {
1775
+ logger.debug(`localStorage access failed: ${e}`);
1776
+ return `session-${generateUUID()}`;
1332
1777
  }
1333
- if (schema["if"] && schema["then"]) {
1334
- return this.parseObject(schema);
1778
+ }
1779
+ _getCacheHome(os, path) {
1780
+ const envVar = process.env.XDG_CACHE_HOME;
1781
+ if (envVar && path.isAbsolute(envVar)) {
1782
+ return envVar;
1335
1783
  }
1336
- if (schema.properties && (!schema.type || schema.type === "object")) {
1337
- return this.parseObject(schema);
1784
+ const platform = process.platform;
1785
+ const homeDir = os.homedir();
1786
+ if (platform === "win32") {
1787
+ const appdata = process.env.LOCALAPPDATA || process.env.APPDATA;
1788
+ if (appdata) {
1789
+ return appdata;
1790
+ }
1791
+ return path.join(homeDir, "AppData", "Local");
1792
+ } else if (platform === "darwin") {
1793
+ return path.join(homeDir, "Library", "Caches");
1794
+ } else {
1795
+ return path.join(homeDir, ".cache");
1338
1796
  }
1339
- return this.handleSingleType(schema);
1340
1797
  }
1341
- /**
1342
- * Handles schemas with an array of types.
1343
- *
1344
- * @param {JSONSchema} schema - The JSON schema with type array.
1345
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
1346
- */
1347
- static handleTypeArray(schema) {
1348
- if (!Array.isArray(schema.type)) {
1349
- throw new Error("Expected schema.type to be an array");
1798
+ async capture(event) {
1799
+ if (this._posthogLoading) {
1800
+ await this._posthogLoading;
1350
1801
  }
1351
- if (schema.type.includes("null")) {
1352
- return this.handleNullableType(schema);
1802
+ if (!this._posthogNodeClient && !this._posthogBrowserClient && !this._scarfClient) {
1803
+ return;
1353
1804
  }
1354
- return this.createUnionFromTypes(schema.type, schema);
1355
- }
1356
- /**
1357
- * Handles nullable types by creating a nullable schema.
1358
- *
1359
- * @param {JSONSchema} schema - The JSON schema with nullable type.
1360
- * @returns {ZodTypeAny} - The nullable Zod schema.
1361
- */
1362
- static handleNullableType(schema) {
1363
- if (!Array.isArray(schema.type)) {
1364
- throw new Error("Expected schema.type to be an array");
1805
+ const properties = { ...event.properties };
1806
+ properties.mcp_use_version = getPackageVersion();
1807
+ properties.language = "typescript";
1808
+ properties.source = this._source;
1809
+ properties.runtime = this._runtimeEnvironment;
1810
+ if (this._posthogNodeClient) {
1811
+ try {
1812
+ logger.debug(`CAPTURE: PostHog Node Event ${event.name}`);
1813
+ this._posthogNodeClient.capture({
1814
+ distinctId: this.userId,
1815
+ event: event.name,
1816
+ properties
1817
+ });
1818
+ } catch (e) {
1819
+ logger.debug(`Failed to track PostHog Node event ${event.name}: ${e}`);
1820
+ }
1365
1821
  }
1366
- const nonNullSchema = { ...schema };
1367
- nonNullSchema.type = schema.type.filter((t) => t !== "null");
1368
- if (nonNullSchema.type.length === 1) {
1369
- const singleTypeSchema = this.handleSingleType({
1370
- ...schema,
1371
- type: nonNullSchema.type[0]
1372
- });
1373
- return singleTypeSchema.nullable();
1822
+ if (this._posthogBrowserClient) {
1823
+ try {
1824
+ logger.debug(`CAPTURE: PostHog Browser Event ${event.name}`);
1825
+ this._posthogBrowserClient.capture(event.name, {
1826
+ ...properties,
1827
+ distinct_id: this.userId
1828
+ });
1829
+ } catch (e) {
1830
+ logger.debug(
1831
+ `Failed to track PostHog Browser event ${event.name}: ${e}`
1832
+ );
1833
+ }
1834
+ }
1835
+ if (this._scarfClient) {
1836
+ try {
1837
+ const scarfProperties = {
1838
+ ...properties,
1839
+ user_id: this.userId,
1840
+ event: event.name
1841
+ };
1842
+ await this._scarfClient.logEvent(scarfProperties);
1843
+ } catch (e) {
1844
+ logger.debug(`Failed to track Scarf event ${event.name}: ${e}`);
1845
+ }
1374
1846
  }
1375
- const unionSchema = this.parseSchema(nonNullSchema);
1376
- return unionSchema.nullable();
1377
1847
  }
1848
+ // ============================================================================
1849
+ // Package Download Tracking (Node.js only)
1850
+ // ============================================================================
1378
1851
  /**
1379
- * Creates a union type from an array of types.
1380
- *
1381
- * @param {string[]} types - Array of type strings.
1382
- * @param {JSONSchema} baseSchema - The base schema to apply to each type.
1383
- * @returns {ZodTypeAny} - The union Zod schema.
1852
+ * Track package download event.
1853
+ * This is a public wrapper that safely accesses userId.
1384
1854
  */
1385
- static createUnionFromTypes(types, baseSchema) {
1386
- const schemas = types.map((type) => {
1387
- const singleTypeSchema = { ...baseSchema, type };
1388
- return this.parseSchema(singleTypeSchema);
1389
- });
1390
- return import_zod.z.union(schemas);
1855
+ async trackPackageDownload(properties) {
1856
+ return this._trackPackageDownloadInternal(this.userId, properties);
1391
1857
  }
1392
1858
  /**
1393
- * Handles schemas with a single type.
1394
- *
1395
- * @param {JSONSchema} schema - The JSON schema with single type.
1396
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
1859
+ * Internal method to track package download with explicit userId.
1397
1860
  */
1398
- static handleSingleType(schema) {
1399
- if (schema.type === void 0) {
1400
- if (schema.oneOf || schema.anyOf || schema.allOf) {
1401
- return this.parseCombinator(schema);
1861
+ async _trackPackageDownloadInternal(userId, properties) {
1862
+ if (!this._scarfClient) {
1863
+ return;
1864
+ }
1865
+ if (this._storageCapability !== "filesystem") {
1866
+ return;
1867
+ }
1868
+ try {
1869
+ const fs = require("fs");
1870
+ const path = require("path");
1871
+ const os = require("os");
1872
+ if (!this._versionDownloadPath) {
1873
+ this._versionDownloadPath = path.join(
1874
+ this._getCacheHome(os, path),
1875
+ "mcp_use",
1876
+ "download_version"
1877
+ );
1402
1878
  }
1403
- if (schema.properties) {
1404
- return this.parseObject(schema);
1879
+ const currentVersion = getPackageVersion();
1880
+ let shouldTrack = false;
1881
+ let firstDownload = false;
1882
+ if (!fs.existsSync(this._versionDownloadPath)) {
1883
+ shouldTrack = true;
1884
+ firstDownload = true;
1885
+ fs.mkdirSync(path.dirname(this._versionDownloadPath), {
1886
+ recursive: true
1887
+ });
1888
+ fs.writeFileSync(this._versionDownloadPath, currentVersion);
1889
+ } else {
1890
+ const savedVersion = fs.readFileSync(this._versionDownloadPath, "utf-8").trim();
1891
+ if (currentVersion > savedVersion) {
1892
+ shouldTrack = true;
1893
+ firstDownload = false;
1894
+ fs.writeFileSync(this._versionDownloadPath, currentVersion);
1895
+ }
1405
1896
  }
1406
- return import_zod.z.any();
1407
- }
1408
- switch (schema.type) {
1409
- case "string":
1410
- return this.parseString(schema);
1411
- case "number":
1412
- case "integer":
1413
- return this.parseNumberSchema(schema);
1414
- case "boolean":
1415
- return import_zod.z.boolean();
1416
- case "array":
1417
- return this.parseArray(schema);
1418
- case "object":
1419
- return this.parseObject(schema);
1420
- default:
1421
- throw new Error("Unsupported schema type");
1897
+ if (shouldTrack) {
1898
+ logger.debug(
1899
+ `Tracking package download event with properties: ${JSON.stringify(properties)}`
1900
+ );
1901
+ const eventProperties = { ...properties || {} };
1902
+ eventProperties.mcp_use_version = currentVersion;
1903
+ eventProperties.user_id = userId;
1904
+ eventProperties.event = "package_download";
1905
+ eventProperties.first_download = firstDownload;
1906
+ eventProperties.language = "typescript";
1907
+ eventProperties.source = this._source;
1908
+ eventProperties.runtime = this._runtimeEnvironment;
1909
+ await this._scarfClient.logEvent(eventProperties);
1910
+ }
1911
+ } catch (e) {
1912
+ logger.debug(`Failed to track Scarf package_download event: ${e}`);
1422
1913
  }
1423
1914
  }
1915
+ // ============================================================================
1916
+ // Agent Events
1917
+ // ============================================================================
1918
+ async trackAgentExecution(data) {
1919
+ if (!this.isEnabled) return;
1920
+ const event = new MCPAgentExecutionEvent(data);
1921
+ await this.capture(event);
1922
+ }
1923
+ // ============================================================================
1924
+ // Server Events
1925
+ // ============================================================================
1424
1926
  /**
1425
- * Parses a number schema.
1426
- *
1427
- * @param {JSONSchema} schema - The JSON schema for a number.
1428
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
1927
+ * Track server run event directly from an MCPServer instance.
1429
1928
  */
1430
- static parseNumberSchema(schema) {
1431
- const numberSchema = import_zod.z.number();
1432
- let result = numberSchema;
1433
- result = this.applyNumberBounds(numberSchema, schema);
1434
- result = this.applyNumberMultipleOf(numberSchema, schema);
1435
- result = this.applyNumberEnum(numberSchema, schema);
1436
- result = this.applyIntegerConstraint(numberSchema, schema);
1437
- return result;
1929
+ async trackServerRunFromServer(server, transport) {
1930
+ if (!this.isEnabled) return;
1931
+ const data = createServerRunEventData(server, transport);
1932
+ const event = new ServerRunEvent(data);
1933
+ await this.capture(event);
1438
1934
  }
1439
- /**
1440
- * Applies bounds validation to a number schema.
1441
- *
1442
- * @param {z.ZodNumber} numberSchema - The base number schema.
1443
- * @param {JSONSchema} schema - The JSON schema with bounds.
1444
- * @returns {z.ZodNumber} - The updated schema with bounds validation.
1445
- */
1446
- static applyNumberBounds(numberSchema, schema) {
1447
- let result = numberSchema;
1448
- if (schema["minimum"] !== void 0) {
1449
- result = schema["exclusiveMinimum"] ? result.gt(schema["minimum"]) : result.gte(schema["minimum"]);
1450
- }
1451
- if (schema["maximum"] !== void 0) {
1452
- result = schema["exclusiveMaximum"] ? result.lt(schema["maximum"]) : result.lte(schema["maximum"]);
1453
- }
1454
- return result;
1935
+ async trackServerInitialize(data) {
1936
+ if (!this.isEnabled) return;
1937
+ const event = new ServerInitializeEvent(data);
1938
+ await this.capture(event);
1455
1939
  }
1456
- /**
1457
- * Applies multipleOf validation to a number schema.
1458
- *
1459
- * @param {z.ZodNumber} numberSchema - The base number schema.
1460
- * @param {JSONSchema} schema - The JSON schema with multipleOf.
1461
- * @returns {z.ZodNumber} - The updated schema with multipleOf validation.
1462
- */
1463
- static applyNumberMultipleOf(numberSchema, schema) {
1464
- if (schema["multipleOf"] === void 0) {
1465
- return numberSchema;
1466
- }
1467
- return numberSchema.refine((val) => val % schema["multipleOf"] === 0, {
1468
- message: `Number must be a multiple of ${schema["multipleOf"]}`
1940
+ async trackServerToolCall(data) {
1941
+ if (!this.isEnabled) return;
1942
+ const event = new ServerToolCallEvent(data);
1943
+ await this.capture(event);
1944
+ }
1945
+ async trackServerResourceCall(data) {
1946
+ if (!this.isEnabled) return;
1947
+ const event = new ServerResourceCallEvent(data);
1948
+ await this.capture(event);
1949
+ }
1950
+ async trackServerPromptCall(data) {
1951
+ if (!this.isEnabled) return;
1952
+ const event = new ServerPromptCallEvent(data);
1953
+ await this.capture(event);
1954
+ }
1955
+ async trackServerContext(data) {
1956
+ if (!this.isEnabled) return;
1957
+ const event = new ServerContextEvent(data);
1958
+ await this.capture(event);
1959
+ }
1960
+ // ============================================================================
1961
+ // Client Events
1962
+ // ============================================================================
1963
+ async trackMCPClientInit(data) {
1964
+ if (!this.isEnabled) return;
1965
+ const event = new MCPClientInitEvent(data);
1966
+ await this.capture(event);
1967
+ }
1968
+ async trackConnectorInit(data) {
1969
+ if (!this.isEnabled) return;
1970
+ const event = new ConnectorInitEvent(data);
1971
+ await this.capture(event);
1972
+ }
1973
+ async trackClientAddServer(serverName, serverConfig) {
1974
+ if (!this.isEnabled) return;
1975
+ const event = new ClientAddServerEvent({ serverName, serverConfig });
1976
+ await this.capture(event);
1977
+ }
1978
+ async trackClientRemoveServer(serverName) {
1979
+ if (!this.isEnabled) return;
1980
+ const event = new ClientRemoveServerEvent({ serverName });
1981
+ await this.capture(event);
1982
+ }
1983
+ // ============================================================================
1984
+ // React Hook / Browser specific events
1985
+ // ============================================================================
1986
+ async trackUseMcpConnection(data) {
1987
+ if (!this.isEnabled) return;
1988
+ await this.capture({
1989
+ name: "usemcp_connection",
1990
+ properties: {
1991
+ url_domain: new URL(data.url).hostname,
1992
+ // Only domain for privacy
1993
+ transport_type: data.transportType,
1994
+ success: data.success,
1995
+ error_type: data.errorType ?? null,
1996
+ connection_time_ms: data.connectionTimeMs ?? null,
1997
+ has_oauth: data.hasOAuth,
1998
+ has_sampling: data.hasSampling,
1999
+ has_elicitation: data.hasElicitation
2000
+ }
1469
2001
  });
1470
2002
  }
1471
- /**
1472
- * Applies enum validation to a number schema.
1473
- *
1474
- * @param {z.ZodNumber} numberSchema - The base number schema.
1475
- * @param {JSONSchema} schema - The JSON schema with enum.
1476
- * @returns {z.ZodNumber} - The updated schema with enum validation.
1477
- */
1478
- static applyNumberEnum(numberSchema, schema) {
1479
- if (!schema.enum) {
1480
- return numberSchema;
1481
- }
1482
- const numberEnums = schema.enum.filter(
1483
- (val) => typeof val === "number"
1484
- );
1485
- if (numberEnums.length === 0) {
1486
- return numberSchema;
1487
- }
1488
- return numberSchema.refine((val) => numberEnums.includes(val), {
1489
- message: `Number must be one of: ${numberEnums.join(", ")}`
2003
+ async trackUseMcpToolCall(data) {
2004
+ if (!this.isEnabled) return;
2005
+ await this.capture({
2006
+ name: "usemcp_tool_call",
2007
+ properties: {
2008
+ tool_name: data.toolName,
2009
+ success: data.success,
2010
+ error_type: data.errorType ?? null,
2011
+ execution_time_ms: data.executionTimeMs ?? null
2012
+ }
1490
2013
  });
1491
2014
  }
2015
+ async trackUseMcpResourceRead(data) {
2016
+ if (!this.isEnabled) return;
2017
+ await this.capture({
2018
+ name: "usemcp_resource_read",
2019
+ properties: {
2020
+ resource_uri_scheme: data.resourceUri.split(":")[0],
2021
+ // Only scheme for privacy
2022
+ success: data.success,
2023
+ error_type: data.errorType ?? null
2024
+ }
2025
+ });
2026
+ }
2027
+ // ============================================================================
2028
+ // Browser-specific Methods
2029
+ // ============================================================================
1492
2030
  /**
1493
- * Applies integer constraint to a number schema if needed.
1494
- *
1495
- * @param {z.ZodNumber} numberSchema - The base number schema.
1496
- * @param {JSONSchema} schema - The JSON schema.
1497
- * @returns {z.ZodNumber} - The updated schema with integer validation if needed.
2031
+ * Identify the current user (useful for linking sessions)
2032
+ * Browser only - no-op in Node.js
1498
2033
  */
1499
- static applyIntegerConstraint(numberSchema, schema) {
1500
- if (schema.type !== "integer") {
1501
- return numberSchema;
2034
+ identify(userId, properties) {
2035
+ if (this._posthogBrowserClient) {
2036
+ try {
2037
+ this._posthogBrowserClient.identify(userId, properties);
2038
+ } catch (e) {
2039
+ logger.debug(`Failed to identify user: ${e}`);
2040
+ }
1502
2041
  }
1503
- return numberSchema.refine((val) => Number.isInteger(val), {
1504
- message: "Number must be an integer"
1505
- });
1506
2042
  }
1507
2043
  /**
1508
- * Parses a string schema.
1509
- *
1510
- * @param {JSONSchema} schema - The JSON schema for a string.
1511
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
2044
+ * Reset the user identity (useful for logout)
2045
+ * Browser only - no-op in Node.js
1512
2046
  */
1513
- static parseString(schema) {
1514
- const stringSchema = import_zod.z.string();
1515
- let result = stringSchema;
1516
- if (schema.format) {
1517
- return this.applyStringFormat(stringSchema, schema);
1518
- } else {
1519
- result = this.applyStringPattern(stringSchema, schema);
1520
- result = this.applyStringLength(stringSchema, schema);
1521
- result = this.applyStringEnum(stringSchema, schema);
2047
+ reset() {
2048
+ if (this._posthogBrowserClient) {
2049
+ try {
2050
+ this._posthogBrowserClient.reset();
2051
+ } catch (e) {
2052
+ logger.debug(`Failed to reset user: ${e}`);
2053
+ }
1522
2054
  }
1523
- return result;
2055
+ this._currUserId = null;
1524
2056
  }
2057
+ // ============================================================================
2058
+ // Node.js-specific Methods
2059
+ // ============================================================================
1525
2060
  /**
1526
- * Applies format validation to a string schema.
1527
- *
1528
- * @param {z.ZodString} stringSchema - The base string schema.
1529
- * @param {JSONSchema} schema - The JSON schema with format.
1530
- * @returns {ZodTypeAny} - The updated schema with format validation.
2061
+ * Flush the telemetry queue (Node.js only)
1531
2062
  */
1532
- static applyStringFormat(stringSchema, schema) {
1533
- if (!schema.format) {
1534
- return stringSchema;
1535
- }
1536
- switch (schema.format) {
1537
- case "email":
1538
- return stringSchema.email();
1539
- case "date-time":
1540
- return stringSchema.datetime();
1541
- case "uri":
1542
- return stringSchema.url();
1543
- case "uuid":
1544
- return stringSchema.uuid();
1545
- case "date":
1546
- return stringSchema.date();
1547
- default:
1548
- return stringSchema;
2063
+ flush() {
2064
+ if (this._posthogNodeClient) {
2065
+ try {
2066
+ this._posthogNodeClient.flush();
2067
+ logger.debug("PostHog client telemetry queue flushed");
2068
+ } catch (e) {
2069
+ logger.debug(`Failed to flush PostHog client: ${e}`);
2070
+ }
1549
2071
  }
1550
2072
  }
1551
2073
  /**
1552
- * Applies pattern validation to a string schema.
1553
- *
1554
- * @param {z.ZodString} stringSchema - The base string schema.
1555
- * @param {JSONSchema} schema - The JSON schema with pattern.
1556
- * @returns {z.ZodString} - The updated schema with pattern validation.
2074
+ * Shutdown the telemetry client (Node.js only)
1557
2075
  */
1558
- static applyStringPattern(stringSchema, schema) {
1559
- if (!schema["pattern"]) {
1560
- return stringSchema;
2076
+ shutdown() {
2077
+ if (this._posthogNodeClient) {
2078
+ try {
2079
+ this._posthogNodeClient.shutdown();
2080
+ logger.debug("PostHog client shutdown successfully");
2081
+ } catch (e) {
2082
+ logger.debug(`Error shutting down PostHog client: ${e}`);
2083
+ }
1561
2084
  }
1562
- const regex = new RegExp(schema["pattern"]);
1563
- return stringSchema.regex(regex, {
1564
- message: `String must match pattern: ${schema["pattern"]}`
2085
+ }
2086
+ };
2087
+
2088
+ // src/client/connectors/codeMode.ts
2089
+ var CODE_MODE_AGENT_PROMPT = `
2090
+ ## MCP Code Mode Tool Usage Guide
2091
+
2092
+ You have access to an MCP Code Mode Client that allows you to execute JavaScript/TypeScript code with access to registered tools. Follow this workflow:
2093
+
2094
+ ### 1. Tool Discovery Phase
2095
+ **Always start by discovering available tools:**
2096
+ - Tools are organized by server namespace (e.g., \`server_name.tool_name\`)
2097
+ - Use the \`search_tools(query, detail_level)\` function to find available tools
2098
+ - You can access \`__tool_namespaces\` to see all available server namespaces
2099
+
2100
+ \`\`\`javascript
2101
+ // Find all GitHub-related tools
2102
+ const tools = await search_tools("github");
2103
+ for (const tool of tools) {
2104
+ console.log(\`\${tool.server}.\${tool.name}: \${tool.description}\`);
2105
+ }
2106
+
2107
+ // Get only tool names for quick overview
2108
+ const tools = await search_tools("", "names");
2109
+ \`\`\`
2110
+
2111
+ ### 2. Interface Introspection
2112
+ **Understand tool contracts before using them:**
2113
+ - Use \`search_tools\` to get tool descriptions and input schemas
2114
+ - Look for "Access as: server.tool(args)" patterns in descriptions
2115
+
2116
+ ### 3. Code Execution Guidelines
2117
+ **When writing code:**
2118
+ - Use \`await server.tool({ param: value })\` syntax for all tool calls
2119
+ - Tools are async functions that return promises
2120
+ - You have access to standard JavaScript globals: \`console\`, \`JSON\`, \`Math\`, \`Date\`, etc.
2121
+ - All console output (\`console.log\`, \`console.error\`, etc.) is automatically captured and returned
2122
+ - Build properly structured input objects based on interface definitions
2123
+ - Handle errors appropriately with try/catch blocks
2124
+ - Chain tool calls by using results from previous calls
2125
+
2126
+ ### 4. Best Practices
2127
+ - **Discover first, code second**: Always explore available tools before writing execution code
2128
+ - **Respect namespaces**: Use full \`server.tool\` names to avoid conflicts
2129
+ - **Minimize Context**: Process large data in code, return only essential results
2130
+ - **Error handling**: Wrap tool calls in try/catch for robustness
2131
+ - **Data flow**: Chain tools by passing outputs as inputs to subsequent tools
2132
+
2133
+ ### 5. Available Runtime Context
2134
+ - \`search_tools(query, detail_level)\`: Function to discover tools
2135
+ - \`__tool_namespaces\`: Array of available server namespaces
2136
+ - All registered tools as \`server.tool\` functions
2137
+ - Standard JavaScript built-ins for data processing
2138
+
2139
+ ### Example Workflow
2140
+
2141
+ \`\`\`javascript
2142
+ // 1. Discover available tools
2143
+ const github_tools = await search_tools("github pull request");
2144
+ console.log(\`Available GitHub PR tools: \${github_tools.map(t => t.name)}\`);
2145
+
2146
+ // 2. Call tools with proper parameters
2147
+ const pr = await github.get_pull_request({
2148
+ owner: "facebook",
2149
+ repo: "react",
2150
+ number: 12345
2151
+ });
2152
+
2153
+ // 3. Process results
2154
+ let result;
2155
+ if (pr.state === 'open' && pr.labels.some(l => l.name === 'bug')) {
2156
+ // 4. Chain with other tools
2157
+ await slack.post_message({
2158
+ channel: "#bugs",
2159
+ text: \`\u{1F41B} Bug PR needs review: \${pr.title}\`
1565
2160
  });
2161
+ result = "Notification sent";
2162
+ } else {
2163
+ result = "No action needed";
2164
+ }
2165
+
2166
+ // 5. Return structured results
2167
+ return {
2168
+ pr_number: pr.number,
2169
+ pr_title: pr.title,
2170
+ action_taken: result
2171
+ };
2172
+ \`\`\`
2173
+
2174
+ Remember: Always discover and understand available tools before attempting to use them in code execution.
2175
+ `;
2176
+
2177
+ // src/client/prompts.ts
2178
+ var PROMPTS = {
2179
+ CODE_MODE: CODE_MODE_AGENT_PROMPT
2180
+ };
2181
+
2182
+ // src/agents/base.ts
2183
+ var BaseAgent = class {
2184
+ static {
2185
+ __name(this, "BaseAgent");
1566
2186
  }
2187
+ session;
1567
2188
  /**
1568
- * Applies length constraints to a string schema.
1569
- *
1570
- * @param {z.ZodString} stringSchema - The base string schema.
1571
- * @param {JSONSchema} schema - The JSON schema with length constraints.
1572
- * @returns {z.ZodString} - The updated schema with length validation.
2189
+ * @param session MCP session used for tool invocation
1573
2190
  */
1574
- static applyStringLength(stringSchema, schema) {
1575
- const result = stringSchema;
1576
- if (schema["minLength"] !== void 0) {
1577
- stringSchema = stringSchema.min(schema["minLength"]);
1578
- }
1579
- if (schema["maxLength"] !== void 0) {
1580
- stringSchema = stringSchema.max(schema["maxLength"]);
1581
- }
1582
- return result;
2191
+ constructor(session) {
2192
+ this.session = session;
1583
2193
  }
1584
- /**
1585
- * Applies enum validation to a string schema.
1586
- *
1587
- * @param {z.ZodString} stringSchema - The base string schema.
1588
- * @param {JSONSchema} schema - The JSON schema with enum.
1589
- * @returns {ZodTypeAny} - The updated schema with enum validation.
1590
- */
1591
- static applyStringEnum(stringSchema, schema) {
1592
- if (!schema.enum) {
1593
- return stringSchema;
1594
- }
1595
- return stringSchema.refine((val) => schema.enum?.includes(val), {
1596
- message: `Value must be one of: ${schema.enum?.join(", ")}`
1597
- });
2194
+ };
2195
+
2196
+ // src/agents/mcp_agent.ts
2197
+ var import_langchain2 = require("langchain");
2198
+ var import_zod9 = require("zod");
2199
+
2200
+ // src/utils/json-schema-to-zod/JSONSchemaToZod.ts
2201
+ var import_zod = require("zod");
2202
+ var JSONSchemaToZod = class {
2203
+ static {
2204
+ __name(this, "JSONSchemaToZod");
1598
2205
  }
1599
2206
  /**
1600
- * Parses a JSON schema of type array and returns the corresponding Zod schema.
2207
+ * Converts a JSON schema to a Zod schema.
1601
2208
  *
1602
2209
  * @param {JSONSchema} schema - The JSON schema.
1603
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
2210
+ * @returns {ZodSchema} - The Zod schema.
1604
2211
  */
1605
- static parseArray(schema) {
1606
- if (Array.isArray(schema.items)) {
1607
- const tupleSchemas = schema.items.map((item) => this.parseSchema(item));
1608
- return import_zod.z.union(tupleSchemas);
1609
- }
1610
- const itemSchema = schema.items ? this.parseSchema(schema.items) : import_zod.z.any();
1611
- const arraySchema = import_zod.z.array(itemSchema);
1612
- let result = arraySchema;
1613
- result = this.applyArrayConstraints(arraySchema, schema);
1614
- return result;
2212
+ static convert(schema) {
2213
+ return this.parseSchema(schema);
1615
2214
  }
1616
2215
  /**
1617
- * Applies constraints to an array schema.
2216
+ * Checks if data matches a condition schema.
1618
2217
  *
1619
- * @param {z.ZodArray<any>} arraySchema - The base array schema.
1620
- * @param {JSONSchema} schema - The JSON schema with array constraints.
1621
- * @returns {z.ZodTypeAny} - The updated array schema with constraints.
2218
+ * @param {JSONValue} data - The data to check.
2219
+ * @param {JSONSchema} condition - The condition schema.
2220
+ * @returns {boolean} - Whether the data matches the condition.
1622
2221
  */
1623
- static applyArrayConstraints(arraySchema, schema) {
1624
- if (schema["minItems"] !== void 0) {
1625
- arraySchema = arraySchema.min(schema["minItems"]);
2222
+ static matchesCondition(data, condition) {
2223
+ if (!condition.properties) {
2224
+ return true;
1626
2225
  }
1627
- if (schema["maxItems"] !== void 0) {
1628
- arraySchema = arraySchema.max(schema["maxItems"]);
2226
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
2227
+ return false;
1629
2228
  }
1630
- if (schema["uniqueItems"]) {
1631
- return arraySchema.refine(
1632
- (items) => new Set(items).size === items.length,
1633
- { message: "Array items must be unique" }
1634
- );
2229
+ const objectData = data;
2230
+ for (const [key, propCondition] of Object.entries(condition.properties)) {
2231
+ if (!(key in objectData)) {
2232
+ if ("const" in propCondition) {
2233
+ return false;
2234
+ }
2235
+ continue;
2236
+ }
2237
+ const value = objectData[key];
2238
+ if ("const" in propCondition && value !== propCondition["const"]) {
2239
+ return false;
2240
+ }
2241
+ if ("minimum" in propCondition && typeof value === "number" && value < propCondition["minimum"]) {
2242
+ return false;
2243
+ }
2244
+ if ("maximum" in propCondition && typeof value === "number" && value > propCondition["maximum"]) {
2245
+ return false;
2246
+ }
1635
2247
  }
1636
- return arraySchema;
2248
+ return true;
1637
2249
  }
1638
2250
  /**
1639
- * Parses an object schema.
2251
+ * Validates data against a conditional schema and adds issues to context if validation fails.
1640
2252
  *
1641
- * @param {JSONSchema} schema - The JSON schema for an object.
1642
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
2253
+ * @param {JSONValue} data - The data to validate.
2254
+ * @param {JSONSchema} schema - The conditional schema.
2255
+ * @param {z.RefinementCtx} ctx - The Zod refinement context.
1643
2256
  */
1644
- static parseObject(schema) {
1645
- if (schema["if"] && schema["then"]) {
1646
- return this.parseConditional(schema);
1647
- }
1648
- const shape = {};
1649
- this.processObjectProperties(schema, shape);
1650
- return this.processAdditionalProperties(schema, import_zod.z.object(shape));
2257
+ static validateConditionalSchema(data, schema, ctx) {
2258
+ this.validateRequiredProperties(data, schema, ctx);
2259
+ this.validatePropertyPatterns(data, schema, ctx);
2260
+ this.validateNestedConditions(data, schema, ctx);
1651
2261
  }
1652
2262
  /**
1653
- * Processes object properties and builds the shape object.
2263
+ * Validates that all required properties are present in the data.
1654
2264
  *
1655
- * @param {JSONSchema} schema - The JSON schema for an object.
1656
- * @param {Record<string, ZodTypeAny>} shape - The shape object to populate.
2265
+ * @param {JSONValue} data - The data to validate.
2266
+ * @param {JSONSchema} schema - The schema containing required properties.
2267
+ * @param {z.RefinementCtx} ctx - The Zod refinement context.
1657
2268
  */
1658
- static processObjectProperties(schema, shape) {
1659
- const required = new Set(schema.required || []);
1660
- if (!schema.properties) {
2269
+ static validateRequiredProperties(data, schema, ctx) {
2270
+ if (!schema.required) {
1661
2271
  return;
1662
2272
  }
1663
- for (const [key, propSchema] of Object.entries(schema.properties)) {
1664
- const zodSchema = this.parseSchema(propSchema);
1665
- shape[key] = required.has(key) ? zodSchema : zodSchema.optional();
1666
- }
1667
- }
1668
- /**
1669
- * Processes additionalProperties configuration.
1670
- *
1671
- * @param {JSONSchema} schema - The JSON schema for an object.
1672
- * @param {z.ZodObject<any, any>} objectSchema - The Zod object schema.
1673
- * @returns {z.ZodObject<any, any>} - The updated Zod object schema.
1674
- */
1675
- static processAdditionalProperties(schema, objectSchema) {
1676
- if (schema.additionalProperties === true) {
1677
- return objectSchema.passthrough();
1678
- } else if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
1679
- const additionalPropSchema = this.parseSchema(
1680
- schema.additionalProperties
1681
- );
1682
- return objectSchema.catchall(additionalPropSchema);
1683
- } else {
1684
- return objectSchema.strict();
2273
+ if (typeof data !== "object" || data === null) {
2274
+ for (const requiredProp of schema.required) {
2275
+ ctx.addIssue({
2276
+ code: import_zod.z.ZodIssueCode.custom,
2277
+ message: `Required property '${requiredProp}' is missing`,
2278
+ path: [requiredProp]
2279
+ });
2280
+ }
2281
+ return;
1685
2282
  }
1686
- }
1687
- /**
1688
- * Parses a conditional schema with if-then-else.
1689
- *
1690
- * @param {JSONSchema} schema - The JSON schema with conditional validation.
1691
- * @returns {ZodTypeAny} - The conditional Zod schema.
1692
- */
1693
- static parseConditional(schema) {
1694
- const zodObject = this.createBaseObjectSchema(schema);
1695
- const ifCondition = schema["if"];
1696
- const thenSchema = schema["then"];
1697
- const elseSchema = schema["else"];
1698
- return zodObject.superRefine((data, ctx) => {
1699
- const dataWithDefaults = this.applyDefaultValues(
1700
- data,
1701
- schema
1702
- );
1703
- if (this.matchesCondition(dataWithDefaults, ifCondition)) {
1704
- this.validateConditionalSchema(dataWithDefaults, thenSchema, ctx);
1705
- } else if (elseSchema) {
1706
- this.validateConditionalSchema(dataWithDefaults, elseSchema, ctx);
2283
+ for (const requiredProp of schema.required) {
2284
+ if (!(requiredProp in data)) {
2285
+ ctx.addIssue({
2286
+ code: import_zod.z.ZodIssueCode.custom,
2287
+ message: `Required property '${requiredProp}' is missing`,
2288
+ path: [requiredProp]
2289
+ });
1707
2290
  }
1708
- });
1709
- }
1710
- /**
1711
- * Creates a base object schema from the given JSON schema.
1712
- *
1713
- * @param {JSONSchema} schema - The JSON schema.
1714
- * @returns {z.ZodObject<any, any>} - The base Zod object schema.
1715
- */
1716
- static createBaseObjectSchema(schema) {
1717
- const shape = {};
1718
- const required = new Set(schema.required || []);
1719
- for (const [key, value] of Object.entries(schema.properties || {})) {
1720
- const zodSchema = this.parseSchema(value);
1721
- shape[key] = required.has(key) ? zodSchema : zodSchema.optional();
1722
2291
  }
1723
- const zodObject = import_zod.z.object(shape);
1724
- return this.processAdditionalProperties(schema, zodObject);
1725
2292
  }
1726
2293
  /**
1727
- * Applies default values from schema properties to data object.
2294
+ * Validates property patterns for string properties.
1728
2295
  *
1729
- * @param {JSONValue} data - The original data object.
1730
- * @param {JSONSchema} schema - The schema with default values.
1731
- * @returns {JSONValue} - The data object with defaults applied.
2296
+ * @param {JSONValue} data - The data to validate.
2297
+ * @param {JSONSchema} schema - The schema containing property patterns.
2298
+ * @param {z.RefinementCtx} ctx - The Zod refinement context.
1732
2299
  */
1733
- static applyDefaultValues(data, schema) {
2300
+ static validatePropertyPatterns(data, schema, ctx) {
2301
+ if (!schema.properties) {
2302
+ return;
2303
+ }
1734
2304
  if (typeof data !== "object" || data === null) {
1735
- return data;
2305
+ return;
1736
2306
  }
1737
2307
  if (Array.isArray(data)) {
1738
- return data;
2308
+ return;
1739
2309
  }
1740
2310
  const objectData = data;
1741
- const dataWithDefaults = { ...objectData };
1742
- if (!schema.properties) {
1743
- return dataWithDefaults;
2311
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
2312
+ if (!(key in objectData)) {
2313
+ continue;
2314
+ }
2315
+ const value = objectData[key];
2316
+ if (propSchema["pattern"] && typeof value === "string") {
2317
+ const regex = new RegExp(propSchema["pattern"]);
2318
+ if (!regex.test(value)) {
2319
+ ctx.addIssue({
2320
+ code: import_zod.z.ZodIssueCode.custom,
2321
+ message: `String '${value}' does not match pattern '${propSchema["pattern"]}'`,
2322
+ path: [key]
2323
+ });
2324
+ }
2325
+ }
2326
+ }
2327
+ }
2328
+ /**
2329
+ * Validates nested if-then-else conditions.
2330
+ *
2331
+ * @param {JSONValue} data - The data to validate.
2332
+ * @param {JSONSchema} schema - The schema containing if-then-else conditions.
2333
+ * @param {z.RefinementCtx} ctx - The Zod refinement context.
2334
+ */
2335
+ static validateNestedConditions(data, schema, ctx) {
2336
+ if (!schema["if"] || !schema["then"]) {
2337
+ return;
1744
2338
  }
1745
- for (const [key, propSchema] of Object.entries(schema.properties)) {
1746
- if (!(key in dataWithDefaults) && "default" in propSchema) {
1747
- dataWithDefaults[key] = propSchema["default"];
1748
- }
2339
+ const matchesIf = this.matchesCondition(data, schema["if"]);
2340
+ if (matchesIf) {
2341
+ this.validateConditionalSchema(data, schema["then"], ctx);
2342
+ } else if (schema["else"]) {
2343
+ this.validateConditionalSchema(data, schema["else"], ctx);
1749
2344
  }
1750
- return dataWithDefaults;
1751
2345
  }
1752
2346
  /**
1753
- * Parses a schema with combinators (oneOf, anyOf, allOf).
1754
- * Delegates to the appropriate combinator parser based on which combinator is present.
2347
+ * Parses a JSON schema and returns the corresponding Zod schema.
2348
+ * This is the main entry point for schema conversion.
1755
2349
  *
1756
- * @param {JSONSchema} schema - The JSON schema with combinators.
2350
+ * @param {JSONSchema} schema - The JSON schema.
1757
2351
  * @returns {ZodTypeAny} - The ZodTypeAny schema.
1758
2352
  */
1759
- static parseCombinator(schema) {
1760
- if (schema.oneOf) {
1761
- return this.parseOneOf(schema.oneOf);
2353
+ static parseSchema(schema) {
2354
+ if (Array.isArray(schema.type)) {
2355
+ return this.handleTypeArray(schema);
1762
2356
  }
1763
- if (schema.anyOf) {
1764
- return this.parseAnyOf(schema.anyOf);
2357
+ if (schema.oneOf || schema.anyOf || schema.allOf) {
2358
+ return this.parseCombinator(schema);
1765
2359
  }
1766
- if (schema.allOf) {
1767
- return this.parseAllOf(schema.allOf);
2360
+ if (schema["if"] && schema["then"]) {
2361
+ return this.parseObject(schema);
1768
2362
  }
1769
- throw new Error("Unsupported schema type");
2363
+ if (schema.properties && (!schema.type || schema.type === "object")) {
2364
+ return this.parseObject(schema);
2365
+ }
2366
+ return this.handleSingleType(schema);
1770
2367
  }
1771
2368
  /**
1772
- * Parses a oneOf combinator schema.
2369
+ * Handles schemas with an array of types.
1773
2370
  *
1774
- * @param {JSONSchema[]} schemas - Array of JSON schemas in the oneOf.
2371
+ * @param {JSONSchema} schema - The JSON schema with type array.
1775
2372
  * @returns {ZodTypeAny} - The ZodTypeAny schema.
1776
2373
  */
1777
- static parseOneOf(schemas) {
1778
- return this.createUnionFromSchemas(schemas);
2374
+ static handleTypeArray(schema) {
2375
+ if (!Array.isArray(schema.type)) {
2376
+ throw new Error("Expected schema.type to be an array");
2377
+ }
2378
+ if (schema.type.includes("null")) {
2379
+ return this.handleNullableType(schema);
2380
+ }
2381
+ return this.createUnionFromTypes(schema.type, schema);
1779
2382
  }
1780
2383
  /**
1781
- * Parses an anyOf combinator schema.
2384
+ * Handles nullable types by creating a nullable schema.
1782
2385
  *
1783
- * @param {JSONSchema[]} schemas - Array of JSON schemas in the anyOf.
1784
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
2386
+ * @param {JSONSchema} schema - The JSON schema with nullable type.
2387
+ * @returns {ZodTypeAny} - The nullable Zod schema.
1785
2388
  */
1786
- static parseAnyOf(schemas) {
1787
- return this.createUnionFromSchemas(schemas);
2389
+ static handleNullableType(schema) {
2390
+ if (!Array.isArray(schema.type)) {
2391
+ throw new Error("Expected schema.type to be an array");
2392
+ }
2393
+ const nonNullSchema = { ...schema };
2394
+ nonNullSchema.type = schema.type.filter((t) => t !== "null");
2395
+ if (nonNullSchema.type.length === 1) {
2396
+ const singleTypeSchema = this.handleSingleType({
2397
+ ...schema,
2398
+ type: nonNullSchema.type[0]
2399
+ });
2400
+ return singleTypeSchema.nullable();
2401
+ }
2402
+ const unionSchema = this.parseSchema(nonNullSchema);
2403
+ return unionSchema.nullable();
1788
2404
  }
1789
2405
  /**
1790
- * Creates a union from an array of schemas, handling special cases.
2406
+ * Creates a union type from an array of types.
1791
2407
  *
1792
- * @param {JSONSchema[]} schemas - Array of JSON schemas to create a union from.
2408
+ * @param {string[]} types - Array of type strings.
2409
+ * @param {JSONSchema} baseSchema - The base schema to apply to each type.
1793
2410
  * @returns {ZodTypeAny} - The union Zod schema.
1794
2411
  */
1795
- static createUnionFromSchemas(schemas) {
1796
- if (schemas.length === 0) {
2412
+ static createUnionFromTypes(types, baseSchema) {
2413
+ const schemas = types.map((type) => {
2414
+ const singleTypeSchema = { ...baseSchema, type };
2415
+ return this.parseSchema(singleTypeSchema);
2416
+ });
2417
+ return import_zod.z.union(schemas);
2418
+ }
2419
+ /**
2420
+ * Handles schemas with a single type.
2421
+ *
2422
+ * @param {JSONSchema} schema - The JSON schema with single type.
2423
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
2424
+ */
2425
+ static handleSingleType(schema) {
2426
+ if (schema.type === void 0) {
2427
+ if (schema.oneOf || schema.anyOf || schema.allOf) {
2428
+ return this.parseCombinator(schema);
2429
+ }
2430
+ if (schema.properties) {
2431
+ return this.parseObject(schema);
2432
+ }
1797
2433
  return import_zod.z.any();
1798
2434
  }
1799
- if (schemas.length === 1) {
1800
- return this.parseSchema(schemas[0]);
2435
+ switch (schema.type) {
2436
+ case "string":
2437
+ return this.parseString(schema);
2438
+ case "number":
2439
+ case "integer":
2440
+ return this.parseNumberSchema(schema);
2441
+ case "boolean":
2442
+ return import_zod.z.boolean();
2443
+ case "array":
2444
+ return this.parseArray(schema);
2445
+ case "object":
2446
+ return this.parseObject(schema);
2447
+ default:
2448
+ throw new Error("Unsupported schema type");
1801
2449
  }
1802
- const zodSchemas = [];
1803
- for (const subSchema of schemas) {
1804
- if (subSchema.type === "null") {
1805
- zodSchemas.push(import_zod.z.null());
1806
- } else {
1807
- zodSchemas.push(this.parseSchema(subSchema));
1808
- }
2450
+ }
2451
+ /**
2452
+ * Parses a number schema.
2453
+ *
2454
+ * @param {JSONSchema} schema - The JSON schema for a number.
2455
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
2456
+ */
2457
+ static parseNumberSchema(schema) {
2458
+ const numberSchema = import_zod.z.number();
2459
+ let result = numberSchema;
2460
+ result = this.applyNumberBounds(numberSchema, schema);
2461
+ result = this.applyNumberMultipleOf(numberSchema, schema);
2462
+ result = this.applyNumberEnum(numberSchema, schema);
2463
+ result = this.applyIntegerConstraint(numberSchema, schema);
2464
+ return result;
2465
+ }
2466
+ /**
2467
+ * Applies bounds validation to a number schema.
2468
+ *
2469
+ * @param {z.ZodNumber} numberSchema - The base number schema.
2470
+ * @param {JSONSchema} schema - The JSON schema with bounds.
2471
+ * @returns {z.ZodNumber} - The updated schema with bounds validation.
2472
+ */
2473
+ static applyNumberBounds(numberSchema, schema) {
2474
+ let result = numberSchema;
2475
+ if (schema["minimum"] !== void 0) {
2476
+ result = schema["exclusiveMinimum"] ? result.gt(schema["minimum"]) : result.gte(schema["minimum"]);
1809
2477
  }
1810
- if (zodSchemas.length >= 2) {
1811
- return import_zod.z.union(zodSchemas);
1812
- } else if (zodSchemas.length === 1) {
1813
- return zodSchemas[0];
2478
+ if (schema["maximum"] !== void 0) {
2479
+ result = schema["exclusiveMaximum"] ? result.lt(schema["maximum"]) : result.lte(schema["maximum"]);
1814
2480
  }
1815
- return import_zod.z.any();
2481
+ return result;
1816
2482
  }
1817
2483
  /**
1818
- * Parses an allOf combinator schema by merging all schemas.
2484
+ * Applies multipleOf validation to a number schema.
1819
2485
  *
1820
- * @param {JSONSchema[]} schemas - Array of JSON schemas in the allOf.
1821
- * @returns {ZodTypeAny} - The ZodTypeAny schema.
2486
+ * @param {z.ZodNumber} numberSchema - The base number schema.
2487
+ * @param {JSONSchema} schema - The JSON schema with multipleOf.
2488
+ * @returns {z.ZodNumber} - The updated schema with multipleOf validation.
1822
2489
  */
1823
- static parseAllOf(schemas) {
1824
- if (schemas.length === 0) {
1825
- return import_zod.z.any();
2490
+ static applyNumberMultipleOf(numberSchema, schema) {
2491
+ if (schema["multipleOf"] === void 0) {
2492
+ return numberSchema;
1826
2493
  }
1827
- if (schemas.length === 1) {
1828
- return this.parseSchema(schemas[0]);
2494
+ return numberSchema.refine((val) => val % schema["multipleOf"] === 0, {
2495
+ message: `Number must be a multiple of ${schema["multipleOf"]}`
2496
+ });
2497
+ }
2498
+ /**
2499
+ * Applies enum validation to a number schema.
2500
+ *
2501
+ * @param {z.ZodNumber} numberSchema - The base number schema.
2502
+ * @param {JSONSchema} schema - The JSON schema with enum.
2503
+ * @returns {z.ZodNumber} - The updated schema with enum validation.
2504
+ */
2505
+ static applyNumberEnum(numberSchema, schema) {
2506
+ if (!schema.enum) {
2507
+ return numberSchema;
1829
2508
  }
1830
- const mergedSchema = schemas.reduce(
1831
- (acc, currentSchema) => this.mergeSchemas(acc, currentSchema)
2509
+ const numberEnums = schema.enum.filter(
2510
+ (val) => typeof val === "number"
1832
2511
  );
1833
- return this.parseSchema(mergedSchema);
2512
+ if (numberEnums.length === 0) {
2513
+ return numberSchema;
2514
+ }
2515
+ return numberSchema.refine((val) => numberEnums.includes(val), {
2516
+ message: `Number must be one of: ${numberEnums.join(", ")}`
2517
+ });
1834
2518
  }
1835
2519
  /**
1836
- * Merges two JSON schemas together.
2520
+ * Applies integer constraint to a number schema if needed.
1837
2521
  *
1838
- * @param {JSONSchema} baseSchema - The base JSON schema.
1839
- * @param {JSONSchema} addSchema - The JSON schema to add.
1840
- * @returns {JSONSchema} - The merged JSON schema
2522
+ * @param {z.ZodNumber} numberSchema - The base number schema.
2523
+ * @param {JSONSchema} schema - The JSON schema.
2524
+ * @returns {z.ZodNumber} - The updated schema with integer validation if needed.
1841
2525
  */
1842
- static mergeSchemas(baseSchema, addSchema) {
1843
- const merged = { ...baseSchema, ...addSchema };
1844
- if (baseSchema.properties && addSchema.properties) {
1845
- const mergedProperties = {
1846
- ...baseSchema.properties,
1847
- ...addSchema.properties
1848
- };
1849
- merged.properties = mergedProperties;
1850
- }
1851
- if (baseSchema.required && addSchema.required) {
1852
- const mergedRequired = [
1853
- .../* @__PURE__ */ new Set([...baseSchema.required, ...addSchema.required])
1854
- ];
1855
- merged.required = mergedRequired;
2526
+ static applyIntegerConstraint(numberSchema, schema) {
2527
+ if (schema.type !== "integer") {
2528
+ return numberSchema;
1856
2529
  }
1857
- return merged;
2530
+ return numberSchema.refine((val) => Number.isInteger(val), {
2531
+ message: "Number must be an integer"
2532
+ });
1858
2533
  }
1859
- };
1860
-
1861
- // src/adapters/langchain_adapter.ts
1862
- var import_tools = require("@langchain/core/tools");
1863
- var import_zod2 = require("zod");
1864
- init_logging();
1865
-
1866
- // src/adapters/base.ts
1867
- init_logging();
1868
- var BaseAdapter = class {
1869
- static {
1870
- __name(this, "BaseAdapter");
2534
+ /**
2535
+ * Parses a string schema.
2536
+ *
2537
+ * @param {JSONSchema} schema - The JSON schema for a string.
2538
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
2539
+ */
2540
+ static parseString(schema) {
2541
+ const stringSchema = import_zod.z.string();
2542
+ let result = stringSchema;
2543
+ if (schema.format) {
2544
+ return this.applyStringFormat(stringSchema, schema);
2545
+ } else {
2546
+ result = this.applyStringPattern(stringSchema, schema);
2547
+ result = this.applyStringLength(stringSchema, schema);
2548
+ result = this.applyStringEnum(stringSchema, schema);
2549
+ }
2550
+ return result;
1871
2551
  }
1872
2552
  /**
1873
- * List of tool names that should not be available.
1874
- */
1875
- disallowedTools;
1876
- /**
1877
- * Internal cache that maps a connector instance to the list of tools
1878
- * generated for it.
2553
+ * Applies format validation to a string schema.
2554
+ *
2555
+ * @param {z.ZodString} stringSchema - The base string schema.
2556
+ * @param {JSONSchema} schema - The JSON schema with format.
2557
+ * @returns {ZodTypeAny} - The updated schema with format validation.
1879
2558
  */
1880
- connectorToolMap = /* @__PURE__ */ new Map();
1881
- constructor(disallowedTools) {
1882
- this.disallowedTools = disallowedTools ?? [];
2559
+ static applyStringFormat(stringSchema, schema) {
2560
+ if (!schema.format) {
2561
+ return stringSchema;
2562
+ }
2563
+ switch (schema.format) {
2564
+ case "email":
2565
+ return stringSchema.email();
2566
+ case "date-time":
2567
+ return stringSchema.datetime();
2568
+ case "uri":
2569
+ return stringSchema.url();
2570
+ case "uuid":
2571
+ return stringSchema.uuid();
2572
+ case "date":
2573
+ return stringSchema.date();
2574
+ default:
2575
+ return stringSchema;
2576
+ }
1883
2577
  }
1884
2578
  /**
1885
- * Create tools from an MCPClient instance.
1886
- *
1887
- * This is the recommended way to create tools from an MCPClient, as it handles
1888
- * session creation and connector extraction automatically.
2579
+ * Applies pattern validation to a string schema.
1889
2580
  *
1890
- * @param client The MCPClient to extract tools from.
1891
- * @param disallowedTools Optional list of tool names to exclude.
1892
- * @returns A promise that resolves with a list of converted tools.
2581
+ * @param {z.ZodString} stringSchema - The base string schema.
2582
+ * @param {JSONSchema} schema - The JSON schema with pattern.
2583
+ * @returns {z.ZodString} - The updated schema with pattern validation.
1893
2584
  */
1894
- static async createTools(client, disallowedTools) {
1895
- const adapter = new this(disallowedTools);
1896
- if (!client.activeSessions || Object.keys(client.activeSessions).length === 0) {
1897
- logger.info("No active sessions found, creating new ones...");
1898
- await client.createAllSessions();
2585
+ static applyStringPattern(stringSchema, schema) {
2586
+ if (!schema["pattern"]) {
2587
+ return stringSchema;
1899
2588
  }
1900
- const sessions = client.getAllActiveSessions();
1901
- const connectors = Object.values(sessions).map(
1902
- (session) => session.connector
1903
- );
1904
- return adapter.createToolsFromConnectors(connectors);
2589
+ const regex = new RegExp(schema["pattern"]);
2590
+ return stringSchema.regex(regex, {
2591
+ message: `String must match pattern: ${schema["pattern"]}`
2592
+ });
1905
2593
  }
1906
2594
  /**
1907
- * Dynamically load tools for a specific connector.
2595
+ * Applies length constraints to a string schema.
1908
2596
  *
1909
- * @param connector The connector to load tools for.
1910
- * @returns The list of tools that were loaded in the target framework's format.
2597
+ * @param {z.ZodString} stringSchema - The base string schema.
2598
+ * @param {JSONSchema} schema - The JSON schema with length constraints.
2599
+ * @returns {z.ZodString} - The updated schema with length validation.
1911
2600
  */
1912
- async loadToolsForConnector(connector) {
1913
- if (this.connectorToolMap.has(connector)) {
1914
- const cached = this.connectorToolMap.get(connector);
1915
- logger.debug(`Returning ${cached.length} existing tools for connector`);
1916
- return cached;
1917
- }
1918
- const connectorTools = [];
1919
- const success = await this.ensureConnectorInitialized(connector);
1920
- if (!success) {
1921
- return [];
2601
+ static applyStringLength(stringSchema, schema) {
2602
+ const result = stringSchema;
2603
+ if (schema["minLength"] !== void 0) {
2604
+ stringSchema = stringSchema.min(schema["minLength"]);
1922
2605
  }
1923
- for (const tool of connector.tools) {
1924
- const converted = this.convertTool(tool, connector);
1925
- if (converted) {
1926
- connectorTools.push(converted);
1927
- }
2606
+ if (schema["maxLength"] !== void 0) {
2607
+ stringSchema = stringSchema.max(schema["maxLength"]);
1928
2608
  }
1929
- this.connectorToolMap.set(connector, connectorTools);
1930
- logger.debug(
1931
- `Loaded ${connectorTools.length} new tools for connector: ${connectorTools.map((t) => t?.name ?? String(t)).join(", ")}`
1932
- );
1933
- return connectorTools;
2609
+ return result;
1934
2610
  }
1935
2611
  /**
1936
- * Create tools from MCP tools in all provided connectors.
2612
+ * Applies enum validation to a string schema.
1937
2613
  *
1938
- * @param connectors List of MCP connectors to create tools from.
1939
- * @returns A promise that resolves with all converted tools.
2614
+ * @param {z.ZodString} stringSchema - The base string schema.
2615
+ * @param {JSONSchema} schema - The JSON schema with enum.
2616
+ * @returns {ZodTypeAny} - The updated schema with enum validation.
1940
2617
  */
1941
- async createToolsFromConnectors(connectors) {
1942
- const tools = [];
1943
- for (const connector of connectors) {
1944
- const connectorTools = await this.loadToolsForConnector(connector);
1945
- tools.push(...connectorTools);
2618
+ static applyStringEnum(stringSchema, schema) {
2619
+ if (!schema.enum) {
2620
+ return stringSchema;
1946
2621
  }
1947
- logger.debug(`Available tools: ${tools.length}`);
1948
- return tools;
2622
+ return stringSchema.refine((val) => schema.enum?.includes(val), {
2623
+ message: `Value must be one of: ${schema.enum?.join(", ")}`
2624
+ });
1949
2625
  }
1950
2626
  /**
1951
- * Check if a connector is initialized and has tools.
2627
+ * Parses a JSON schema of type array and returns the corresponding Zod schema.
1952
2628
  *
1953
- * @param connector The connector to check.
1954
- * @returns True if the connector is initialized and has tools, false otherwise.
2629
+ * @param {JSONSchema} schema - The JSON schema.
2630
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
1955
2631
  */
1956
- checkConnectorInitialized(connector) {
1957
- return Boolean(connector.tools && connector.tools.length);
2632
+ static parseArray(schema) {
2633
+ if (Array.isArray(schema.items)) {
2634
+ const tupleSchemas = schema.items.map((item) => this.parseSchema(item));
2635
+ return import_zod.z.union(tupleSchemas);
2636
+ }
2637
+ const itemSchema = schema.items ? this.parseSchema(schema.items) : import_zod.z.any();
2638
+ const arraySchema = import_zod.z.array(itemSchema);
2639
+ let result = arraySchema;
2640
+ result = this.applyArrayConstraints(arraySchema, schema);
2641
+ return result;
1958
2642
  }
1959
2643
  /**
1960
- * Ensure a connector is initialized.
2644
+ * Applies constraints to an array schema.
1961
2645
  *
1962
- * @param connector The connector to initialize.
1963
- * @returns True if initialization succeeded, false otherwise.
2646
+ * @param {z.ZodArray<any>} arraySchema - The base array schema.
2647
+ * @param {JSONSchema} schema - The JSON schema with array constraints.
2648
+ * @returns {z.ZodTypeAny} - The updated array schema with constraints.
1964
2649
  */
1965
- async ensureConnectorInitialized(connector) {
1966
- if (!this.checkConnectorInitialized(connector)) {
1967
- logger.debug("Connector doesn't have tools, initializing it");
1968
- try {
1969
- await connector.initialize();
1970
- return true;
1971
- } catch (err) {
1972
- logger.error(`Error initializing connector: ${err}`);
1973
- return false;
1974
- }
2650
+ static applyArrayConstraints(arraySchema, schema) {
2651
+ if (schema["minItems"] !== void 0) {
2652
+ arraySchema = arraySchema.min(schema["minItems"]);
1975
2653
  }
1976
- return true;
1977
- }
1978
- };
1979
-
1980
- // src/adapters/langchain_adapter.ts
1981
- function schemaToZod(schema) {
1982
- try {
1983
- return JSONSchemaToZod.convert(schema);
1984
- } catch (err) {
1985
- logger.warn(`Failed to convert JSON schema to Zod: ${err}`);
1986
- return import_zod2.z.any();
1987
- }
1988
- }
1989
- __name(schemaToZod, "schemaToZod");
1990
- var LangChainAdapter = class extends BaseAdapter {
1991
- static {
1992
- __name(this, "LangChainAdapter");
1993
- }
1994
- constructor(disallowedTools = []) {
1995
- super(disallowedTools);
1996
- }
1997
- /**
1998
- * Convert a single MCP tool specification into a LangChainJS structured tool.
1999
- */
2000
- convertTool(mcpTool, connector) {
2001
- if (this.disallowedTools.includes(mcpTool.name)) {
2002
- return null;
2654
+ if (schema["maxItems"] !== void 0) {
2655
+ arraySchema = arraySchema.max(schema["maxItems"]);
2003
2656
  }
2004
- const argsSchema = mcpTool.inputSchema ? schemaToZod(mcpTool.inputSchema) : import_zod2.z.object({}).optional();
2005
- const tool = new import_tools.DynamicStructuredTool({
2006
- name: mcpTool.name ?? "NO NAME",
2007
- description: mcpTool.description ?? "",
2008
- // Blank is acceptable but discouraged.
2009
- schema: argsSchema,
2010
- func: /* @__PURE__ */ __name(async (input) => {
2011
- logger.debug(
2012
- `MCP tool "${mcpTool.name}" received input: ${JSON.stringify(input)}`
2013
- );
2014
- try {
2015
- const result = await connector.callTool(
2016
- mcpTool.name,
2017
- input
2018
- );
2019
- return JSON.stringify(result);
2020
- } catch (err) {
2021
- logger.error(`Error executing MCP tool: ${err.message}`);
2022
- return `Error executing MCP tool: ${String(err)}`;
2023
- }
2024
- }, "func")
2025
- });
2026
- return tool;
2027
- }
2028
- };
2029
-
2030
- // src/agents/mcp_agent.ts
2031
- init_logging();
2032
-
2033
- // src/managers/server_manager.ts
2034
- init_logging();
2035
-
2036
- // src/managers/tools/acquire_active_mcp_server.ts
2037
- var import_zod3 = require("zod");
2038
-
2039
- // src/managers/tools/base.ts
2040
- var import_tools2 = require("@langchain/core/tools");
2041
- var MCPServerTool = class extends import_tools2.StructuredTool {
2042
- static {
2043
- __name(this, "MCPServerTool");
2044
- }
2045
- name = "mcp_server_tool";
2046
- description = "Base tool for MCP server operations.";
2047
- schema;
2048
- _manager;
2049
- constructor(manager) {
2050
- super();
2051
- this._manager = manager;
2052
- }
2053
- async _call(_arg, _runManager, _parentConfig) {
2054
- throw new Error("Method not implemented.");
2055
- }
2056
- get manager() {
2057
- return this._manager;
2058
- }
2059
- };
2060
-
2061
- // src/managers/tools/acquire_active_mcp_server.ts
2062
- var PresentActiveServerSchema = import_zod3.z.object({});
2063
- var AcquireActiveMCPServerTool = class extends MCPServerTool {
2064
- static {
2065
- __name(this, "AcquireActiveMCPServerTool");
2066
- }
2067
- name = "get_active_mcp_server";
2068
- description = "Get the currently active MCP (Model Context Protocol) server";
2069
- schema = PresentActiveServerSchema;
2070
- constructor(manager) {
2071
- super(manager);
2072
- }
2073
- async _call() {
2074
- if (!this.manager.activeServer) {
2075
- return `No MCP server is currently active. Use connect_to_mcp_server to connect to a server.`;
2657
+ if (schema["uniqueItems"]) {
2658
+ return arraySchema.refine(
2659
+ (items) => new Set(items).size === items.length,
2660
+ { message: "Array items must be unique" }
2661
+ );
2076
2662
  }
2077
- return `Currently active MCP server: ${this.manager.activeServer}`;
2663
+ return arraySchema;
2078
2664
  }
2079
- };
2080
-
2081
- // src/managers/tools/add_server_from_config.ts
2082
- var import_tools3 = require("@langchain/core/tools");
2083
- var import_zod4 = require("zod");
2084
- init_logging();
2085
- var AddMCPServerFromConfigTool = class extends import_tools3.StructuredTool {
2086
- static {
2087
- __name(this, "AddMCPServerFromConfigTool");
2665
+ /**
2666
+ * Parses an object schema.
2667
+ *
2668
+ * @param {JSONSchema} schema - The JSON schema for an object.
2669
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
2670
+ */
2671
+ static parseObject(schema) {
2672
+ if (schema["if"] && schema["then"]) {
2673
+ return this.parseConditional(schema);
2674
+ }
2675
+ const shape = {};
2676
+ this.processObjectProperties(schema, shape);
2677
+ return this.processAdditionalProperties(schema, import_zod.z.object(shape));
2088
2678
  }
2089
- name = "add_mcp_server_from_config";
2090
- description = "Adds a new MCP server to the client from a configuration object and connects to it, making its tools available.";
2091
- schema = import_zod4.z.object({
2092
- serverName: import_zod4.z.string().describe("The name for the new MCP server."),
2093
- serverConfig: import_zod4.z.any().describe(
2094
- 'The configuration object for the server. This should not include the top-level "mcpServers" key.'
2095
- )
2096
- });
2097
- manager;
2098
- constructor(manager) {
2099
- super();
2100
- this.manager = manager;
2679
+ /**
2680
+ * Processes object properties and builds the shape object.
2681
+ *
2682
+ * @param {JSONSchema} schema - The JSON schema for an object.
2683
+ * @param {Record<string, ZodTypeAny>} shape - The shape object to populate.
2684
+ */
2685
+ static processObjectProperties(schema, shape) {
2686
+ const required = new Set(schema.required || []);
2687
+ if (!schema.properties) {
2688
+ return;
2689
+ }
2690
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
2691
+ const zodSchema = this.parseSchema(propSchema);
2692
+ shape[key] = required.has(key) ? zodSchema : zodSchema.optional();
2693
+ }
2101
2694
  }
2102
- async _call({
2103
- serverName,
2104
- serverConfig
2105
- }) {
2106
- try {
2107
- this.manager.client.addServer(serverName, serverConfig);
2108
- let result = `Server '${serverName}' added to the client.`;
2109
- logger.debug(
2110
- `Connecting to new server '${serverName}' and discovering tools.`
2111
- );
2112
- const session = await this.manager.client.createSession(serverName);
2113
- const connector = session.connector;
2114
- const tools = await this.manager.adapter.createToolsFromConnectors([connector]);
2115
- this.manager.serverTools[serverName] = tools;
2116
- this.manager.initializedServers[serverName] = true;
2117
- this.manager.activeServer = serverName;
2118
- const numTools = tools.length;
2119
- result += ` Session created and connected. '${serverName}' is now the active server with ${numTools} tools available.`;
2120
- result += `
2121
-
2122
- ${tools.map((t) => t.name).join("\n")}`;
2123
- logger.info(result);
2124
- return result;
2125
- } catch (e) {
2126
- logger.error(
2127
- `Failed to add or connect to server '${serverName}': ${e.message}`
2695
+ /**
2696
+ * Processes additionalProperties configuration.
2697
+ *
2698
+ * @param {JSONSchema} schema - The JSON schema for an object.
2699
+ * @param {z.ZodObject<any, any>} objectSchema - The Zod object schema.
2700
+ * @returns {z.ZodObject<any, any>} - The updated Zod object schema.
2701
+ */
2702
+ static processAdditionalProperties(schema, objectSchema) {
2703
+ if (schema.additionalProperties === true) {
2704
+ return objectSchema.passthrough();
2705
+ } else if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
2706
+ const additionalPropSchema = this.parseSchema(
2707
+ schema.additionalProperties
2128
2708
  );
2129
- return `Failed to add or connect to server '${serverName}': ${e.message}`;
2709
+ return objectSchema.catchall(additionalPropSchema);
2710
+ } else {
2711
+ return objectSchema.strict();
2130
2712
  }
2131
2713
  }
2132
- };
2133
-
2134
- // src/managers/tools/connect_mcp_server.ts
2135
- var import_zod5 = require("zod");
2136
- init_logging();
2137
- var ConnectMCPServerSchema = import_zod5.z.object({
2138
- serverName: import_zod5.z.string().describe("The name of the MCP server.")
2139
- });
2140
- var ConnectMCPServerTool = class extends MCPServerTool {
2141
- static {
2142
- __name(this, "ConnectMCPServerTool");
2714
+ /**
2715
+ * Parses a conditional schema with if-then-else.
2716
+ *
2717
+ * @param {JSONSchema} schema - The JSON schema with conditional validation.
2718
+ * @returns {ZodTypeAny} - The conditional Zod schema.
2719
+ */
2720
+ static parseConditional(schema) {
2721
+ const zodObject = this.createBaseObjectSchema(schema);
2722
+ const ifCondition = schema["if"];
2723
+ const thenSchema = schema["then"];
2724
+ const elseSchema = schema["else"];
2725
+ return zodObject.superRefine((data, ctx) => {
2726
+ const dataWithDefaults = this.applyDefaultValues(
2727
+ data,
2728
+ schema
2729
+ );
2730
+ if (this.matchesCondition(dataWithDefaults, ifCondition)) {
2731
+ this.validateConditionalSchema(dataWithDefaults, thenSchema, ctx);
2732
+ } else if (elseSchema) {
2733
+ this.validateConditionalSchema(dataWithDefaults, elseSchema, ctx);
2734
+ }
2735
+ });
2143
2736
  }
2144
- name = "connect_to_mcp_server";
2145
- description = "Connect to a specific MCP (Model Context Protocol) server to use its tools. Use this tool to connect to a specific server and use its tools.";
2146
- schema = ConnectMCPServerSchema;
2147
- constructor(manager) {
2148
- super(manager);
2737
+ /**
2738
+ * Creates a base object schema from the given JSON schema.
2739
+ *
2740
+ * @param {JSONSchema} schema - The JSON schema.
2741
+ * @returns {z.ZodObject<any, any>} - The base Zod object schema.
2742
+ */
2743
+ static createBaseObjectSchema(schema) {
2744
+ const shape = {};
2745
+ const required = new Set(schema.required || []);
2746
+ for (const [key, value] of Object.entries(schema.properties || {})) {
2747
+ const zodSchema = this.parseSchema(value);
2748
+ shape[key] = required.has(key) ? zodSchema : zodSchema.optional();
2749
+ }
2750
+ const zodObject = import_zod.z.object(shape);
2751
+ return this.processAdditionalProperties(schema, zodObject);
2149
2752
  }
2150
- async _call({ serverName }) {
2151
- const serverNames = this.manager.client.getServerNames();
2152
- if (!serverNames.includes(serverName)) {
2153
- const available = serverNames.length > 0 ? serverNames.join(", ") : "none";
2154
- return `Server '${serverName}' not found. Available servers: ${available}`;
2753
+ /**
2754
+ * Applies default values from schema properties to data object.
2755
+ *
2756
+ * @param {JSONValue} data - The original data object.
2757
+ * @param {JSONSchema} schema - The schema with default values.
2758
+ * @returns {JSONValue} - The data object with defaults applied.
2759
+ */
2760
+ static applyDefaultValues(data, schema) {
2761
+ if (typeof data !== "object" || data === null) {
2762
+ return data;
2155
2763
  }
2156
- if (this.manager.activeServer === serverName) {
2157
- return `Already connected to MCP server '${serverName}'`;
2764
+ if (Array.isArray(data)) {
2765
+ return data;
2158
2766
  }
2159
- try {
2160
- let session = this.manager.client.getSession(serverName);
2161
- logger.debug(`Using existing session for server '${serverName}'`);
2162
- if (!session) {
2163
- logger.debug(`Creating new session for server '${serverName}'`);
2164
- session = await this.manager.client.createSession(serverName);
2165
- }
2166
- this.manager.activeServer = serverName;
2167
- if (this.manager.serverTools[serverName]) {
2168
- const connector = session.connector;
2169
- const tools = await this.manager.adapter.createToolsFromConnectors([connector]);
2170
- this.manager.serverTools[serverName] = tools;
2171
- this.manager.initializedServers[serverName] = true;
2767
+ const objectData = data;
2768
+ const dataWithDefaults = { ...objectData };
2769
+ if (!schema.properties) {
2770
+ return dataWithDefaults;
2771
+ }
2772
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
2773
+ if (!(key in dataWithDefaults) && "default" in propSchema) {
2774
+ dataWithDefaults[key] = propSchema["default"];
2172
2775
  }
2173
- const serverTools = this.manager.serverTools[serverName] || [];
2174
- const numTools = serverTools.length;
2175
- return `Connected to MCP server '${serverName}'. ${numTools} tools are now available.`;
2176
- } catch (error) {
2177
- logger.error(
2178
- `Error connecting to server '${serverName}': ${String(error)}`
2179
- );
2180
- return `Failed to connect to server '${serverName}': ${String(error)}`;
2181
2776
  }
2777
+ return dataWithDefaults;
2182
2778
  }
2183
- };
2184
-
2185
- // src/managers/tools/list_mcp_servers.ts
2186
- var import_zod6 = require("zod");
2187
- init_logging();
2188
- var EnumerateServersSchema = import_zod6.z.object({});
2189
- var ListMCPServersTool = class extends MCPServerTool {
2190
- static {
2191
- __name(this, "ListMCPServersTool");
2779
+ /**
2780
+ * Parses a schema with combinators (oneOf, anyOf, allOf).
2781
+ * Delegates to the appropriate combinator parser based on which combinator is present.
2782
+ *
2783
+ * @param {JSONSchema} schema - The JSON schema with combinators.
2784
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
2785
+ */
2786
+ static parseCombinator(schema) {
2787
+ if (schema.oneOf) {
2788
+ return this.parseOneOf(schema.oneOf);
2789
+ }
2790
+ if (schema.anyOf) {
2791
+ return this.parseAnyOf(schema.anyOf);
2792
+ }
2793
+ if (schema.allOf) {
2794
+ return this.parseAllOf(schema.allOf);
2795
+ }
2796
+ throw new Error("Unsupported schema type");
2192
2797
  }
2193
- name = "list_mcp_servers";
2194
- description = `Lists all available MCP (Model Context Protocol) servers that can be connected to, along with the tools available on each server. Use this tool to discover servers and see what functionalities they offer.`;
2195
- schema = EnumerateServersSchema;
2196
- constructor(manager) {
2197
- super(manager);
2798
+ /**
2799
+ * Parses a oneOf combinator schema.
2800
+ *
2801
+ * @param {JSONSchema[]} schemas - Array of JSON schemas in the oneOf.
2802
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
2803
+ */
2804
+ static parseOneOf(schemas) {
2805
+ return this.createUnionFromSchemas(schemas);
2198
2806
  }
2199
- async _call() {
2200
- const serverNames = this.manager.client.getServerNames();
2201
- if (serverNames.length === 0) {
2202
- return `No MCP servers are currently defined.`;
2807
+ /**
2808
+ * Parses an anyOf combinator schema.
2809
+ *
2810
+ * @param {JSONSchema[]} schemas - Array of JSON schemas in the anyOf.
2811
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
2812
+ */
2813
+ static parseAnyOf(schemas) {
2814
+ return this.createUnionFromSchemas(schemas);
2815
+ }
2816
+ /**
2817
+ * Creates a union from an array of schemas, handling special cases.
2818
+ *
2819
+ * @param {JSONSchema[]} schemas - Array of JSON schemas to create a union from.
2820
+ * @returns {ZodTypeAny} - The union Zod schema.
2821
+ */
2822
+ static createUnionFromSchemas(schemas) {
2823
+ if (schemas.length === 0) {
2824
+ return import_zod.z.any();
2203
2825
  }
2204
- const outputLines = ["Available MCP servers:"];
2205
- for (const serverName of serverNames) {
2206
- const isActiveServer = serverName === this.manager.activeServer;
2207
- const activeFlag = isActiveServer ? " (ACTIVE)" : "";
2208
- outputLines.push(`- ${serverName}${activeFlag}`);
2209
- try {
2210
- const serverTools = this.manager.serverTools?.[serverName] ?? [];
2211
- const numberOfTools = Array.isArray(serverTools) ? serverTools.length : 0;
2212
- outputLines.push(`${numberOfTools} tools available for this server
2213
- `);
2214
- } catch (error) {
2215
- logger.error(
2216
- `Unexpected error listing tools for server '${serverName}': ${String(error)}`
2217
- );
2826
+ if (schemas.length === 1) {
2827
+ return this.parseSchema(schemas[0]);
2828
+ }
2829
+ const zodSchemas = [];
2830
+ for (const subSchema of schemas) {
2831
+ if (subSchema.type === "null") {
2832
+ zodSchemas.push(import_zod.z.null());
2833
+ } else {
2834
+ zodSchemas.push(this.parseSchema(subSchema));
2218
2835
  }
2219
2836
  }
2220
- return outputLines.join("\n");
2221
- }
2222
- };
2223
-
2224
- // src/managers/tools/release_mcp_server_connection.ts
2225
- var import_zod7 = require("zod");
2226
- var ReleaseConnectionSchema = import_zod7.z.object({});
2227
- var ReleaseMCPServerConnectionTool = class extends MCPServerTool {
2228
- static {
2229
- __name(this, "ReleaseMCPServerConnectionTool");
2837
+ if (zodSchemas.length >= 2) {
2838
+ return import_zod.z.union(zodSchemas);
2839
+ } else if (zodSchemas.length === 1) {
2840
+ return zodSchemas[0];
2841
+ }
2842
+ return import_zod.z.any();
2230
2843
  }
2231
- name = "disconnect_from_mcp_server";
2232
- description = "Disconnect from the currently active MCP (Model Context Protocol) server";
2233
- schema = ReleaseConnectionSchema;
2234
- constructor(manager) {
2235
- super(manager);
2844
+ /**
2845
+ * Parses an allOf combinator schema by merging all schemas.
2846
+ *
2847
+ * @param {JSONSchema[]} schemas - Array of JSON schemas in the allOf.
2848
+ * @returns {ZodTypeAny} - The ZodTypeAny schema.
2849
+ */
2850
+ static parseAllOf(schemas) {
2851
+ if (schemas.length === 0) {
2852
+ return import_zod.z.any();
2853
+ }
2854
+ if (schemas.length === 1) {
2855
+ return this.parseSchema(schemas[0]);
2856
+ }
2857
+ const mergedSchema = schemas.reduce(
2858
+ (acc, currentSchema) => this.mergeSchemas(acc, currentSchema)
2859
+ );
2860
+ return this.parseSchema(mergedSchema);
2236
2861
  }
2237
- async _call() {
2238
- if (!this.manager.activeServer) {
2239
- return `No MCP server is currently active, so there's nothing to disconnect from.`;
2862
+ /**
2863
+ * Merges two JSON schemas together.
2864
+ *
2865
+ * @param {JSONSchema} baseSchema - The base JSON schema.
2866
+ * @param {JSONSchema} addSchema - The JSON schema to add.
2867
+ * @returns {JSONSchema} - The merged JSON schema
2868
+ */
2869
+ static mergeSchemas(baseSchema, addSchema) {
2870
+ const merged = { ...baseSchema, ...addSchema };
2871
+ if (baseSchema.properties && addSchema.properties) {
2872
+ const mergedProperties = {
2873
+ ...baseSchema.properties,
2874
+ ...addSchema.properties
2875
+ };
2876
+ merged.properties = mergedProperties;
2240
2877
  }
2241
- const serverName = this.manager.activeServer;
2242
- this.manager.activeServer = null;
2243
- return `Successfully disconnected from MCP server '${serverName}'.`;
2878
+ if (baseSchema.required && addSchema.required) {
2879
+ const mergedRequired = [
2880
+ .../* @__PURE__ */ new Set([...baseSchema.required, ...addSchema.required])
2881
+ ];
2882
+ merged.required = mergedRequired;
2883
+ }
2884
+ return merged;
2244
2885
  }
2245
2886
  };
2246
2887
 
2247
- // src/managers/server_manager.ts
2248
- function isEqual(a, b) {
2249
- if (a === b) return true;
2250
- if (a == null || b == null) return false;
2251
- if (typeof a !== typeof b) return false;
2252
- if (a instanceof Date && b instanceof Date) {
2253
- return a.getTime() === b.getTime();
2254
- }
2255
- if (Array.isArray(a) && Array.isArray(b)) {
2256
- if (a.length !== b.length) return false;
2257
- return a.every((item, index) => isEqual(item, b[index]));
2258
- }
2259
- if (typeof a === "object" && typeof b === "object") {
2260
- const keysA = Object.keys(a);
2261
- const keysB = Object.keys(b);
2262
- if (keysA.length !== keysB.length) return false;
2263
- return keysA.every((key) => {
2264
- return Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]);
2265
- });
2266
- }
2267
- return false;
2268
- }
2269
- __name(isEqual, "isEqual");
2270
- var ServerManager = class {
2888
+ // src/adapters/langchain_adapter.ts
2889
+ var import_tools = require("@langchain/core/tools");
2890
+ var import_zod2 = require("zod");
2891
+ init_logging();
2892
+
2893
+ // src/adapters/base.ts
2894
+ init_logging();
2895
+ var BaseAdapter = class {
2271
2896
  static {
2272
- __name(this, "ServerManager");
2273
- }
2274
- initializedServers = {};
2275
- serverTools = {};
2276
- client;
2277
- adapter;
2278
- activeServer = null;
2279
- overrideManagementTools;
2280
- constructor(client, adapter, managementTools) {
2281
- this.client = client;
2282
- this.adapter = adapter;
2283
- this.overrideManagementTools = managementTools;
2284
- }
2285
- setManagementTools(tools) {
2286
- this.overrideManagementTools = tools;
2287
- logger.info(
2288
- `Overriding default management tools with a new set of ${tools.length} tools.`
2289
- );
2897
+ __name(this, "BaseAdapter");
2290
2898
  }
2291
- logState(context) {
2292
- const allServerNames = this.client.getServerNames();
2293
- const activeSessionNames = Object.keys(this.client.getAllActiveSessions());
2294
- if (allServerNames.length === 0) {
2295
- logger.info("Server Manager State: No servers configured.");
2296
- return;
2297
- }
2298
- const tableData = allServerNames.map((name) => ({
2299
- "Server Name": name,
2300
- Connected: activeSessionNames.includes(name) ? "\u2705" : "\u274C",
2301
- Initialized: this.initializedServers[name] ? "\u2705" : "\u274C",
2302
- "Tool Count": this.serverTools[name]?.length ?? 0,
2303
- Active: this.activeServer === name ? "\u2705" : "\u274C"
2304
- }));
2305
- logger.info(`Server Manager State: [${context}]`);
2306
- console.table(tableData);
2899
+ /**
2900
+ * List of tool names that should not be available.
2901
+ */
2902
+ disallowedTools;
2903
+ /**
2904
+ * Internal cache that maps a connector instance to the list of tools
2905
+ * generated for it.
2906
+ */
2907
+ connectorToolMap = /* @__PURE__ */ new Map();
2908
+ constructor(disallowedTools) {
2909
+ this.disallowedTools = disallowedTools ?? [];
2307
2910
  }
2308
- initialize() {
2309
- const serverNames = this.client.getServerNames?.();
2310
- if (serverNames.length === 0) {
2311
- logger.warn("No MCP servers defined in client configuration");
2911
+ /**
2912
+ * Create tools from an MCPClient instance.
2913
+ *
2914
+ * This is the recommended way to create tools from an MCPClient, as it handles
2915
+ * session creation and connector extraction automatically.
2916
+ *
2917
+ * @param client The MCPClient to extract tools from.
2918
+ * @param disallowedTools Optional list of tool names to exclude.
2919
+ * @returns A promise that resolves with a list of converted tools.
2920
+ */
2921
+ static async createTools(client, disallowedTools) {
2922
+ const adapter = new this(disallowedTools);
2923
+ if (!client.activeSessions || Object.keys(client.activeSessions).length === 0) {
2924
+ logger.info("No active sessions found, creating new ones...");
2925
+ await client.createAllSessions();
2312
2926
  }
2927
+ const sessions = client.getAllActiveSessions();
2928
+ const connectors = Object.values(sessions).map(
2929
+ (session) => session.connector
2930
+ );
2931
+ return adapter.createToolsFromConnectors(connectors);
2313
2932
  }
2314
- async prefetchServerTools() {
2315
- const servers = this.client.getServerNames();
2316
- for (const serverName of servers) {
2317
- try {
2318
- let session = null;
2319
- session = this.client.getSession(serverName);
2320
- logger.debug(
2321
- `Using existing session for server '${serverName}' to prefetch tools.`
2322
- );
2323
- if (!session) {
2324
- session = await this.client.createSession(serverName).catch((createSessionError) => {
2325
- logger.warn(
2326
- `Could not create session for '${serverName}' during prefetch: ${createSessionError}`
2327
- );
2328
- return null;
2329
- });
2330
- logger.debug(
2331
- `Temporarily created session for '${serverName}' to prefetch tools.`
2332
- );
2333
- }
2334
- if (session) {
2335
- const connector = session.connector;
2336
- let tools = [];
2337
- try {
2338
- tools = await this.adapter.createToolsFromConnectors([connector]);
2339
- } catch (toolFetchError) {
2340
- logger.error(
2341
- `Failed to create tools from connector for server '${serverName}': ${toolFetchError}`
2342
- );
2343
- continue;
2344
- }
2345
- const cachedTools = this.serverTools[serverName];
2346
- const toolsChanged = !cachedTools || !isEqual(cachedTools, tools);
2347
- if (toolsChanged) {
2348
- this.serverTools[serverName] = tools;
2349
- this.initializedServers[serverName] = true;
2350
- logger.debug(
2351
- `Prefetched ${tools.length} tools for server '${serverName}'.`
2352
- );
2353
- } else {
2354
- logger.debug(
2355
- `Tools for server '${serverName}' unchanged, using cached version.`
2356
- );
2357
- }
2358
- }
2359
- } catch (outerError) {
2360
- logger.error(
2361
- `Error prefetching tools for server '${serverName}': ${outerError}`
2362
- );
2933
+ /**
2934
+ * Dynamically load tools for a specific connector.
2935
+ *
2936
+ * @param connector The connector to load tools for.
2937
+ * @returns The list of tools that were loaded in the target framework's format.
2938
+ */
2939
+ async loadToolsForConnector(connector) {
2940
+ if (this.connectorToolMap.has(connector)) {
2941
+ const cached = this.connectorToolMap.get(connector);
2942
+ logger.debug(`Returning ${cached.length} existing tools for connector`);
2943
+ return cached;
2944
+ }
2945
+ const connectorTools = [];
2946
+ const success = await this.ensureConnectorInitialized(connector);
2947
+ if (!success) {
2948
+ return [];
2949
+ }
2950
+ for (const tool of connector.tools) {
2951
+ const converted = this.convertTool(tool, connector);
2952
+ if (converted) {
2953
+ connectorTools.push(converted);
2363
2954
  }
2364
2955
  }
2956
+ this.connectorToolMap.set(connector, connectorTools);
2957
+ logger.debug(
2958
+ `Loaded ${connectorTools.length} new tools for connector: ${connectorTools.map((t) => t?.name ?? String(t)).join(", ")}`
2959
+ );
2960
+ return connectorTools;
2365
2961
  }
2366
- get tools() {
2367
- if (logger.level === "debug") {
2368
- this.logState("Providing tools to agent");
2962
+ /**
2963
+ * Create tools from MCP tools in all provided connectors.
2964
+ *
2965
+ * @param connectors List of MCP connectors to create tools from.
2966
+ * @returns A promise that resolves with all converted tools.
2967
+ */
2968
+ async createToolsFromConnectors(connectors) {
2969
+ const tools = [];
2970
+ for (const connector of connectors) {
2971
+ const connectorTools = await this.loadToolsForConnector(connector);
2972
+ tools.push(...connectorTools);
2369
2973
  }
2370
- const managementTools = this.overrideManagementTools ?? [
2371
- new AddMCPServerFromConfigTool(this),
2372
- new ListMCPServersTool(this),
2373
- new ConnectMCPServerTool(this),
2374
- new AcquireActiveMCPServerTool(this),
2375
- new ReleaseMCPServerConnectionTool(this)
2376
- ];
2377
- if (this.activeServer && this.serverTools[this.activeServer]) {
2378
- const activeTools = this.serverTools[this.activeServer];
2379
- logger.debug(
2380
- `Adding ${activeTools.length} tools from active server '${this.activeServer}'`
2381
- );
2382
- return [...managementTools, ...activeTools];
2974
+ logger.debug(`Available tools: ${tools.length}`);
2975
+ return tools;
2976
+ }
2977
+ /**
2978
+ * Check if a connector is initialized and has tools.
2979
+ *
2980
+ * @param connector The connector to check.
2981
+ * @returns True if the connector is initialized and has tools, false otherwise.
2982
+ */
2983
+ checkConnectorInitialized(connector) {
2984
+ return Boolean(connector.tools && connector.tools.length);
2985
+ }
2986
+ /**
2987
+ * Ensure a connector is initialized.
2988
+ *
2989
+ * @param connector The connector to initialize.
2990
+ * @returns True if initialization succeeded, false otherwise.
2991
+ */
2992
+ async ensureConnectorInitialized(connector) {
2993
+ if (!this.checkConnectorInitialized(connector)) {
2994
+ logger.debug("Connector doesn't have tools, initializing it");
2995
+ try {
2996
+ await connector.initialize();
2997
+ return true;
2998
+ } catch (err) {
2999
+ logger.error(`Error initializing connector: ${err}`);
3000
+ return false;
3001
+ }
2383
3002
  }
2384
- return managementTools;
3003
+ return true;
2385
3004
  }
2386
3005
  };
2387
3006
 
2388
- // src/observability/index.ts
2389
- init_langfuse();
2390
- init_langfuse();
2391
-
2392
- // src/observability/manager.ts
2393
- init_logging();
2394
- var ObservabilityManager = class {
3007
+ // src/adapters/langchain_adapter.ts
3008
+ function schemaToZod(schema) {
3009
+ try {
3010
+ return JSONSchemaToZod.convert(schema);
3011
+ } catch (err) {
3012
+ logger.warn(`Failed to convert JSON schema to Zod: ${err}`);
3013
+ return import_zod2.z.any();
3014
+ }
3015
+ }
3016
+ __name(schemaToZod, "schemaToZod");
3017
+ var LangChainAdapter = class extends BaseAdapter {
2395
3018
  static {
2396
- __name(this, "ObservabilityManager");
3019
+ __name(this, "LangChainAdapter");
2397
3020
  }
2398
- customCallbacks;
2399
- availableHandlers = [];
2400
- handlerNames = [];
2401
- initialized = false;
2402
- verbose;
2403
- observe;
2404
- agentId;
2405
- metadata;
2406
- metadataProvider;
2407
- tagsProvider;
2408
- constructor(config = {}) {
2409
- this.customCallbacks = config.customCallbacks;
2410
- this.verbose = config.verbose ?? false;
2411
- this.observe = config.observe ?? true;
2412
- this.agentId = config.agentId;
2413
- this.metadata = config.metadata;
2414
- this.metadataProvider = config.metadataProvider;
2415
- this.tagsProvider = config.tagsProvider;
3021
+ constructor(disallowedTools = []) {
3022
+ super(disallowedTools);
2416
3023
  }
2417
3024
  /**
2418
- * Collect all available observability handlers from configured platforms.
3025
+ * Convert a single MCP tool specification into a LangChainJS structured tool.
2419
3026
  */
2420
- async collectAvailableHandlers() {
2421
- if (this.initialized) {
2422
- return;
3027
+ convertTool(mcpTool, connector) {
3028
+ if (this.disallowedTools.includes(mcpTool.name)) {
3029
+ return null;
2423
3030
  }
2424
- try {
2425
- const { langfuseHandler: langfuseHandler2, langfuseInitPromise: langfuseInitPromise2 } = await Promise.resolve().then(() => (init_langfuse(), langfuse_exports));
2426
- if (this.agentId || this.metadata || this.metadataProvider || this.tagsProvider) {
2427
- const { initializeLangfuse: initializeLangfuse2 } = await Promise.resolve().then(() => (init_langfuse(), langfuse_exports));
2428
- await initializeLangfuse2(
2429
- this.agentId,
2430
- this.metadata,
2431
- this.metadataProvider,
2432
- this.tagsProvider
2433
- );
3031
+ const argsSchema = mcpTool.inputSchema ? schemaToZod(mcpTool.inputSchema) : import_zod2.z.object({}).optional();
3032
+ const tool = new import_tools.DynamicStructuredTool({
3033
+ name: mcpTool.name ?? "NO NAME",
3034
+ description: mcpTool.description ?? "",
3035
+ // Blank is acceptable but discouraged.
3036
+ schema: argsSchema,
3037
+ func: /* @__PURE__ */ __name(async (input) => {
2434
3038
  logger.debug(
2435
- `ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`
3039
+ `MCP tool "${mcpTool.name}" received input: ${JSON.stringify(input)}`
2436
3040
  );
2437
- } else {
2438
- const initPromise = langfuseInitPromise2();
2439
- if (initPromise) {
2440
- await initPromise;
3041
+ try {
3042
+ const result = await connector.callTool(
3043
+ mcpTool.name,
3044
+ input
3045
+ );
3046
+ return JSON.stringify(result);
3047
+ } catch (err) {
3048
+ logger.error(`Error executing MCP tool: ${err.message}`);
3049
+ return `Error executing MCP tool: ${String(err)}`;
2441
3050
  }
2442
- }
2443
- const handler = langfuseHandler2();
2444
- if (handler) {
2445
- this.availableHandlers.push(handler);
2446
- this.handlerNames.push("Langfuse");
2447
- logger.debug("ObservabilityManager: Langfuse handler available");
2448
- }
2449
- } catch {
2450
- logger.debug("ObservabilityManager: Langfuse module not available");
2451
- }
2452
- this.initialized = true;
3051
+ }, "func")
3052
+ });
3053
+ return tool;
2453
3054
  }
2454
- /**
2455
- * Get the list of callbacks to use.
2456
- * @returns List of callbacks - either custom callbacks if provided, or all available observability handlers.
2457
- */
2458
- async getCallbacks() {
2459
- if (!this.observe) {
2460
- logger.debug(
2461
- "ObservabilityManager: Observability disabled via observe=false"
2462
- );
2463
- return [];
3055
+ };
3056
+
3057
+ // src/agents/mcp_agent.ts
3058
+ init_logging();
3059
+
3060
+ // src/managers/server_manager.ts
3061
+ init_logging();
3062
+
3063
+ // src/managers/tools/acquire_active_mcp_server.ts
3064
+ var import_zod3 = require("zod");
3065
+
3066
+ // src/managers/tools/base.ts
3067
+ var import_tools2 = require("@langchain/core/tools");
3068
+ var MCPServerTool = class extends import_tools2.StructuredTool {
3069
+ static {
3070
+ __name(this, "MCPServerTool");
3071
+ }
3072
+ name = "mcp_server_tool";
3073
+ description = "Base tool for MCP server operations.";
3074
+ schema;
3075
+ _manager;
3076
+ constructor(manager) {
3077
+ super();
3078
+ this._manager = manager;
3079
+ }
3080
+ async _call(_arg, _runManager, _parentConfig) {
3081
+ throw new Error("Method not implemented.");
3082
+ }
3083
+ get manager() {
3084
+ return this._manager;
3085
+ }
3086
+ };
3087
+
3088
+ // src/managers/tools/acquire_active_mcp_server.ts
3089
+ var PresentActiveServerSchema = import_zod3.z.object({});
3090
+ var AcquireActiveMCPServerTool = class extends MCPServerTool {
3091
+ static {
3092
+ __name(this, "AcquireActiveMCPServerTool");
3093
+ }
3094
+ name = "get_active_mcp_server";
3095
+ description = "Get the currently active MCP (Model Context Protocol) server";
3096
+ schema = PresentActiveServerSchema;
3097
+ constructor(manager) {
3098
+ super(manager);
3099
+ }
3100
+ async _call() {
3101
+ if (!this.manager.activeServer) {
3102
+ return `No MCP server is currently active. Use connect_to_mcp_server to connect to a server.`;
2464
3103
  }
2465
- if (this.customCallbacks) {
3104
+ return `Currently active MCP server: ${this.manager.activeServer}`;
3105
+ }
3106
+ };
3107
+
3108
+ // src/managers/tools/add_server_from_config.ts
3109
+ var import_tools3 = require("@langchain/core/tools");
3110
+ var import_zod4 = require("zod");
3111
+ init_logging();
3112
+ var AddMCPServerFromConfigTool = class extends import_tools3.StructuredTool {
3113
+ static {
3114
+ __name(this, "AddMCPServerFromConfigTool");
3115
+ }
3116
+ name = "add_mcp_server_from_config";
3117
+ description = "Adds a new MCP server to the client from a configuration object and connects to it, making its tools available.";
3118
+ schema = import_zod4.z.object({
3119
+ serverName: import_zod4.z.string().describe("The name for the new MCP server."),
3120
+ serverConfig: import_zod4.z.any().describe(
3121
+ 'The configuration object for the server. This should not include the top-level "mcpServers" key.'
3122
+ )
3123
+ });
3124
+ manager;
3125
+ constructor(manager) {
3126
+ super();
3127
+ this.manager = manager;
3128
+ }
3129
+ async _call({
3130
+ serverName,
3131
+ serverConfig
3132
+ }) {
3133
+ try {
3134
+ this.manager.client.addServer(serverName, serverConfig);
3135
+ let result = `Server '${serverName}' added to the client.`;
2466
3136
  logger.debug(
2467
- `ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`
3137
+ `Connecting to new server '${serverName}' and discovering tools.`
2468
3138
  );
2469
- return this.customCallbacks;
2470
- }
2471
- await this.collectAvailableHandlers();
2472
- if (this.availableHandlers.length > 0) {
2473
- logger.debug(
2474
- `ObservabilityManager: Using ${this.availableHandlers.length} handlers`
3139
+ const session = await this.manager.client.createSession(serverName);
3140
+ const connector = session.connector;
3141
+ const tools = await this.manager.adapter.createToolsFromConnectors([connector]);
3142
+ this.manager.serverTools[serverName] = tools;
3143
+ this.manager.initializedServers[serverName] = true;
3144
+ this.manager.activeServer = serverName;
3145
+ const numTools = tools.length;
3146
+ result += ` Session created and connected. '${serverName}' is now the active server with ${numTools} tools available.`;
3147
+ result += `
3148
+
3149
+ ${tools.map((t) => t.name).join("\n")}`;
3150
+ logger.info(result);
3151
+ return result;
3152
+ } catch (e) {
3153
+ logger.error(
3154
+ `Failed to add or connect to server '${serverName}': ${e.message}`
2475
3155
  );
2476
- } else {
2477
- logger.debug("ObservabilityManager: No callbacks configured");
3156
+ return `Failed to add or connect to server '${serverName}': ${e.message}`;
2478
3157
  }
2479
- return this.availableHandlers;
2480
3158
  }
2481
- /**
2482
- * Get the names of available handlers.
2483
- * @returns List of handler names (e.g., ["Langfuse", "Laminar"])
2484
- */
2485
- async getHandlerNames() {
2486
- if (!this.observe) {
2487
- return [];
3159
+ };
3160
+
3161
+ // src/managers/tools/connect_mcp_server.ts
3162
+ var import_zod5 = require("zod");
3163
+ init_logging();
3164
+ var ConnectMCPServerSchema = import_zod5.z.object({
3165
+ serverName: import_zod5.z.string().describe("The name of the MCP server.")
3166
+ });
3167
+ var ConnectMCPServerTool = class extends MCPServerTool {
3168
+ static {
3169
+ __name(this, "ConnectMCPServerTool");
3170
+ }
3171
+ name = "connect_to_mcp_server";
3172
+ description = "Connect to a specific MCP (Model Context Protocol) server to use its tools. Use this tool to connect to a specific server and use its tools.";
3173
+ schema = ConnectMCPServerSchema;
3174
+ constructor(manager) {
3175
+ super(manager);
3176
+ }
3177
+ async _call({ serverName }) {
3178
+ const serverNames = this.manager.client.getServerNames();
3179
+ if (!serverNames.includes(serverName)) {
3180
+ const available = serverNames.length > 0 ? serverNames.join(", ") : "none";
3181
+ return `Server '${serverName}' not found. Available servers: ${available}`;
2488
3182
  }
2489
- if (this.customCallbacks) {
2490
- return this.customCallbacks.map((cb) => cb.constructor.name);
3183
+ if (this.manager.activeServer === serverName) {
3184
+ return `Already connected to MCP server '${serverName}'`;
2491
3185
  }
2492
- await this.collectAvailableHandlers();
2493
- return this.handlerNames;
2494
- }
2495
- /**
2496
- * Check if any callbacks are available.
2497
- * @returns True if callbacks are available, False otherwise.
2498
- */
2499
- async hasCallbacks() {
2500
- if (!this.observe) {
2501
- return false;
3186
+ try {
3187
+ let session = this.manager.client.getSession(serverName);
3188
+ logger.debug(`Using existing session for server '${serverName}'`);
3189
+ if (!session) {
3190
+ logger.debug(`Creating new session for server '${serverName}'`);
3191
+ session = await this.manager.client.createSession(serverName);
3192
+ }
3193
+ this.manager.activeServer = serverName;
3194
+ if (this.manager.serverTools[serverName]) {
3195
+ const connector = session.connector;
3196
+ const tools = await this.manager.adapter.createToolsFromConnectors([connector]);
3197
+ this.manager.serverTools[serverName] = tools;
3198
+ this.manager.initializedServers[serverName] = true;
3199
+ }
3200
+ const serverTools = this.manager.serverTools[serverName] || [];
3201
+ const numTools = serverTools.length;
3202
+ return `Connected to MCP server '${serverName}'. ${numTools} tools are now available.`;
3203
+ } catch (error) {
3204
+ logger.error(
3205
+ `Error connecting to server '${serverName}': ${String(error)}`
3206
+ );
3207
+ return `Failed to connect to server '${serverName}': ${String(error)}`;
2502
3208
  }
2503
- const callbacks = await this.getCallbacks();
2504
- return callbacks.length > 0;
2505
- }
2506
- /**
2507
- * Get the current observability status including metadata and tags.
2508
- * @returns Object containing enabled status, callback count, handler names, metadata, and tags.
2509
- */
2510
- async getStatus() {
2511
- const callbacks = await this.getCallbacks();
2512
- const handlerNames = await this.getHandlerNames();
2513
- const currentMetadata = this.metadataProvider ? this.metadataProvider() : this.metadata || {};
2514
- const currentTags = this.tagsProvider ? this.tagsProvider() : [];
2515
- return {
2516
- enabled: this.observe && callbacks.length > 0,
2517
- callbackCount: callbacks.length,
2518
- handlerNames,
2519
- metadata: currentMetadata,
2520
- tags: currentTags
2521
- };
2522
3209
  }
2523
- /**
2524
- * Add a callback to the custom callbacks list.
2525
- * @param callback The callback to add.
2526
- */
2527
- addCallback(callback) {
2528
- if (!this.customCallbacks) {
2529
- this.customCallbacks = [];
2530
- }
2531
- this.customCallbacks.push(callback);
2532
- logger.debug(
2533
- `ObservabilityManager: Added custom callback: ${callback.constructor.name}`
2534
- );
3210
+ };
3211
+
3212
+ // src/managers/tools/list_mcp_servers.ts
3213
+ var import_zod6 = require("zod");
3214
+ init_logging();
3215
+ var EnumerateServersSchema = import_zod6.z.object({});
3216
+ var ListMCPServersTool = class extends MCPServerTool {
3217
+ static {
3218
+ __name(this, "ListMCPServersTool");
2535
3219
  }
2536
- /**
2537
- * Clear all custom callbacks.
2538
- */
2539
- clearCallbacks() {
2540
- this.customCallbacks = [];
2541
- logger.debug("ObservabilityManager: Cleared all custom callbacks");
3220
+ name = "list_mcp_servers";
3221
+ description = `Lists all available MCP (Model Context Protocol) servers that can be connected to, along with the tools available on each server. Use this tool to discover servers and see what functionalities they offer.`;
3222
+ schema = EnumerateServersSchema;
3223
+ constructor(manager) {
3224
+ super(manager);
2542
3225
  }
2543
- /**
2544
- * Flush all pending traces to observability platforms.
2545
- * Important for serverless environments and short-lived processes.
2546
- */
2547
- async flush() {
2548
- const callbacks = await this.getCallbacks();
2549
- for (const callback of callbacks) {
2550
- if ("flushAsync" in callback && typeof callback.flushAsync === "function") {
2551
- await callback.flushAsync();
2552
- }
3226
+ async _call() {
3227
+ const serverNames = this.manager.client.getServerNames();
3228
+ if (serverNames.length === 0) {
3229
+ return `No MCP servers are currently defined.`;
2553
3230
  }
2554
- logger.debug("ObservabilityManager: All traces flushed");
2555
- }
2556
- /**
2557
- * Shutdown all handlers gracefully (for serverless environments).
2558
- */
2559
- async shutdown() {
2560
- await this.flush();
2561
- const callbacks = await this.getCallbacks();
2562
- for (const callback of callbacks) {
2563
- if ("shutdownAsync" in callback && typeof callback.shutdownAsync === "function") {
2564
- await callback.shutdownAsync();
2565
- } else if ("shutdown" in callback && typeof callback.shutdown === "function") {
2566
- await callback.shutdown();
3231
+ const outputLines = ["Available MCP servers:"];
3232
+ for (const serverName of serverNames) {
3233
+ const isActiveServer = serverName === this.manager.activeServer;
3234
+ const activeFlag = isActiveServer ? " (ACTIVE)" : "";
3235
+ outputLines.push(`- ${serverName}${activeFlag}`);
3236
+ try {
3237
+ const serverTools = this.manager.serverTools?.[serverName] ?? [];
3238
+ const numberOfTools = Array.isArray(serverTools) ? serverTools.length : 0;
3239
+ outputLines.push(`${numberOfTools} tools available for this server
3240
+ `);
3241
+ } catch (error) {
3242
+ logger.error(
3243
+ `Unexpected error listing tools for server '${serverName}': ${String(error)}`
3244
+ );
2567
3245
  }
2568
3246
  }
2569
- logger.debug("ObservabilityManager: All handlers shutdown");
2570
- }
2571
- /**
2572
- * String representation of the ObservabilityManager.
2573
- */
2574
- toString() {
2575
- const names = this.handlerNames;
2576
- if (names.length > 0) {
2577
- return `ObservabilityManager(handlers=${names.join(", ")})`;
2578
- }
2579
- return "ObservabilityManager(no handlers)";
3247
+ return outputLines.join("\n");
2580
3248
  }
2581
3249
  };
2582
3250
 
2583
- // src/telemetry/telemetry.ts
2584
- var fs2 = __toESM(require("fs"), 1);
2585
- var os = __toESM(require("os"), 1);
2586
- var path2 = __toESM(require("path"), 1);
2587
- var import_posthog_node = require("posthog-node");
2588
-
2589
- // src/server/utils/runtime.ts
2590
- var isDeno = typeof globalThis.Deno !== "undefined";
2591
- function generateUUID() {
2592
- return globalThis.crypto.randomUUID();
2593
- }
2594
- __name(generateUUID, "generateUUID");
2595
-
2596
- // src/telemetry/telemetry.ts
2597
- init_logging();
2598
-
2599
- // src/telemetry/events.ts
2600
- var BaseTelemetryEvent = class {
3251
+ // src/managers/tools/release_mcp_server_connection.ts
3252
+ var import_zod7 = require("zod");
3253
+ var ReleaseConnectionSchema = import_zod7.z.object({});
3254
+ var ReleaseMCPServerConnectionTool = class extends MCPServerTool {
2601
3255
  static {
2602
- __name(this, "BaseTelemetryEvent");
3256
+ __name(this, "ReleaseMCPServerConnectionTool");
3257
+ }
3258
+ name = "disconnect_from_mcp_server";
3259
+ description = "Disconnect from the currently active MCP (Model Context Protocol) server";
3260
+ schema = ReleaseConnectionSchema;
3261
+ constructor(manager) {
3262
+ super(manager);
3263
+ }
3264
+ async _call() {
3265
+ if (!this.manager.activeServer) {
3266
+ return `No MCP server is currently active, so there's nothing to disconnect from.`;
3267
+ }
3268
+ const serverName = this.manager.activeServer;
3269
+ this.manager.activeServer = null;
3270
+ return `Successfully disconnected from MCP server '${serverName}'.`;
2603
3271
  }
2604
3272
  };
2605
- var MCPAgentExecutionEvent = class extends BaseTelemetryEvent {
2606
- constructor(data) {
2607
- super();
2608
- this.data = data;
3273
+
3274
+ // src/managers/server_manager.ts
3275
+ function isEqual(a, b) {
3276
+ if (a === b) return true;
3277
+ if (a == null || b == null) return false;
3278
+ if (typeof a !== typeof b) return false;
3279
+ if (a instanceof Date && b instanceof Date) {
3280
+ return a.getTime() === b.getTime();
3281
+ }
3282
+ if (Array.isArray(a) && Array.isArray(b)) {
3283
+ if (a.length !== b.length) return false;
3284
+ return a.every((item, index) => isEqual(item, b[index]));
3285
+ }
3286
+ if (typeof a === "object" && typeof b === "object") {
3287
+ const keysA = Object.keys(a);
3288
+ const keysB = Object.keys(b);
3289
+ if (keysA.length !== keysB.length) return false;
3290
+ return keysA.every((key) => {
3291
+ return Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]);
3292
+ });
2609
3293
  }
3294
+ return false;
3295
+ }
3296
+ __name(isEqual, "isEqual");
3297
+ var ServerManager = class {
2610
3298
  static {
2611
- __name(this, "MCPAgentExecutionEvent");
3299
+ __name(this, "ServerManager");
2612
3300
  }
2613
- get name() {
2614
- return "mcp_agent_execution";
3301
+ initializedServers = {};
3302
+ serverTools = {};
3303
+ client;
3304
+ adapter;
3305
+ activeServer = null;
3306
+ overrideManagementTools;
3307
+ constructor(client, adapter, managementTools) {
3308
+ this.client = client;
3309
+ this.adapter = adapter;
3310
+ this.overrideManagementTools = managementTools;
2615
3311
  }
2616
- get properties() {
2617
- return {
2618
- // Core execution info
2619
- execution_method: this.data.executionMethod,
2620
- query: this.data.query,
2621
- query_length: this.data.query.length,
2622
- success: this.data.success,
2623
- // Agent configuration
2624
- model_provider: this.data.modelProvider,
2625
- model_name: this.data.modelName,
2626
- server_count: this.data.serverCount,
2627
- server_identifiers: this.data.serverIdentifiers,
2628
- total_tools_available: this.data.totalToolsAvailable,
2629
- tools_available_names: this.data.toolsAvailableNames,
2630
- max_steps_configured: this.data.maxStepsConfigured,
2631
- memory_enabled: this.data.memoryEnabled,
2632
- use_server_manager: this.data.useServerManager,
2633
- // Execution parameters (always include, even if null)
2634
- max_steps_used: this.data.maxStepsUsed,
2635
- manage_connector: this.data.manageConnector,
2636
- external_history_used: this.data.externalHistoryUsed,
2637
- // Execution results (always include, even if null)
2638
- steps_taken: this.data.stepsTaken ?? null,
2639
- tools_used_count: this.data.toolsUsedCount ?? null,
2640
- tools_used_names: this.data.toolsUsedNames ?? null,
2641
- response: this.data.response ?? null,
2642
- response_length: this.data.response ? this.data.response.length : null,
2643
- execution_time_ms: this.data.executionTimeMs ?? null,
2644
- error_type: this.data.errorType ?? null,
2645
- conversation_history_length: this.data.conversationHistoryLength ?? null
2646
- };
3312
+ setManagementTools(tools) {
3313
+ this.overrideManagementTools = tools;
3314
+ logger.info(
3315
+ `Overriding default management tools with a new set of ${tools.length} tools.`
3316
+ );
2647
3317
  }
2648
- };
2649
-
2650
- // src/telemetry/utils.ts
2651
- var fs = __toESM(require("fs"), 1);
2652
- var path = __toESM(require("path"), 1);
2653
- function getPackageVersion() {
2654
- try {
2655
- if (typeof __dirname === "undefined" || typeof fs === "undefined") {
2656
- return "unknown";
3318
+ logState(context) {
3319
+ const allServerNames = this.client.getServerNames();
3320
+ const activeSessionNames = Object.keys(this.client.getAllActiveSessions());
3321
+ if (allServerNames.length === 0) {
3322
+ logger.info("Server Manager State: No servers configured.");
3323
+ return;
2657
3324
  }
2658
- const packagePath = path.join(__dirname, "../../package.json");
2659
- const packageJson = JSON.parse(fs.readFileSync(packagePath, "utf-8"));
2660
- return packageJson.version || "unknown";
2661
- } catch {
2662
- return "unknown";
3325
+ const tableData = allServerNames.map((name) => ({
3326
+ "Server Name": name,
3327
+ Connected: activeSessionNames.includes(name) ? "\u2705" : "\u274C",
3328
+ Initialized: this.initializedServers[name] ? "\u2705" : "\u274C",
3329
+ "Tool Count": this.serverTools[name]?.length ?? 0,
3330
+ Active: this.activeServer === name ? "\u2705" : "\u274C"
3331
+ }));
3332
+ logger.info(`Server Manager State: [${context}]`);
3333
+ console.table(tableData);
2663
3334
  }
2664
- }
2665
- __name(getPackageVersion, "getPackageVersion");
2666
- function getModelProvider(llm) {
2667
- return llm._llm_type || llm.constructor.name.toLowerCase();
2668
- }
2669
- __name(getModelProvider, "getModelProvider");
2670
- function getModelName(llm) {
2671
- if ("_identifyingParams" in llm) {
2672
- const identifyingParams = llm._identifyingParams;
2673
- if (typeof identifyingParams === "object" && identifyingParams !== null) {
2674
- for (const key of [
2675
- "model",
2676
- "modelName",
2677
- "model_name",
2678
- "modelId",
2679
- "model_id",
2680
- "deploymentName",
2681
- "deployment_name"
2682
- ]) {
2683
- if (key in identifyingParams) {
2684
- return String(identifyingParams[key]);
3335
+ initialize() {
3336
+ const serverNames = this.client.getServerNames?.();
3337
+ if (serverNames.length === 0) {
3338
+ logger.warn("No MCP servers defined in client configuration");
3339
+ }
3340
+ }
3341
+ async prefetchServerTools() {
3342
+ const servers = this.client.getServerNames();
3343
+ for (const serverName of servers) {
3344
+ try {
3345
+ let session = null;
3346
+ session = this.client.getSession(serverName);
3347
+ logger.debug(
3348
+ `Using existing session for server '${serverName}' to prefetch tools.`
3349
+ );
3350
+ if (!session) {
3351
+ session = await this.client.createSession(serverName).catch((createSessionError) => {
3352
+ logger.warn(
3353
+ `Could not create session for '${serverName}' during prefetch: ${createSessionError}`
3354
+ );
3355
+ return null;
3356
+ });
3357
+ logger.debug(
3358
+ `Temporarily created session for '${serverName}' to prefetch tools.`
3359
+ );
3360
+ }
3361
+ if (session) {
3362
+ const connector = session.connector;
3363
+ let tools = [];
3364
+ try {
3365
+ tools = await this.adapter.createToolsFromConnectors([connector]);
3366
+ } catch (toolFetchError) {
3367
+ logger.error(
3368
+ `Failed to create tools from connector for server '${serverName}': ${toolFetchError}`
3369
+ );
3370
+ continue;
3371
+ }
3372
+ const cachedTools = this.serverTools[serverName];
3373
+ const toolsChanged = !cachedTools || !isEqual(cachedTools, tools);
3374
+ if (toolsChanged) {
3375
+ this.serverTools[serverName] = tools;
3376
+ this.initializedServers[serverName] = true;
3377
+ logger.debug(
3378
+ `Prefetched ${tools.length} tools for server '${serverName}'.`
3379
+ );
3380
+ } else {
3381
+ logger.debug(
3382
+ `Tools for server '${serverName}' unchanged, using cached version.`
3383
+ );
3384
+ }
2685
3385
  }
3386
+ } catch (outerError) {
3387
+ logger.error(
3388
+ `Error prefetching tools for server '${serverName}': ${outerError}`
3389
+ );
2686
3390
  }
2687
3391
  }
2688
3392
  }
2689
- return llm.model || llm.modelName || llm.constructor.name;
2690
- }
2691
- __name(getModelName, "getModelName");
2692
- function extractModelInfo(llm) {
2693
- return [getModelProvider(llm), getModelName(llm)];
2694
- }
2695
- __name(extractModelInfo, "extractModelInfo");
2696
-
2697
- // src/telemetry/telemetry.ts
2698
- function isNodeJSEnvironment2() {
2699
- try {
2700
- if (typeof navigator !== "undefined" && navigator.userAgent?.includes("Cloudflare-Workers")) {
2701
- return false;
3393
+ get tools() {
3394
+ if (logger.level === "debug") {
3395
+ this.logState("Providing tools to agent");
2702
3396
  }
2703
- if (typeof globalThis.EdgeRuntime !== "undefined" || typeof globalThis.Deno !== "undefined") {
2704
- return false;
3397
+ const managementTools = this.overrideManagementTools ?? [
3398
+ new AddMCPServerFromConfigTool(this),
3399
+ new ListMCPServersTool(this),
3400
+ new ConnectMCPServerTool(this),
3401
+ new AcquireActiveMCPServerTool(this),
3402
+ new ReleaseMCPServerConnectionTool(this)
3403
+ ];
3404
+ if (this.activeServer && this.serverTools[this.activeServer]) {
3405
+ const activeTools = this.serverTools[this.activeServer];
3406
+ logger.debug(
3407
+ `Adding ${activeTools.length} tools from active server '${this.activeServer}'`
3408
+ );
3409
+ return [...managementTools, ...activeTools];
2705
3410
  }
2706
- const hasNodeGlobals = typeof process !== "undefined" && typeof process.platform !== "undefined" && typeof __dirname !== "undefined";
2707
- const hasNodeModules = typeof fs2 !== "undefined" && typeof os !== "undefined" && typeof fs2.existsSync === "function";
2708
- return hasNodeGlobals && hasNodeModules;
2709
- } catch {
2710
- return false;
3411
+ return managementTools;
2711
3412
  }
2712
- }
2713
- __name(isNodeJSEnvironment2, "isNodeJSEnvironment");
2714
- var ScarfEventLogger = class {
3413
+ };
3414
+
3415
+ // src/observability/index.ts
3416
+ init_langfuse();
3417
+ init_langfuse();
3418
+
3419
+ // src/observability/manager.ts
3420
+ init_logging();
3421
+ var ObservabilityManager = class {
2715
3422
  static {
2716
- __name(this, "ScarfEventLogger");
3423
+ __name(this, "ObservabilityManager");
2717
3424
  }
2718
- endpoint;
2719
- timeout;
2720
- constructor(endpoint, timeout = 3e3) {
2721
- this.endpoint = endpoint;
2722
- this.timeout = timeout;
3425
+ customCallbacks;
3426
+ availableHandlers = [];
3427
+ handlerNames = [];
3428
+ initialized = false;
3429
+ verbose;
3430
+ observe;
3431
+ agentId;
3432
+ metadata;
3433
+ metadataProvider;
3434
+ tagsProvider;
3435
+ constructor(config = {}) {
3436
+ this.customCallbacks = config.customCallbacks;
3437
+ this.verbose = config.verbose ?? false;
3438
+ this.observe = config.observe ?? true;
3439
+ this.agentId = config.agentId;
3440
+ this.metadata = config.metadata;
3441
+ this.metadataProvider = config.metadataProvider;
3442
+ this.tagsProvider = config.tagsProvider;
2723
3443
  }
2724
- async logEvent(properties) {
3444
+ /**
3445
+ * Collect all available observability handlers from configured platforms.
3446
+ */
3447
+ async collectAvailableHandlers() {
3448
+ if (this.initialized) {
3449
+ return;
3450
+ }
2725
3451
  try {
2726
- const controller = new AbortController();
2727
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
2728
- const response = await fetch(this.endpoint, {
2729
- method: "POST",
2730
- headers: {
2731
- "Content-Type": "application/json"
2732
- },
2733
- body: JSON.stringify(properties),
2734
- signal: controller.signal
2735
- });
2736
- clearTimeout(timeoutId);
2737
- if (!response.ok) {
2738
- throw new Error(`HTTP error! status: ${response.status}`);
3452
+ const { langfuseHandler: langfuseHandler2, langfuseInitPromise: langfuseInitPromise2 } = await Promise.resolve().then(() => (init_langfuse(), langfuse_exports));
3453
+ if (this.agentId || this.metadata || this.metadataProvider || this.tagsProvider) {
3454
+ const { initializeLangfuse: initializeLangfuse2 } = await Promise.resolve().then(() => (init_langfuse(), langfuse_exports));
3455
+ await initializeLangfuse2(
3456
+ this.agentId,
3457
+ this.metadata,
3458
+ this.metadataProvider,
3459
+ this.tagsProvider
3460
+ );
3461
+ logger.debug(
3462
+ `ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`
3463
+ );
3464
+ } else {
3465
+ const initPromise = langfuseInitPromise2();
3466
+ if (initPromise) {
3467
+ await initPromise;
3468
+ }
2739
3469
  }
2740
- } catch (error) {
2741
- logger.debug(`Failed to send Scarf event: ${error}`);
3470
+ const handler = langfuseHandler2();
3471
+ if (handler) {
3472
+ this.availableHandlers.push(handler);
3473
+ this.handlerNames.push("Langfuse");
3474
+ logger.debug("ObservabilityManager: Langfuse handler available");
3475
+ }
3476
+ } catch {
3477
+ logger.debug("ObservabilityManager: Langfuse module not available");
2742
3478
  }
3479
+ this.initialized = true;
2743
3480
  }
2744
- };
2745
- function getCacheHome() {
2746
- if (!isNodeJSEnvironment2()) {
2747
- return "/tmp/mcp_use_cache";
2748
- }
2749
- const envVar = process.env.XDG_CACHE_HOME;
2750
- if (envVar && path2.isAbsolute(envVar)) {
2751
- return envVar;
2752
- }
2753
- const platform = process.platform;
2754
- const homeDir = os.homedir();
2755
- if (platform === "win32") {
2756
- const appdata = process.env.LOCALAPPDATA || process.env.APPDATA;
2757
- if (appdata) {
2758
- return appdata;
2759
- }
2760
- return path2.join(homeDir, "AppData", "Local");
2761
- } else if (platform === "darwin") {
2762
- return path2.join(homeDir, "Library", "Caches");
2763
- } else {
2764
- return path2.join(homeDir, ".cache");
2765
- }
2766
- }
2767
- __name(getCacheHome, "getCacheHome");
2768
- var Telemetry = class _Telemetry {
2769
- static {
2770
- __name(this, "Telemetry");
2771
- }
2772
- static instance = null;
2773
- USER_ID_PATH = path2.join(
2774
- getCacheHome(),
2775
- "mcp_use_3",
2776
- "telemetry_user_id"
2777
- );
2778
- VERSION_DOWNLOAD_PATH = path2.join(
2779
- getCacheHome(),
2780
- "mcp_use",
2781
- "download_version"
2782
- );
2783
- PROJECT_API_KEY = "phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";
2784
- HOST = "https://eu.i.posthog.com";
2785
- SCARF_GATEWAY_URL = "https://mcpuse.gateway.scarf.sh/events-ts";
2786
- UNKNOWN_USER_ID = "UNKNOWN_USER_ID";
2787
- _currUserId = null;
2788
- _posthogClient = null;
2789
- _scarfClient = null;
2790
- _source = "typescript";
2791
- constructor() {
2792
- const isNodeJS = isNodeJSEnvironment2();
2793
- const telemetryDisabled = typeof process !== "undefined" && process.env?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase() === "false" || false;
2794
- this._source = typeof process !== "undefined" && process.env?.MCP_USE_TELEMETRY_SOURCE || "typescript";
2795
- if (telemetryDisabled) {
2796
- this._posthogClient = null;
2797
- this._scarfClient = null;
2798
- logger.debug("Telemetry disabled via environment variable");
2799
- } else if (!isNodeJS) {
2800
- this._posthogClient = null;
2801
- this._scarfClient = null;
3481
+ /**
3482
+ * Get the list of callbacks to use.
3483
+ * @returns List of callbacks - either custom callbacks if provided, or all available observability handlers.
3484
+ */
3485
+ async getCallbacks() {
3486
+ if (!this.observe) {
2802
3487
  logger.debug(
2803
- "Telemetry disabled - non-Node.js environment detected (e.g., Cloudflare Workers)"
3488
+ "ObservabilityManager: Observability disabled via observe=false"
2804
3489
  );
2805
- } else {
2806
- logger.info(
2807
- "Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."
3490
+ return [];
3491
+ }
3492
+ if (this.customCallbacks) {
3493
+ logger.debug(
3494
+ `ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`
2808
3495
  );
2809
- try {
2810
- this._posthogClient = new import_posthog_node.PostHog(this.PROJECT_API_KEY, {
2811
- host: this.HOST,
2812
- disableGeoip: false
2813
- });
2814
- } catch (e) {
2815
- logger.warn(`Failed to initialize PostHog telemetry: ${e}`);
2816
- this._posthogClient = null;
2817
- }
2818
- try {
2819
- this._scarfClient = new ScarfEventLogger(this.SCARF_GATEWAY_URL, 3e3);
2820
- } catch (e) {
2821
- logger.warn(`Failed to initialize Scarf telemetry: ${e}`);
2822
- this._scarfClient = null;
2823
- }
3496
+ return this.customCallbacks;
2824
3497
  }
2825
- }
2826
- static getInstance() {
2827
- if (!_Telemetry.instance) {
2828
- _Telemetry.instance = new _Telemetry();
3498
+ await this.collectAvailableHandlers();
3499
+ if (this.availableHandlers.length > 0) {
3500
+ logger.debug(
3501
+ `ObservabilityManager: Using ${this.availableHandlers.length} handlers`
3502
+ );
3503
+ } else {
3504
+ logger.debug("ObservabilityManager: No callbacks configured");
2829
3505
  }
2830
- return _Telemetry.instance;
3506
+ return this.availableHandlers;
2831
3507
  }
2832
3508
  /**
2833
- * Set the source identifier for telemetry events.
2834
- * This allows tracking usage from different applications.
2835
- * @param source - The source identifier (e.g., "my-app", "cli", "vs-code-extension")
3509
+ * Get the names of available handlers.
3510
+ * @returns List of handler names (e.g., ["Langfuse", "Laminar"])
2836
3511
  */
2837
- setSource(source) {
2838
- this._source = source;
2839
- logger.debug(`Telemetry source set to: ${source}`);
3512
+ async getHandlerNames() {
3513
+ if (!this.observe) {
3514
+ return [];
3515
+ }
3516
+ if (this.customCallbacks) {
3517
+ return this.customCallbacks.map((cb) => cb.constructor.name);
3518
+ }
3519
+ await this.collectAvailableHandlers();
3520
+ return this.handlerNames;
2840
3521
  }
2841
3522
  /**
2842
- * Get the current source identifier.
3523
+ * Check if any callbacks are available.
3524
+ * @returns True if callbacks are available, False otherwise.
2843
3525
  */
2844
- getSource() {
2845
- return this._source;
2846
- }
2847
- get userId() {
2848
- if (this._currUserId) {
2849
- return this._currUserId;
2850
- }
2851
- if (!isNodeJSEnvironment2()) {
2852
- this._currUserId = this.UNKNOWN_USER_ID;
2853
- return this._currUserId;
2854
- }
2855
- try {
2856
- const isFirstTime = !fs2.existsSync(this.USER_ID_PATH);
2857
- if (isFirstTime) {
2858
- logger.debug(`Creating user ID path: ${this.USER_ID_PATH}`);
2859
- fs2.mkdirSync(path2.dirname(this.USER_ID_PATH), { recursive: true });
2860
- const newUserId = generateUUID();
2861
- fs2.writeFileSync(this.USER_ID_PATH, newUserId);
2862
- this._currUserId = newUserId;
2863
- logger.debug(`User ID path created: ${this.USER_ID_PATH}`);
2864
- } else {
2865
- this._currUserId = fs2.readFileSync(this.USER_ID_PATH, "utf-8").trim();
2866
- }
2867
- this.trackPackageDownload({
2868
- triggered_by: "user_id_property"
2869
- }).catch((e) => logger.debug(`Failed to track package download: ${e}`));
2870
- } catch (e) {
2871
- logger.debug(`Failed to get/create user ID: ${e}`);
2872
- this._currUserId = this.UNKNOWN_USER_ID;
3526
+ async hasCallbacks() {
3527
+ if (!this.observe) {
3528
+ return false;
2873
3529
  }
2874
- return this._currUserId;
3530
+ const callbacks = await this.getCallbacks();
3531
+ return callbacks.length > 0;
2875
3532
  }
2876
- async capture(event) {
2877
- if (!this._posthogClient && !this._scarfClient) {
2878
- return;
2879
- }
2880
- if (this._posthogClient) {
2881
- try {
2882
- const properties = { ...event.properties };
2883
- properties.mcp_use_version = getPackageVersion();
2884
- properties.language = "typescript";
2885
- properties.source = this._source;
2886
- this._posthogClient.capture({
2887
- distinctId: this.userId,
2888
- event: event.name,
2889
- properties
2890
- });
2891
- } catch (e) {
2892
- logger.debug(`Failed to track PostHog event ${event.name}: ${e}`);
2893
- }
2894
- }
2895
- if (this._scarfClient) {
2896
- try {
2897
- const properties = {};
2898
- properties.mcp_use_version = getPackageVersion();
2899
- properties.user_id = this.userId;
2900
- properties.event = event.name;
2901
- properties.language = "typescript";
2902
- properties.source = this._source;
2903
- await this._scarfClient.logEvent(properties);
2904
- } catch (e) {
2905
- logger.debug(`Failed to track Scarf event ${event.name}: ${e}`);
2906
- }
2907
- }
3533
+ /**
3534
+ * Get the current observability status including metadata and tags.
3535
+ * @returns Object containing enabled status, callback count, handler names, metadata, and tags.
3536
+ */
3537
+ async getStatus() {
3538
+ const callbacks = await this.getCallbacks();
3539
+ const handlerNames = await this.getHandlerNames();
3540
+ const currentMetadata = this.metadataProvider ? this.metadataProvider() : this.metadata || {};
3541
+ const currentTags = this.tagsProvider ? this.tagsProvider() : [];
3542
+ return {
3543
+ enabled: this.observe && callbacks.length > 0,
3544
+ callbackCount: callbacks.length,
3545
+ handlerNames,
3546
+ metadata: currentMetadata,
3547
+ tags: currentTags
3548
+ };
2908
3549
  }
2909
- async trackPackageDownload(properties) {
2910
- if (!this._scarfClient) {
2911
- return;
2912
- }
2913
- if (!isNodeJSEnvironment2()) {
2914
- return;
2915
- }
2916
- try {
2917
- const currentVersion = getPackageVersion();
2918
- let shouldTrack = false;
2919
- let firstDownload = false;
2920
- if (!fs2.existsSync(this.VERSION_DOWNLOAD_PATH)) {
2921
- shouldTrack = true;
2922
- firstDownload = true;
2923
- fs2.mkdirSync(path2.dirname(this.VERSION_DOWNLOAD_PATH), {
2924
- recursive: true
2925
- });
2926
- fs2.writeFileSync(this.VERSION_DOWNLOAD_PATH, currentVersion);
2927
- } else {
2928
- const savedVersion = fs2.readFileSync(this.VERSION_DOWNLOAD_PATH, "utf-8").trim();
2929
- if (currentVersion > savedVersion) {
2930
- shouldTrack = true;
2931
- firstDownload = false;
2932
- fs2.writeFileSync(this.VERSION_DOWNLOAD_PATH, currentVersion);
2933
- }
2934
- }
2935
- if (shouldTrack) {
2936
- logger.debug(
2937
- `Tracking package download event with properties: ${JSON.stringify(properties)}`
2938
- );
2939
- const eventProperties = { ...properties || {} };
2940
- eventProperties.mcp_use_version = currentVersion;
2941
- eventProperties.user_id = this.userId;
2942
- eventProperties.event = "package_download";
2943
- eventProperties.first_download = firstDownload;
2944
- eventProperties.language = "typescript";
2945
- eventProperties.source = this._source;
2946
- await this._scarfClient.logEvent(eventProperties);
2947
- }
2948
- } catch (e) {
2949
- logger.debug(`Failed to track Scarf package_download event: ${e}`);
3550
+ /**
3551
+ * Add a callback to the custom callbacks list.
3552
+ * @param callback The callback to add.
3553
+ */
3554
+ addCallback(callback) {
3555
+ if (!this.customCallbacks) {
3556
+ this.customCallbacks = [];
2950
3557
  }
3558
+ this.customCallbacks.push(callback);
3559
+ logger.debug(
3560
+ `ObservabilityManager: Added custom callback: ${callback.constructor.name}`
3561
+ );
2951
3562
  }
2952
- async trackAgentExecution(data) {
2953
- const event = new MCPAgentExecutionEvent(data);
2954
- await this.capture(event);
3563
+ /**
3564
+ * Clear all custom callbacks.
3565
+ */
3566
+ clearCallbacks() {
3567
+ this.customCallbacks = [];
3568
+ logger.debug("ObservabilityManager: Cleared all custom callbacks");
2955
3569
  }
2956
- flush() {
2957
- if (this._posthogClient) {
2958
- try {
2959
- this._posthogClient.flush();
2960
- logger.debug("PostHog client telemetry queue flushed");
2961
- } catch (e) {
2962
- logger.debug(`Failed to flush PostHog client: ${e}`);
3570
+ /**
3571
+ * Flush all pending traces to observability platforms.
3572
+ * Important for serverless environments and short-lived processes.
3573
+ */
3574
+ async flush() {
3575
+ const callbacks = await this.getCallbacks();
3576
+ for (const callback of callbacks) {
3577
+ if ("flushAsync" in callback && typeof callback.flushAsync === "function") {
3578
+ await callback.flushAsync();
2963
3579
  }
2964
3580
  }
2965
- if (this._scarfClient) {
2966
- logger.debug("Scarf telemetry events sent immediately (no flush needed)");
2967
- }
3581
+ logger.debug("ObservabilityManager: All traces flushed");
2968
3582
  }
2969
- shutdown() {
2970
- if (this._posthogClient) {
2971
- try {
2972
- this._posthogClient.shutdown();
2973
- logger.debug("PostHog client shutdown successfully");
2974
- } catch (e) {
2975
- logger.debug(`Error shutting down PostHog client: ${e}`);
3583
+ /**
3584
+ * Shutdown all handlers gracefully (for serverless environments).
3585
+ */
3586
+ async shutdown() {
3587
+ await this.flush();
3588
+ const callbacks = await this.getCallbacks();
3589
+ for (const callback of callbacks) {
3590
+ if ("shutdownAsync" in callback && typeof callback.shutdownAsync === "function") {
3591
+ await callback.shutdownAsync();
3592
+ } else if ("shutdown" in callback && typeof callback.shutdown === "function") {
3593
+ await callback.shutdown();
2976
3594
  }
2977
3595
  }
2978
- if (this._scarfClient) {
2979
- logger.debug("Scarf telemetry client shutdown (no action needed)");
3596
+ logger.debug("ObservabilityManager: All handlers shutdown");
3597
+ }
3598
+ /**
3599
+ * String representation of the ObservabilityManager.
3600
+ */
3601
+ toString() {
3602
+ const names = this.handlerNames;
3603
+ if (names.length > 0) {
3604
+ return `ObservabilityManager(handlers=${names.join(", ")})`;
2980
3605
  }
3606
+ return "ObservabilityManager(no handlers)";
2981
3607
  }
2982
3608
  };
2983
3609
 
@@ -3308,6 +3934,13 @@ var MCPAgent = class {
3308
3934
  static {
3309
3935
  __name(this, "MCPAgent");
3310
3936
  }
3937
+ /**
3938
+ * Get the mcp-use package version.
3939
+ * Works in all environments (Node.js, browser, Cloudflare Workers, Deno, etc.)
3940
+ */
3941
+ static getPackageVersion() {
3942
+ return getPackageVersion();
3943
+ }
3311
3944
  llm;
3312
3945
  client;
3313
3946
  connectors;
@@ -4031,7 +4664,7 @@ var MCPAgent = class {
4031
4664
  const historyToUse = externalHistory ?? this.conversationHistory;
4032
4665
  const langchainHistory = [];
4033
4666
  for (const msg of historyToUse) {
4034
- if (this._isHumanMessageLike(msg) || this._isAIMessageLike(msg)) {
4667
+ if (this._isHumanMessageLike(msg) || this._isAIMessageLike(msg) || this._isToolMessageLike(msg)) {
4035
4668
  langchainHistory.push(msg);
4036
4669
  }
4037
4670
  }
@@ -4164,9 +4797,9 @@ var MCPAgent = class {
4164
4797
  }
4165
4798
  }
4166
4799
  if (this.memoryEnabled) {
4167
- this.addToHistory(new import_langchain2.HumanMessage(query));
4168
- if (finalOutput) {
4169
- this.addToHistory(new import_langchain2.AIMessage(finalOutput));
4800
+ const newMessages = accumulatedMessages.slice(langchainHistory.length);
4801
+ for (const msg of newMessages) {
4802
+ this.addToHistory(msg);
4170
4803
  }
4171
4804
  }
4172
4805
  if (outputSchema && finalOutput) {
@@ -4601,7 +5234,9 @@ ${formatPrompt}`
4601
5234
  let chunkCount = 0;
4602
5235
  for await (const chunk of stream) {
4603
5236
  chunkCount++;
4604
- logger.info(`Chunk ${chunkCount}: ${JSON.stringify(chunk, null, 2)}`);
5237
+ logger.debug(
5238
+ `Chunk ${chunkCount}: ${JSON.stringify(chunk, null, 2)}`
5239
+ );
4605
5240
  if (typeof chunk === "string") {
4606
5241
  try {
4607
5242
  structuredResult = JSON.parse(chunk);
@@ -4618,7 +5253,9 @@ ${formatPrompt}`
4618
5253
  }
4619
5254
  }
4620
5255
  if (chunkCount % 10 === 0) {
4621
- logger.info(`\u{1F504} Structured output streaming: ${chunkCount} chunks`);
5256
+ logger.debug(
5257
+ `\u{1F504} Structured output streaming: ${chunkCount} chunks`
5258
+ );
4622
5259
  }
4623
5260
  }
4624
5261
  logger.info(