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
@@ -31,6 +31,360 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
31
31
  ));
32
32
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
33
33
 
34
+ // src/telemetry/events.ts
35
+ function createServerRunEventData(server, transport) {
36
+ const toolRegistrations = Array.from(server.registrations.tools.values());
37
+ const promptRegistrations = Array.from(server.registrations.prompts.values());
38
+ const resourceRegistrations = Array.from(
39
+ server.registrations.resources.values()
40
+ );
41
+ const templateRegistrations = Array.from(
42
+ server.registrations.resourceTemplates.values()
43
+ );
44
+ const allResources = resourceRegistrations.map((r) => ({
45
+ name: r.config.name,
46
+ title: r.config.title ?? null,
47
+ description: r.config.description ?? null,
48
+ uri: r.config.uri ?? null,
49
+ mime_type: r.config.mimeType ?? null
50
+ }));
51
+ const appsSdkResources = allResources.filter(
52
+ (r) => r.mime_type === "text/html+skybridge"
53
+ );
54
+ const mcpUiResources = allResources.filter(
55
+ (r) => r.mime_type === "text/uri-list" || r.mime_type === "text/html"
56
+ );
57
+ const mcpAppsResources = allResources.filter(
58
+ (r) => r.mime_type === "text/html+mcp"
59
+ );
60
+ return {
61
+ transport,
62
+ toolsNumber: server.registeredTools.length,
63
+ resourcesNumber: server.registeredResources.length,
64
+ promptsNumber: server.registeredPrompts.length,
65
+ auth: !!server.oauthProvider,
66
+ name: server.config.name,
67
+ description: server.config.description ?? null,
68
+ baseUrl: server.serverBaseUrl ?? null,
69
+ toolNames: server.registeredTools.length > 0 ? server.registeredTools : null,
70
+ resourceNames: server.registeredResources.length > 0 ? server.registeredResources : null,
71
+ promptNames: server.registeredPrompts.length > 0 ? server.registeredPrompts : null,
72
+ tools: toolRegistrations.length > 0 ? toolRegistrations.map((r) => ({
73
+ name: r.config.name,
74
+ title: r.config.title ?? null,
75
+ description: r.config.description ?? null,
76
+ input_schema: r.config.schema ? JSON.stringify(r.config.schema) : null,
77
+ output_schema: r.config.outputSchema ? JSON.stringify(r.config.outputSchema) : null
78
+ })) : null,
79
+ resources: allResources.length > 0 ? allResources : null,
80
+ prompts: promptRegistrations.length > 0 ? promptRegistrations.map((r) => ({
81
+ name: r.config.name,
82
+ title: r.config.title ?? null,
83
+ description: r.config.description ?? null,
84
+ args: r.config.args ? JSON.stringify(r.config.args) : null
85
+ })) : null,
86
+ templates: templateRegistrations.length > 0 ? templateRegistrations.map((r) => ({
87
+ name: r.config.name,
88
+ title: r.config.title ?? null,
89
+ description: r.config.description ?? null
90
+ })) : null,
91
+ capabilities: {
92
+ logging: true,
93
+ resources: { subscribe: true, listChanged: true }
94
+ },
95
+ appsSdkResources: appsSdkResources.length > 0 ? appsSdkResources : null,
96
+ appsSdkResourcesNumber: appsSdkResources.length,
97
+ mcpUiResources: mcpUiResources.length > 0 ? mcpUiResources : null,
98
+ mcpUiResourcesNumber: mcpUiResources.length,
99
+ mcpAppsResources: mcpAppsResources.length > 0 ? mcpAppsResources : null,
100
+ mcpAppsResourcesNumber: mcpAppsResources.length
101
+ };
102
+ }
103
+ var BaseTelemetryEvent, MCPAgentExecutionEvent, ServerRunEvent, ServerInitializeEvent, ServerToolCallEvent, ServerResourceCallEvent, ServerPromptCallEvent, ServerContextEvent, MCPClientInitEvent, ConnectorInitEvent, ClientAddServerEvent, ClientRemoveServerEvent;
104
+ var init_events = __esm({
105
+ "src/telemetry/events.ts"() {
106
+ "use strict";
107
+ BaseTelemetryEvent = class {
108
+ static {
109
+ __name(this, "BaseTelemetryEvent");
110
+ }
111
+ };
112
+ MCPAgentExecutionEvent = class extends BaseTelemetryEvent {
113
+ constructor(data) {
114
+ super();
115
+ this.data = data;
116
+ }
117
+ static {
118
+ __name(this, "MCPAgentExecutionEvent");
119
+ }
120
+ get name() {
121
+ return "mcp_agent_execution";
122
+ }
123
+ get properties() {
124
+ return {
125
+ // Core execution info
126
+ execution_method: this.data.executionMethod,
127
+ query: this.data.query,
128
+ query_length: this.data.query.length,
129
+ success: this.data.success,
130
+ // Agent configuration
131
+ model_provider: this.data.modelProvider,
132
+ model_name: this.data.modelName,
133
+ server_count: this.data.serverCount,
134
+ server_identifiers: this.data.serverIdentifiers,
135
+ total_tools_available: this.data.totalToolsAvailable,
136
+ tools_available_names: this.data.toolsAvailableNames,
137
+ max_steps_configured: this.data.maxStepsConfigured,
138
+ memory_enabled: this.data.memoryEnabled,
139
+ use_server_manager: this.data.useServerManager,
140
+ // Execution parameters (always include, even if null)
141
+ max_steps_used: this.data.maxStepsUsed,
142
+ manage_connector: this.data.manageConnector,
143
+ external_history_used: this.data.externalHistoryUsed,
144
+ // Execution results (always include, even if null)
145
+ steps_taken: this.data.stepsTaken ?? null,
146
+ tools_used_count: this.data.toolsUsedCount ?? null,
147
+ tools_used_names: this.data.toolsUsedNames ?? null,
148
+ response: this.data.response ?? null,
149
+ response_length: this.data.response ? this.data.response.length : null,
150
+ execution_time_ms: this.data.executionTimeMs ?? null,
151
+ error_type: this.data.errorType ?? null,
152
+ conversation_history_length: this.data.conversationHistoryLength ?? null
153
+ };
154
+ }
155
+ };
156
+ __name(createServerRunEventData, "createServerRunEventData");
157
+ ServerRunEvent = class extends BaseTelemetryEvent {
158
+ constructor(data) {
159
+ super();
160
+ this.data = data;
161
+ }
162
+ static {
163
+ __name(this, "ServerRunEvent");
164
+ }
165
+ get name() {
166
+ return "server_run";
167
+ }
168
+ get properties() {
169
+ return {
170
+ transport: this.data.transport,
171
+ tools_number: this.data.toolsNumber,
172
+ resources_number: this.data.resourcesNumber,
173
+ prompts_number: this.data.promptsNumber,
174
+ auth: this.data.auth,
175
+ name: this.data.name,
176
+ description: this.data.description ?? null,
177
+ base_url: this.data.baseUrl ?? null,
178
+ tool_names: this.data.toolNames ?? null,
179
+ resource_names: this.data.resourceNames ?? null,
180
+ prompt_names: this.data.promptNames ?? null,
181
+ tools: this.data.tools ?? null,
182
+ resources: this.data.resources ?? null,
183
+ prompts: this.data.prompts ?? null,
184
+ templates: this.data.templates ?? null,
185
+ capabilities: this.data.capabilities ? JSON.stringify(this.data.capabilities) : null,
186
+ apps_sdk_resources: this.data.appsSdkResources ? JSON.stringify(this.data.appsSdkResources) : null,
187
+ apps_sdk_resources_number: this.data.appsSdkResourcesNumber ?? 0,
188
+ mcp_ui_resources: this.data.mcpUiResources ? JSON.stringify(this.data.mcpUiResources) : null,
189
+ mcp_ui_resources_number: this.data.mcpUiResourcesNumber ?? 0,
190
+ mcp_apps_resources: this.data.mcpAppsResources ? JSON.stringify(this.data.mcpAppsResources) : null,
191
+ mcp_apps_resources_number: this.data.mcpAppsResourcesNumber ?? 0
192
+ };
193
+ }
194
+ };
195
+ ServerInitializeEvent = class extends BaseTelemetryEvent {
196
+ constructor(data) {
197
+ super();
198
+ this.data = data;
199
+ }
200
+ static {
201
+ __name(this, "ServerInitializeEvent");
202
+ }
203
+ get name() {
204
+ return "server_initialize_call";
205
+ }
206
+ get properties() {
207
+ return {
208
+ protocol_version: this.data.protocolVersion,
209
+ client_info: JSON.stringify(this.data.clientInfo),
210
+ client_capabilities: JSON.stringify(this.data.clientCapabilities),
211
+ session_id: this.data.sessionId ?? null
212
+ };
213
+ }
214
+ };
215
+ ServerToolCallEvent = class extends BaseTelemetryEvent {
216
+ constructor(data) {
217
+ super();
218
+ this.data = data;
219
+ }
220
+ static {
221
+ __name(this, "ServerToolCallEvent");
222
+ }
223
+ get name() {
224
+ return "server_tool_call";
225
+ }
226
+ get properties() {
227
+ return {
228
+ tool_name: this.data.toolName,
229
+ length_input_argument: this.data.lengthInputArgument,
230
+ success: this.data.success,
231
+ error_type: this.data.errorType ?? null,
232
+ execution_time_ms: this.data.executionTimeMs ?? null
233
+ };
234
+ }
235
+ };
236
+ ServerResourceCallEvent = class extends BaseTelemetryEvent {
237
+ constructor(data) {
238
+ super();
239
+ this.data = data;
240
+ }
241
+ static {
242
+ __name(this, "ServerResourceCallEvent");
243
+ }
244
+ get name() {
245
+ return "server_resource_call";
246
+ }
247
+ get properties() {
248
+ return {
249
+ name: this.data.name,
250
+ description: this.data.description,
251
+ contents: this.data.contents,
252
+ success: this.data.success,
253
+ error_type: this.data.errorType ?? null
254
+ };
255
+ }
256
+ };
257
+ ServerPromptCallEvent = class extends BaseTelemetryEvent {
258
+ constructor(data) {
259
+ super();
260
+ this.data = data;
261
+ }
262
+ static {
263
+ __name(this, "ServerPromptCallEvent");
264
+ }
265
+ get name() {
266
+ return "server_prompt_call";
267
+ }
268
+ get properties() {
269
+ return {
270
+ name: this.data.name,
271
+ description: this.data.description,
272
+ success: this.data.success,
273
+ error_type: this.data.errorType ?? null
274
+ };
275
+ }
276
+ };
277
+ ServerContextEvent = class extends BaseTelemetryEvent {
278
+ constructor(data) {
279
+ super();
280
+ this.data = data;
281
+ }
282
+ static {
283
+ __name(this, "ServerContextEvent");
284
+ }
285
+ get name() {
286
+ return `server_context_${this.data.contextType}`;
287
+ }
288
+ get properties() {
289
+ return {
290
+ context_type: this.data.contextType,
291
+ notification_type: this.data.notificationType ?? null
292
+ };
293
+ }
294
+ };
295
+ MCPClientInitEvent = class extends BaseTelemetryEvent {
296
+ constructor(data) {
297
+ super();
298
+ this.data = data;
299
+ }
300
+ static {
301
+ __name(this, "MCPClientInitEvent");
302
+ }
303
+ get name() {
304
+ return "mcpclient_init";
305
+ }
306
+ get properties() {
307
+ return {
308
+ code_mode: this.data.codeMode,
309
+ sandbox: this.data.sandbox,
310
+ all_callbacks: this.data.allCallbacks,
311
+ verify: this.data.verify,
312
+ servers: this.data.servers,
313
+ num_servers: this.data.numServers,
314
+ is_browser: this.data.isBrowser
315
+ };
316
+ }
317
+ };
318
+ ConnectorInitEvent = class extends BaseTelemetryEvent {
319
+ constructor(data) {
320
+ super();
321
+ this.data = data;
322
+ }
323
+ static {
324
+ __name(this, "ConnectorInitEvent");
325
+ }
326
+ get name() {
327
+ return "connector_init";
328
+ }
329
+ get properties() {
330
+ return {
331
+ connector_type: this.data.connectorType,
332
+ server_command: this.data.serverCommand ?? null,
333
+ server_args: this.data.serverArgs ?? null,
334
+ server_url: this.data.serverUrl ?? null,
335
+ public_identifier: this.data.publicIdentifier ?? null
336
+ };
337
+ }
338
+ };
339
+ ClientAddServerEvent = class extends BaseTelemetryEvent {
340
+ constructor(data) {
341
+ super();
342
+ this.data = data;
343
+ }
344
+ static {
345
+ __name(this, "ClientAddServerEvent");
346
+ }
347
+ get name() {
348
+ return "client_add_server";
349
+ }
350
+ get properties() {
351
+ const { serverName, serverConfig } = this.data;
352
+ const url = serverConfig.url;
353
+ return {
354
+ server_name: serverName,
355
+ server_url_domain: url ? this._extractHostname(url) : null,
356
+ transport: serverConfig.transport ?? null,
357
+ has_auth: !!(serverConfig.authToken || serverConfig.authProvider)
358
+ };
359
+ }
360
+ _extractHostname(url) {
361
+ try {
362
+ return new URL(url).hostname;
363
+ } catch {
364
+ return null;
365
+ }
366
+ }
367
+ };
368
+ ClientRemoveServerEvent = class extends BaseTelemetryEvent {
369
+ constructor(data) {
370
+ super();
371
+ this.data = data;
372
+ }
373
+ static {
374
+ __name(this, "ClientRemoveServerEvent");
375
+ }
376
+ get name() {
377
+ return "client_remove_server";
378
+ }
379
+ get properties() {
380
+ return {
381
+ server_name: this.data.serverName
382
+ };
383
+ }
384
+ };
385
+ }
386
+ });
387
+
34
388
  // src/server/utils/runtime.ts
35
389
  function getEnv(key) {
36
390
  if (isDeno) {
@@ -68,57 +422,1005 @@ var init_runtime = __esm({
68
422
  const data = await globalThis.Deno.readFile(path);
69
423
  return data.buffer;
70
424
  }
71
- const { readFileSync } = await import("fs");
72
- const buffer = readFileSync(path);
73
- return buffer.buffer.slice(
74
- buffer.byteOffset,
75
- buffer.byteOffset + buffer.byteLength
76
- );
77
- },
78
- async existsSync(path) {
79
- if (isDeno) {
425
+ const { readFileSync } = await import("fs");
426
+ const buffer = readFileSync(path);
427
+ return buffer.buffer.slice(
428
+ buffer.byteOffset,
429
+ buffer.byteOffset + buffer.byteLength
430
+ );
431
+ },
432
+ async existsSync(path) {
433
+ if (isDeno) {
434
+ try {
435
+ await globalThis.Deno.stat(path);
436
+ return true;
437
+ } catch {
438
+ return false;
439
+ }
440
+ }
441
+ const { existsSync } = await import("fs");
442
+ return existsSync(path);
443
+ },
444
+ async readdirSync(path) {
445
+ if (isDeno) {
446
+ const entries = [];
447
+ for await (const entry of globalThis.Deno.readDir(path)) {
448
+ entries.push(entry.name);
449
+ }
450
+ return entries;
451
+ }
452
+ const { readdirSync } = await import("fs");
453
+ return readdirSync(path);
454
+ }
455
+ };
456
+ pathHelpers = {
457
+ join(...paths) {
458
+ if (isDeno) {
459
+ return paths.join("/").replace(/\/+/g, "/");
460
+ }
461
+ return paths.join("/").replace(/\/+/g, "/");
462
+ },
463
+ relative(from, to) {
464
+ const fromParts = from.split("/").filter((p) => p);
465
+ const toParts = to.split("/").filter((p) => p);
466
+ let i = 0;
467
+ while (i < fromParts.length && i < toParts.length && fromParts[i] === toParts[i]) {
468
+ i++;
469
+ }
470
+ const upCount = fromParts.length - i;
471
+ const relativeParts = [...Array(upCount).fill(".."), ...toParts.slice(i)];
472
+ return relativeParts.join("/");
473
+ }
474
+ };
475
+ __name(generateUUID, "generateUUID");
476
+ }
477
+ });
478
+
479
+ // src/logging.ts
480
+ async function getNodeModules() {
481
+ if (typeof process !== "undefined" && process.platform) {
482
+ try {
483
+ const fs = await import("fs");
484
+ const path = await import("path");
485
+ return { fs: fs.default, path: path.default };
486
+ } catch {
487
+ return { fs: null, path: null };
488
+ }
489
+ }
490
+ return { fs: null, path: null };
491
+ }
492
+ function loadWinstonSync() {
493
+ if (typeof require !== "undefined") {
494
+ try {
495
+ winston = require("winston");
496
+ } catch {
497
+ }
498
+ }
499
+ }
500
+ async function getWinston() {
501
+ if (!winston) {
502
+ winston = await import("winston");
503
+ }
504
+ return winston;
505
+ }
506
+ function isNodeJSEnvironment() {
507
+ try {
508
+ if (typeof navigator !== "undefined" && navigator.userAgent?.includes("Cloudflare-Workers")) {
509
+ return false;
510
+ }
511
+ if (typeof globalThis.EdgeRuntime !== "undefined" || typeof globalThis.Deno !== "undefined") {
512
+ return false;
513
+ }
514
+ const hasNodeGlobals = typeof process !== "undefined" && typeof process.platform !== "undefined" && typeof __dirname !== "undefined";
515
+ return hasNodeGlobals;
516
+ } catch {
517
+ return false;
518
+ }
519
+ }
520
+ function resolveLevel(env) {
521
+ const envValue = typeof process !== "undefined" && process.env ? env : void 0;
522
+ switch (envValue?.trim()) {
523
+ case "2":
524
+ return "debug";
525
+ case "1":
526
+ return "info";
527
+ default:
528
+ return "info";
529
+ }
530
+ }
531
+ var winston, DEFAULT_LOGGER_NAME, SimpleConsoleLogger, Logger, logger;
532
+ var init_logging = __esm({
533
+ "src/logging.ts"() {
534
+ "use strict";
535
+ __name(getNodeModules, "getNodeModules");
536
+ winston = null;
537
+ __name(loadWinstonSync, "loadWinstonSync");
538
+ __name(getWinston, "getWinston");
539
+ DEFAULT_LOGGER_NAME = "mcp-use";
540
+ __name(isNodeJSEnvironment, "isNodeJSEnvironment");
541
+ SimpleConsoleLogger = class {
542
+ static {
543
+ __name(this, "SimpleConsoleLogger");
544
+ }
545
+ _level;
546
+ name;
547
+ constructor(name = DEFAULT_LOGGER_NAME, level = "info") {
548
+ this.name = name;
549
+ this._level = level;
550
+ }
551
+ shouldLog(level) {
552
+ const levels = [
553
+ "error",
554
+ "warn",
555
+ "info",
556
+ "http",
557
+ "verbose",
558
+ "debug",
559
+ "silly"
560
+ ];
561
+ const currentIndex = levels.indexOf(this._level);
562
+ const messageIndex = levels.indexOf(level);
563
+ return messageIndex <= currentIndex;
564
+ }
565
+ formatMessage(level, message) {
566
+ const timestamp = (/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", { hour12: false });
567
+ return `${timestamp} [${this.name}] ${level}: ${message}`;
568
+ }
569
+ error(message) {
570
+ if (this.shouldLog("error")) {
571
+ console.error(this.formatMessage("error", message));
572
+ }
573
+ }
574
+ warn(message) {
575
+ if (this.shouldLog("warn")) {
576
+ console.warn(this.formatMessage("warn", message));
577
+ }
578
+ }
579
+ info(message) {
580
+ if (this.shouldLog("info")) {
581
+ console.info(this.formatMessage("info", message));
582
+ }
583
+ }
584
+ debug(message) {
585
+ if (this.shouldLog("debug")) {
586
+ console.debug(this.formatMessage("debug", message));
587
+ }
588
+ }
589
+ http(message) {
590
+ if (this.shouldLog("http")) {
591
+ console.log(this.formatMessage("http", message));
592
+ }
593
+ }
594
+ verbose(message) {
595
+ if (this.shouldLog("verbose")) {
596
+ console.log(this.formatMessage("verbose", message));
597
+ }
598
+ }
599
+ silly(message) {
600
+ if (this.shouldLog("silly")) {
601
+ console.log(this.formatMessage("silly", message));
602
+ }
603
+ }
604
+ // Make it compatible with Winston interface
605
+ get level() {
606
+ return this._level;
607
+ }
608
+ set level(newLevel) {
609
+ this._level = newLevel;
610
+ }
611
+ };
612
+ __name(resolveLevel, "resolveLevel");
613
+ Logger = class {
614
+ static {
615
+ __name(this, "Logger");
616
+ }
617
+ static instances = {};
618
+ static simpleInstances = {};
619
+ static currentFormat = "minimal";
620
+ static get(name = DEFAULT_LOGGER_NAME) {
621
+ if (!isNodeJSEnvironment()) {
622
+ if (!this.simpleInstances[name]) {
623
+ const debugEnv = typeof process !== "undefined" && process.env?.DEBUG || void 0;
624
+ this.simpleInstances[name] = new SimpleConsoleLogger(
625
+ name,
626
+ resolveLevel(debugEnv)
627
+ );
628
+ }
629
+ return this.simpleInstances[name];
630
+ }
631
+ if (!this.instances[name]) {
632
+ if (!winston) {
633
+ throw new Error("Winston not loaded - call Logger.configure() first");
634
+ }
635
+ const { createLogger, format } = winston;
636
+ const { combine, timestamp, label, colorize, splat } = format;
637
+ this.instances[name] = createLogger({
638
+ level: resolveLevel(process.env.DEBUG),
639
+ format: combine(
640
+ colorize(),
641
+ splat(),
642
+ label({ label: name }),
643
+ timestamp({ format: "HH:mm:ss" }),
644
+ this.getFormatter()
645
+ ),
646
+ transports: []
647
+ });
648
+ }
649
+ return this.instances[name];
650
+ }
651
+ static getFormatter() {
652
+ if (!winston) {
653
+ throw new Error("Winston not loaded");
654
+ }
655
+ const { format } = winston;
656
+ const { printf } = format;
657
+ const minimalFormatter = printf(({ level, message, label, timestamp }) => {
658
+ return `${timestamp} [${label}] ${level}: ${message}`;
659
+ });
660
+ const detailedFormatter = printf(({ level, message, label, timestamp }) => {
661
+ return `${timestamp} [${label}] ${level.toUpperCase()}: ${message}`;
662
+ });
663
+ const emojiFormatter = printf(({ level, message, label, timestamp }) => {
664
+ return `${timestamp} [${label}] ${level.toUpperCase()}: ${message}`;
665
+ });
666
+ switch (this.currentFormat) {
667
+ case "minimal":
668
+ return minimalFormatter;
669
+ case "detailed":
670
+ return detailedFormatter;
671
+ case "emoji":
672
+ return emojiFormatter;
673
+ default:
674
+ return minimalFormatter;
675
+ }
676
+ }
677
+ static async configure(options = {}) {
678
+ const { level, console: console2 = true, file, format = "minimal" } = options;
679
+ const debugEnv = typeof process !== "undefined" && process.env?.DEBUG || void 0;
680
+ const resolvedLevel = level ?? resolveLevel(debugEnv);
681
+ this.currentFormat = format;
682
+ if (!isNodeJSEnvironment()) {
683
+ Object.values(this.simpleInstances).forEach((logger2) => {
684
+ logger2.level = resolvedLevel;
685
+ });
686
+ return;
687
+ }
688
+ await getWinston();
689
+ if (!winston) {
690
+ throw new Error("Failed to load winston");
691
+ }
692
+ const root = this.get();
693
+ root.level = resolvedLevel;
694
+ const winstonRoot = root;
695
+ winstonRoot.clear();
696
+ if (console2) {
697
+ winstonRoot.add(new winston.transports.Console());
698
+ }
699
+ if (file) {
700
+ const { fs: nodeFs, path: nodePath } = await getNodeModules();
701
+ if (nodeFs && nodePath) {
702
+ const dir = nodePath.dirname(nodePath.resolve(file));
703
+ if (!nodeFs.existsSync(dir)) {
704
+ nodeFs.mkdirSync(dir, { recursive: true });
705
+ }
706
+ winstonRoot.add(new winston.transports.File({ filename: file }));
707
+ }
708
+ }
709
+ const { format: winstonFormat } = winston;
710
+ const { combine, timestamp, label, colorize, splat } = winstonFormat;
711
+ Object.values(this.instances).forEach((logger2) => {
712
+ if (logger2 && "format" in logger2) {
713
+ logger2.level = resolvedLevel;
714
+ logger2.format = combine(
715
+ colorize(),
716
+ splat(),
717
+ label({ label: DEFAULT_LOGGER_NAME }),
718
+ timestamp({ format: "HH:mm:ss" }),
719
+ this.getFormatter()
720
+ );
721
+ }
722
+ });
723
+ }
724
+ static setDebug(enabled) {
725
+ let level;
726
+ if (enabled === 2 || enabled === true) level = "debug";
727
+ else if (enabled === 1) level = "info";
728
+ else level = "info";
729
+ Object.values(this.simpleInstances).forEach((logger2) => {
730
+ logger2.level = level;
731
+ });
732
+ Object.values(this.instances).forEach((logger2) => {
733
+ if (logger2) {
734
+ logger2.level = level;
735
+ }
736
+ });
737
+ if (typeof process !== "undefined" && process.env) {
738
+ process.env.DEBUG = enabled ? enabled === true ? "2" : String(enabled) : "0";
739
+ }
740
+ }
741
+ static setFormat(format) {
742
+ this.currentFormat = format;
743
+ this.configure({ format });
744
+ }
745
+ };
746
+ if (isNodeJSEnvironment()) {
747
+ loadWinstonSync();
748
+ if (winston) {
749
+ Logger.configure();
750
+ }
751
+ }
752
+ logger = Logger.get();
753
+ }
754
+ });
755
+
756
+ // src/version.ts
757
+ function getPackageVersion() {
758
+ return VERSION;
759
+ }
760
+ var VERSION;
761
+ var init_version = __esm({
762
+ "src/version.ts"() {
763
+ "use strict";
764
+ VERSION = "1.10.0-canary.11";
765
+ __name(getPackageVersion, "getPackageVersion");
766
+ }
767
+ });
768
+
769
+ // src/telemetry/utils.ts
770
+ var init_utils = __esm({
771
+ "src/telemetry/utils.ts"() {
772
+ "use strict";
773
+ init_version();
774
+ }
775
+ });
776
+
777
+ // src/telemetry/telemetry.ts
778
+ function detectRuntimeEnvironment() {
779
+ try {
780
+ if (typeof globalThis.Bun !== "undefined") {
781
+ return "bun";
782
+ }
783
+ if (typeof globalThis.Deno !== "undefined") {
784
+ return "deno";
785
+ }
786
+ if (typeof navigator !== "undefined" && navigator.userAgent?.includes("Cloudflare-Workers")) {
787
+ return "cloudflare-workers";
788
+ }
789
+ if (typeof globalThis.EdgeRuntime !== "undefined") {
790
+ return "edge";
791
+ }
792
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
793
+ return "browser";
794
+ }
795
+ if (typeof process !== "undefined" && typeof process.versions?.node !== "undefined") {
796
+ return "node";
797
+ }
798
+ return "unknown";
799
+ } catch {
800
+ return "unknown";
801
+ }
802
+ }
803
+ function getStorageCapability(env) {
804
+ switch (env) {
805
+ case "node":
806
+ case "bun":
807
+ return "filesystem";
808
+ case "browser":
809
+ try {
810
+ if (typeof localStorage !== "undefined") {
811
+ localStorage.setItem("__mcp_use_test__", "1");
812
+ localStorage.removeItem("__mcp_use_test__");
813
+ return "localStorage";
814
+ }
815
+ } catch {
816
+ }
817
+ return "session-only";
818
+ case "deno":
819
+ return "session-only";
820
+ default:
821
+ return "session-only";
822
+ }
823
+ }
824
+ function getRuntimeEnvironment() {
825
+ if (cachedEnvironment === null) {
826
+ cachedEnvironment = detectRuntimeEnvironment();
827
+ }
828
+ return cachedEnvironment;
829
+ }
830
+ var USER_ID_STORAGE_KEY, cachedEnvironment, ScarfEventLogger, Telemetry;
831
+ var init_telemetry = __esm({
832
+ "src/telemetry/telemetry.ts"() {
833
+ "use strict";
834
+ init_runtime();
835
+ init_logging();
836
+ init_events();
837
+ init_utils();
838
+ USER_ID_STORAGE_KEY = "mcp_use_user_id";
839
+ __name(detectRuntimeEnvironment, "detectRuntimeEnvironment");
840
+ __name(getStorageCapability, "getStorageCapability");
841
+ cachedEnvironment = null;
842
+ __name(getRuntimeEnvironment, "getRuntimeEnvironment");
843
+ ScarfEventLogger = class {
844
+ static {
845
+ __name(this, "ScarfEventLogger");
846
+ }
847
+ endpoint;
848
+ timeout;
849
+ constructor(endpoint, timeout = 3e3) {
850
+ this.endpoint = endpoint;
851
+ this.timeout = timeout;
852
+ }
853
+ async logEvent(properties) {
854
+ try {
855
+ const controller = new AbortController();
856
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
857
+ const response = await fetch(this.endpoint, {
858
+ method: "POST",
859
+ headers: {
860
+ "Content-Type": "application/json"
861
+ },
862
+ body: JSON.stringify(properties),
863
+ signal: controller.signal
864
+ });
865
+ clearTimeout(timeoutId);
866
+ if (!response.ok) {
867
+ throw new Error(`HTTP error! status: ${response.status}`);
868
+ }
869
+ } catch (error2) {
870
+ logger.debug(`Failed to send Scarf event: ${error2}`);
871
+ }
872
+ }
873
+ };
874
+ Telemetry = class _Telemetry {
875
+ static {
876
+ __name(this, "Telemetry");
877
+ }
878
+ static instance = null;
879
+ PROJECT_API_KEY = "phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";
880
+ HOST = "https://eu.i.posthog.com";
881
+ SCARF_GATEWAY_URL = "https://mcpuse.gateway.scarf.sh/events-ts";
882
+ UNKNOWN_USER_ID = "UNKNOWN_USER_ID";
883
+ _currUserId = null;
884
+ _posthogNodeClient = null;
885
+ _posthogBrowserClient = null;
886
+ _posthogLoading = null;
887
+ _scarfClient = null;
888
+ _runtimeEnvironment;
889
+ _storageCapability;
890
+ _source;
891
+ // Node.js specific paths (lazily computed)
892
+ _userIdPath = null;
893
+ _versionDownloadPath = null;
894
+ constructor() {
895
+ this._runtimeEnvironment = getRuntimeEnvironment();
896
+ this._storageCapability = getStorageCapability(this._runtimeEnvironment);
897
+ this._source = typeof process !== "undefined" && process.env?.MCP_USE_TELEMETRY_SOURCE || this._runtimeEnvironment;
898
+ const telemetryDisabled = this._checkTelemetryDisabled();
899
+ const canSupportTelemetry = this._runtimeEnvironment !== "unknown";
900
+ if (telemetryDisabled) {
901
+ this._posthogNodeClient = null;
902
+ this._posthogBrowserClient = null;
903
+ this._scarfClient = null;
904
+ logger.debug("Telemetry disabled via environment/localStorage");
905
+ } else if (!canSupportTelemetry) {
906
+ this._posthogNodeClient = null;
907
+ this._posthogBrowserClient = null;
908
+ this._scarfClient = null;
909
+ logger.debug(
910
+ `Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`
911
+ );
912
+ } else {
913
+ logger.info(
914
+ "Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."
915
+ );
916
+ this._posthogLoading = this._initPostHog();
917
+ try {
918
+ this._scarfClient = new ScarfEventLogger(this.SCARF_GATEWAY_URL, 3e3);
919
+ } catch (e) {
920
+ logger.warn(`Failed to initialize Scarf telemetry: ${e}`);
921
+ this._scarfClient = null;
922
+ }
923
+ }
924
+ }
925
+ _checkTelemetryDisabled() {
926
+ if (typeof process !== "undefined" && process.env?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase() === "false") {
927
+ return true;
928
+ }
929
+ if (typeof localStorage !== "undefined" && localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY") === "false") {
930
+ return true;
931
+ }
932
+ return false;
933
+ }
934
+ async _initPostHog() {
935
+ const isBrowser = this._runtimeEnvironment === "browser";
936
+ if (isBrowser) {
937
+ await this._initPostHogBrowser();
938
+ } else {
939
+ await this._initPostHogNode();
940
+ }
941
+ }
942
+ async _initPostHogBrowser() {
943
+ try {
944
+ const posthogModule = await import("posthog-js");
945
+ const posthog = posthogModule.default || posthogModule.posthog;
946
+ if (!posthog || typeof posthog.init !== "function") {
947
+ throw new Error("posthog-js module did not export expected interface");
948
+ }
949
+ posthog.init(this.PROJECT_API_KEY, {
950
+ api_host: this.HOST,
951
+ persistence: "localStorage",
952
+ autocapture: false,
953
+ // We only want explicit captures
954
+ capture_pageview: false,
955
+ // We don't want automatic pageview tracking
956
+ disable_session_recording: true,
957
+ // No session recording
958
+ loaded: /* @__PURE__ */ __name(() => {
959
+ logger.debug("PostHog browser client initialized");
960
+ }, "loaded")
961
+ });
962
+ this._posthogBrowserClient = posthog;
963
+ } catch (e) {
964
+ logger.warn(`Failed to initialize PostHog browser telemetry: ${e}`);
965
+ this._posthogBrowserClient = null;
966
+ }
967
+ }
968
+ async _initPostHogNode() {
969
+ try {
970
+ const { PostHog } = await import("posthog-node");
971
+ const isServerlessEnvironment = [
972
+ "cloudflare-workers",
973
+ "edge",
974
+ "deno"
975
+ ].includes(this._runtimeEnvironment);
976
+ const posthogOptions = {
977
+ host: this.HOST,
978
+ disableGeoip: false
979
+ };
980
+ if (isServerlessEnvironment) {
981
+ posthogOptions.flushAt = 1;
982
+ posthogOptions.flushInterval = 0;
983
+ }
984
+ this._posthogNodeClient = new PostHog(
985
+ this.PROJECT_API_KEY,
986
+ posthogOptions
987
+ );
988
+ logger.debug("PostHog Node.js client initialized");
989
+ } catch (e) {
990
+ logger.warn(`Failed to initialize PostHog Node.js telemetry: ${e}`);
991
+ this._posthogNodeClient = null;
992
+ }
993
+ }
994
+ /**
995
+ * Get the detected runtime environment
996
+ */
997
+ get runtimeEnvironment() {
998
+ return this._runtimeEnvironment;
999
+ }
1000
+ /**
1001
+ * Get the storage capability for this environment
1002
+ */
1003
+ get storageCapability() {
1004
+ return this._storageCapability;
1005
+ }
1006
+ static getInstance() {
1007
+ if (!_Telemetry.instance) {
1008
+ _Telemetry.instance = new _Telemetry();
1009
+ }
1010
+ return _Telemetry.instance;
1011
+ }
1012
+ /**
1013
+ * Set the source identifier for telemetry events.
1014
+ * This allows tracking usage from different applications.
1015
+ * @param source - The source identifier (e.g., "my-app", "cli", "vs-code-extension")
1016
+ */
1017
+ setSource(source) {
1018
+ this._source = source;
1019
+ logger.debug(`Telemetry source set to: ${source}`);
1020
+ }
1021
+ /**
1022
+ * Get the current source identifier.
1023
+ */
1024
+ getSource() {
1025
+ return this._source;
1026
+ }
1027
+ /**
1028
+ * Check if telemetry is enabled.
1029
+ */
1030
+ get isEnabled() {
1031
+ return this._posthogNodeClient !== null || this._posthogBrowserClient !== null || this._scarfClient !== null;
1032
+ }
1033
+ get userId() {
1034
+ if (this._currUserId) {
1035
+ return this._currUserId;
1036
+ }
1037
+ try {
1038
+ switch (this._storageCapability) {
1039
+ case "filesystem":
1040
+ this._currUserId = this._getUserIdFromFilesystem();
1041
+ break;
1042
+ case "localStorage":
1043
+ this._currUserId = this._getUserIdFromLocalStorage();
1044
+ break;
1045
+ case "session-only":
1046
+ default:
1047
+ this._currUserId = `session-${generateUUID()}`;
1048
+ logger.debug(
1049
+ `Using session-based user ID (${this._runtimeEnvironment} environment)`
1050
+ );
1051
+ break;
1052
+ }
1053
+ if (this._storageCapability === "filesystem" && this._currUserId) {
1054
+ this._trackPackageDownloadInternal(this._currUserId, {
1055
+ triggered_by: "user_id_property"
1056
+ }).catch((e) => logger.debug(`Failed to track package download: ${e}`));
1057
+ }
1058
+ } catch (e) {
1059
+ logger.debug(`Failed to get/create user ID: ${e}`);
1060
+ this._currUserId = this.UNKNOWN_USER_ID;
1061
+ }
1062
+ return this._currUserId;
1063
+ }
1064
+ /**
1065
+ * Get or create user ID from filesystem (Node.js/Bun)
1066
+ */
1067
+ _getUserIdFromFilesystem() {
1068
+ const fs = require("fs");
1069
+ const os = require("os");
1070
+ const path = require("path");
1071
+ if (!this._userIdPath) {
1072
+ this._userIdPath = path.join(
1073
+ this._getCacheHome(os, path),
1074
+ "mcp_use_3",
1075
+ "telemetry_user_id"
1076
+ );
1077
+ }
1078
+ const isFirstTime = !fs.existsSync(this._userIdPath);
1079
+ if (isFirstTime) {
1080
+ logger.debug(`Creating user ID path: ${this._userIdPath}`);
1081
+ fs.mkdirSync(path.dirname(this._userIdPath), { recursive: true });
1082
+ const newUserId = generateUUID();
1083
+ fs.writeFileSync(this._userIdPath, newUserId);
1084
+ logger.debug(`User ID path created: ${this._userIdPath}`);
1085
+ return newUserId;
1086
+ }
1087
+ return fs.readFileSync(this._userIdPath, "utf-8").trim();
1088
+ }
1089
+ /**
1090
+ * Get or create user ID from localStorage (Browser)
1091
+ */
1092
+ _getUserIdFromLocalStorage() {
1093
+ try {
1094
+ let userId = localStorage.getItem(USER_ID_STORAGE_KEY);
1095
+ if (!userId) {
1096
+ userId = generateUUID();
1097
+ localStorage.setItem(USER_ID_STORAGE_KEY, userId);
1098
+ logger.debug(`Created new browser user ID`);
1099
+ }
1100
+ return userId;
1101
+ } catch (e) {
1102
+ logger.debug(`localStorage access failed: ${e}`);
1103
+ return `session-${generateUUID()}`;
1104
+ }
1105
+ }
1106
+ _getCacheHome(os, path) {
1107
+ const envVar = process.env.XDG_CACHE_HOME;
1108
+ if (envVar && path.isAbsolute(envVar)) {
1109
+ return envVar;
1110
+ }
1111
+ const platform = process.platform;
1112
+ const homeDir = os.homedir();
1113
+ if (platform === "win32") {
1114
+ const appdata = process.env.LOCALAPPDATA || process.env.APPDATA;
1115
+ if (appdata) {
1116
+ return appdata;
1117
+ }
1118
+ return path.join(homeDir, "AppData", "Local");
1119
+ } else if (platform === "darwin") {
1120
+ return path.join(homeDir, "Library", "Caches");
1121
+ } else {
1122
+ return path.join(homeDir, ".cache");
1123
+ }
1124
+ }
1125
+ async capture(event) {
1126
+ if (this._posthogLoading) {
1127
+ await this._posthogLoading;
1128
+ }
1129
+ if (!this._posthogNodeClient && !this._posthogBrowserClient && !this._scarfClient) {
1130
+ return;
1131
+ }
1132
+ const properties = { ...event.properties };
1133
+ properties.mcp_use_version = getPackageVersion();
1134
+ properties.language = "typescript";
1135
+ properties.source = this._source;
1136
+ properties.runtime = this._runtimeEnvironment;
1137
+ if (this._posthogNodeClient) {
1138
+ try {
1139
+ logger.debug(`CAPTURE: PostHog Node Event ${event.name}`);
1140
+ this._posthogNodeClient.capture({
1141
+ distinctId: this.userId,
1142
+ event: event.name,
1143
+ properties
1144
+ });
1145
+ } catch (e) {
1146
+ logger.debug(`Failed to track PostHog Node event ${event.name}: ${e}`);
1147
+ }
1148
+ }
1149
+ if (this._posthogBrowserClient) {
1150
+ try {
1151
+ logger.debug(`CAPTURE: PostHog Browser Event ${event.name}`);
1152
+ this._posthogBrowserClient.capture(event.name, {
1153
+ ...properties,
1154
+ distinct_id: this.userId
1155
+ });
1156
+ } catch (e) {
1157
+ logger.debug(
1158
+ `Failed to track PostHog Browser event ${event.name}: ${e}`
1159
+ );
1160
+ }
1161
+ }
1162
+ if (this._scarfClient) {
1163
+ try {
1164
+ const scarfProperties = {
1165
+ ...properties,
1166
+ user_id: this.userId,
1167
+ event: event.name
1168
+ };
1169
+ await this._scarfClient.logEvent(scarfProperties);
1170
+ } catch (e) {
1171
+ logger.debug(`Failed to track Scarf event ${event.name}: ${e}`);
1172
+ }
1173
+ }
1174
+ }
1175
+ // ============================================================================
1176
+ // Package Download Tracking (Node.js only)
1177
+ // ============================================================================
1178
+ /**
1179
+ * Track package download event.
1180
+ * This is a public wrapper that safely accesses userId.
1181
+ */
1182
+ async trackPackageDownload(properties) {
1183
+ return this._trackPackageDownloadInternal(this.userId, properties);
1184
+ }
1185
+ /**
1186
+ * Internal method to track package download with explicit userId.
1187
+ */
1188
+ async _trackPackageDownloadInternal(userId, properties) {
1189
+ if (!this._scarfClient) {
1190
+ return;
1191
+ }
1192
+ if (this._storageCapability !== "filesystem") {
1193
+ return;
1194
+ }
1195
+ try {
1196
+ const fs = require("fs");
1197
+ const path = require("path");
1198
+ const os = require("os");
1199
+ if (!this._versionDownloadPath) {
1200
+ this._versionDownloadPath = path.join(
1201
+ this._getCacheHome(os, path),
1202
+ "mcp_use",
1203
+ "download_version"
1204
+ );
1205
+ }
1206
+ const currentVersion = getPackageVersion();
1207
+ let shouldTrack = false;
1208
+ let firstDownload = false;
1209
+ if (!fs.existsSync(this._versionDownloadPath)) {
1210
+ shouldTrack = true;
1211
+ firstDownload = true;
1212
+ fs.mkdirSync(path.dirname(this._versionDownloadPath), {
1213
+ recursive: true
1214
+ });
1215
+ fs.writeFileSync(this._versionDownloadPath, currentVersion);
1216
+ } else {
1217
+ const savedVersion = fs.readFileSync(this._versionDownloadPath, "utf-8").trim();
1218
+ if (currentVersion > savedVersion) {
1219
+ shouldTrack = true;
1220
+ firstDownload = false;
1221
+ fs.writeFileSync(this._versionDownloadPath, currentVersion);
1222
+ }
1223
+ }
1224
+ if (shouldTrack) {
1225
+ logger.debug(
1226
+ `Tracking package download event with properties: ${JSON.stringify(properties)}`
1227
+ );
1228
+ const eventProperties = { ...properties || {} };
1229
+ eventProperties.mcp_use_version = currentVersion;
1230
+ eventProperties.user_id = userId;
1231
+ eventProperties.event = "package_download";
1232
+ eventProperties.first_download = firstDownload;
1233
+ eventProperties.language = "typescript";
1234
+ eventProperties.source = this._source;
1235
+ eventProperties.runtime = this._runtimeEnvironment;
1236
+ await this._scarfClient.logEvent(eventProperties);
1237
+ }
1238
+ } catch (e) {
1239
+ logger.debug(`Failed to track Scarf package_download event: ${e}`);
1240
+ }
1241
+ }
1242
+ // ============================================================================
1243
+ // Agent Events
1244
+ // ============================================================================
1245
+ async trackAgentExecution(data) {
1246
+ if (!this.isEnabled) return;
1247
+ const event = new MCPAgentExecutionEvent(data);
1248
+ await this.capture(event);
1249
+ }
1250
+ // ============================================================================
1251
+ // Server Events
1252
+ // ============================================================================
1253
+ /**
1254
+ * Track server run event directly from an MCPServer instance.
1255
+ */
1256
+ async trackServerRunFromServer(server, transport) {
1257
+ if (!this.isEnabled) return;
1258
+ const data = createServerRunEventData(server, transport);
1259
+ const event = new ServerRunEvent(data);
1260
+ await this.capture(event);
1261
+ }
1262
+ async trackServerInitialize(data) {
1263
+ if (!this.isEnabled) return;
1264
+ const event = new ServerInitializeEvent(data);
1265
+ await this.capture(event);
1266
+ }
1267
+ async trackServerToolCall(data) {
1268
+ if (!this.isEnabled) return;
1269
+ const event = new ServerToolCallEvent(data);
1270
+ await this.capture(event);
1271
+ }
1272
+ async trackServerResourceCall(data) {
1273
+ if (!this.isEnabled) return;
1274
+ const event = new ServerResourceCallEvent(data);
1275
+ await this.capture(event);
1276
+ }
1277
+ async trackServerPromptCall(data) {
1278
+ if (!this.isEnabled) return;
1279
+ const event = new ServerPromptCallEvent(data);
1280
+ await this.capture(event);
1281
+ }
1282
+ async trackServerContext(data) {
1283
+ if (!this.isEnabled) return;
1284
+ const event = new ServerContextEvent(data);
1285
+ await this.capture(event);
1286
+ }
1287
+ // ============================================================================
1288
+ // Client Events
1289
+ // ============================================================================
1290
+ async trackMCPClientInit(data) {
1291
+ if (!this.isEnabled) return;
1292
+ const event = new MCPClientInitEvent(data);
1293
+ await this.capture(event);
1294
+ }
1295
+ async trackConnectorInit(data) {
1296
+ if (!this.isEnabled) return;
1297
+ const event = new ConnectorInitEvent(data);
1298
+ await this.capture(event);
1299
+ }
1300
+ async trackClientAddServer(serverName, serverConfig) {
1301
+ if (!this.isEnabled) return;
1302
+ const event = new ClientAddServerEvent({ serverName, serverConfig });
1303
+ await this.capture(event);
1304
+ }
1305
+ async trackClientRemoveServer(serverName) {
1306
+ if (!this.isEnabled) return;
1307
+ const event = new ClientRemoveServerEvent({ serverName });
1308
+ await this.capture(event);
1309
+ }
1310
+ // ============================================================================
1311
+ // React Hook / Browser specific events
1312
+ // ============================================================================
1313
+ async trackUseMcpConnection(data) {
1314
+ if (!this.isEnabled) return;
1315
+ await this.capture({
1316
+ name: "usemcp_connection",
1317
+ properties: {
1318
+ url_domain: new URL(data.url).hostname,
1319
+ // Only domain for privacy
1320
+ transport_type: data.transportType,
1321
+ success: data.success,
1322
+ error_type: data.errorType ?? null,
1323
+ connection_time_ms: data.connectionTimeMs ?? null,
1324
+ has_oauth: data.hasOAuth,
1325
+ has_sampling: data.hasSampling,
1326
+ has_elicitation: data.hasElicitation
1327
+ }
1328
+ });
1329
+ }
1330
+ async trackUseMcpToolCall(data) {
1331
+ if (!this.isEnabled) return;
1332
+ await this.capture({
1333
+ name: "usemcp_tool_call",
1334
+ properties: {
1335
+ tool_name: data.toolName,
1336
+ success: data.success,
1337
+ error_type: data.errorType ?? null,
1338
+ execution_time_ms: data.executionTimeMs ?? null
1339
+ }
1340
+ });
1341
+ }
1342
+ async trackUseMcpResourceRead(data) {
1343
+ if (!this.isEnabled) return;
1344
+ await this.capture({
1345
+ name: "usemcp_resource_read",
1346
+ properties: {
1347
+ resource_uri_scheme: data.resourceUri.split(":")[0],
1348
+ // Only scheme for privacy
1349
+ success: data.success,
1350
+ error_type: data.errorType ?? null
1351
+ }
1352
+ });
1353
+ }
1354
+ // ============================================================================
1355
+ // Browser-specific Methods
1356
+ // ============================================================================
1357
+ /**
1358
+ * Identify the current user (useful for linking sessions)
1359
+ * Browser only - no-op in Node.js
1360
+ */
1361
+ identify(userId, properties) {
1362
+ if (this._posthogBrowserClient) {
80
1363
  try {
81
- await globalThis.Deno.stat(path);
82
- return true;
83
- } catch {
84
- return false;
1364
+ this._posthogBrowserClient.identify(userId, properties);
1365
+ } catch (e) {
1366
+ logger.debug(`Failed to identify user: ${e}`);
85
1367
  }
86
1368
  }
87
- const { existsSync } = await import("fs");
88
- return existsSync(path);
89
- },
90
- async readdirSync(path) {
91
- if (isDeno) {
92
- const entries = [];
93
- for await (const entry of globalThis.Deno.readDir(path)) {
94
- entries.push(entry.name);
1369
+ }
1370
+ /**
1371
+ * Reset the user identity (useful for logout)
1372
+ * Browser only - no-op in Node.js
1373
+ */
1374
+ reset() {
1375
+ if (this._posthogBrowserClient) {
1376
+ try {
1377
+ this._posthogBrowserClient.reset();
1378
+ } catch (e) {
1379
+ logger.debug(`Failed to reset user: ${e}`);
95
1380
  }
96
- return entries;
97
1381
  }
98
- const { readdirSync } = await import("fs");
99
- return readdirSync(path);
1382
+ this._currUserId = null;
100
1383
  }
101
- };
102
- pathHelpers = {
103
- join(...paths) {
104
- if (isDeno) {
105
- return paths.join("/").replace(/\/+/g, "/");
1384
+ // ============================================================================
1385
+ // Node.js-specific Methods
1386
+ // ============================================================================
1387
+ /**
1388
+ * Flush the telemetry queue (Node.js only)
1389
+ */
1390
+ flush() {
1391
+ if (this._posthogNodeClient) {
1392
+ try {
1393
+ this._posthogNodeClient.flush();
1394
+ logger.debug("PostHog client telemetry queue flushed");
1395
+ } catch (e) {
1396
+ logger.debug(`Failed to flush PostHog client: ${e}`);
1397
+ }
106
1398
  }
107
- return paths.join("/").replace(/\/+/g, "/");
108
- },
109
- relative(from, to) {
110
- const fromParts = from.split("/").filter((p) => p);
111
- const toParts = to.split("/").filter((p) => p);
112
- let i = 0;
113
- while (i < fromParts.length && i < toParts.length && fromParts[i] === toParts[i]) {
114
- i++;
1399
+ }
1400
+ /**
1401
+ * Shutdown the telemetry client (Node.js only)
1402
+ */
1403
+ shutdown() {
1404
+ if (this._posthogNodeClient) {
1405
+ try {
1406
+ this._posthogNodeClient.shutdown();
1407
+ logger.debug("PostHog client shutdown successfully");
1408
+ } catch (e) {
1409
+ logger.debug(`Error shutting down PostHog client: ${e}`);
1410
+ }
115
1411
  }
116
- const upCount = fromParts.length - i;
117
- const relativeParts = [...Array(upCount).fill(".."), ...toParts.slice(i)];
118
- return relativeParts.join("/");
119
1412
  }
120
1413
  };
121
- __name(generateUUID, "generateUUID");
1414
+ }
1415
+ });
1416
+
1417
+ // src/telemetry/index.ts
1418
+ var init_telemetry2 = __esm({
1419
+ "src/telemetry/index.ts"() {
1420
+ "use strict";
1421
+ init_events();
1422
+ init_telemetry();
1423
+ init_utils();
122
1424
  }
123
1425
  });
124
1426
 
@@ -373,6 +1675,9 @@ function createSampleMethod(createMessage, progressToken, sendNotification2) {
373
1675
  `Sampling timed out after ${timeout}ms`
374
1676
  );
375
1677
  console.log("[SAMPLING DEBUG] Got result:", result);
1678
+ Telemetry.getInstance().trackServerContext({
1679
+ contextType: "sample"
1680
+ }).catch((e) => console.debug(`Failed to track sample context: ${e}`));
376
1681
  return result;
377
1682
  } catch (error2) {
378
1683
  console.error("[SAMPLING DEBUG] Error during sampling:", error2);
@@ -395,6 +1700,9 @@ function createElicitMethod(elicitInput) {
395
1700
  const { timeout } = options ?? {};
396
1701
  const sdkTimeout = timeout && timeout !== Infinity ? timeout : 2147483647;
397
1702
  const result = await elicitInput(sdkParams, { timeout: sdkTimeout });
1703
+ Telemetry.getInstance().trackServerContext({
1704
+ contextType: "elicit"
1705
+ }).catch((e) => console.debug(`Failed to track elicit context: ${e}`));
398
1706
  if (zodSchema && result.action === "accept" && result.data) {
399
1707
  try {
400
1708
  const validatedData = zodSchema.parse(result.data);
@@ -403,9 +1711,10 @@ function createElicitMethod(elicitInput) {
403
1711
  data: validatedData
404
1712
  };
405
1713
  } catch (error2) {
1714
+ const err = error2;
406
1715
  throw new ElicitationValidationError(
407
- `Elicitation data validation failed: ${error2.message}`,
408
- error2
1716
+ `Elicitation data validation failed: ${err.message}`,
1717
+ err
409
1718
  );
410
1719
  }
411
1720
  }
@@ -442,7 +1751,7 @@ function createLogMethod(sendNotification2, minLogLevel) {
442
1751
  if (!sendNotification2) {
443
1752
  return void 0;
444
1753
  }
445
- return async (level, message, logger) => {
1754
+ return async (level, message, logger2) => {
446
1755
  if (!shouldLogMessage(level, minLogLevel)) {
447
1756
  return;
448
1757
  }
@@ -451,12 +1760,78 @@ function createLogMethod(sendNotification2, minLogLevel) {
451
1760
  params: {
452
1761
  level,
453
1762
  data: message,
454
- logger: logger || "tool"
1763
+ logger: logger2 || "tool"
455
1764
  }
456
1765
  });
1766
+ Telemetry.getInstance().trackServerContext({
1767
+ contextType: "notification",
1768
+ notificationType: "message"
1769
+ }).catch(
1770
+ (e) => console.debug(`Failed to track notification context: ${e}`)
1771
+ );
1772
+ };
1773
+ }
1774
+ function createClientCapabilityChecker(clientCapabilities) {
1775
+ const caps = clientCapabilities || {};
1776
+ return {
1777
+ can(capability) {
1778
+ return capability in caps;
1779
+ },
1780
+ capabilities() {
1781
+ return { ...caps };
1782
+ }
1783
+ };
1784
+ }
1785
+ function createSendNotificationMethod(sessionId, sessions) {
1786
+ if (!sessionId || !sessions) {
1787
+ return void 0;
1788
+ }
1789
+ return async (method, params) => {
1790
+ const session = sessions.get(sessionId);
1791
+ if (!session?.sendNotification) {
1792
+ console.warn(
1793
+ `[MCP] Cannot send notification to session ${sessionId} - no sendNotification function`
1794
+ );
1795
+ return;
1796
+ }
1797
+ try {
1798
+ await session.sendNotification({
1799
+ method,
1800
+ params: params || {}
1801
+ });
1802
+ } catch (error2) {
1803
+ console.error(
1804
+ `[MCP] Error sending notification to session ${sessionId}:`,
1805
+ error2
1806
+ );
1807
+ }
457
1808
  };
458
1809
  }
459
- function createEnhancedContext(baseContext, createMessage, elicitInput, progressToken, sendNotification2, minLogLevel) {
1810
+ function createSendNotificationToSessionMethod(sessions) {
1811
+ if (!sessions) {
1812
+ return void 0;
1813
+ }
1814
+ return async (sessionId, method, params) => {
1815
+ const session = sessions.get(sessionId);
1816
+ if (!session?.sendNotification) {
1817
+ return false;
1818
+ }
1819
+ try {
1820
+ await session.sendNotification({
1821
+ method,
1822
+ params: params || {}
1823
+ });
1824
+ return true;
1825
+ } catch (error2) {
1826
+ console.error(
1827
+ `[MCP] Error sending notification to session ${sessionId}:`,
1828
+ error2
1829
+ );
1830
+ return false;
1831
+ }
1832
+ };
1833
+ }
1834
+ function createEnhancedContext(baseContext, createMessage, elicitInput, progressToken, sendNotification2, minLogLevel, clientCapabilities, sessionId, sessions) {
460
1835
  const enhancedContext = baseContext ? Object.create(baseContext) : {};
461
1836
  enhancedContext.sample = createSampleMethod(
462
1837
  createMessage,
@@ -469,15 +1844,33 @@ function createEnhancedContext(baseContext, createMessage, elicitInput, progress
469
1844
  sendNotification2
470
1845
  );
471
1846
  enhancedContext.log = createLogMethod(sendNotification2, minLogLevel);
1847
+ enhancedContext.client = createClientCapabilityChecker(clientCapabilities);
1848
+ if (sessionId) {
1849
+ enhancedContext.session = {
1850
+ sessionId
1851
+ };
1852
+ }
1853
+ const sendNotificationMethod = createSendNotificationMethod(
1854
+ sessionId,
1855
+ sessions
1856
+ );
1857
+ if (sendNotificationMethod) {
1858
+ enhancedContext.sendNotification = sendNotificationMethod;
1859
+ }
1860
+ const sendNotificationToSessionMethod = createSendNotificationToSessionMethod(sessions);
1861
+ if (sendNotificationToSessionMethod) {
1862
+ enhancedContext.sendNotificationToSession = sendNotificationToSessionMethod;
1863
+ }
472
1864
  return enhancedContext;
473
1865
  }
474
1866
  var import_zod_json_schema_compat, LOG_LEVELS, VALID_LOG_LEVELS;
475
1867
  var init_tool_execution_helpers = __esm({
476
1868
  "src/server/tools/tool-execution-helpers.ts"() {
477
1869
  "use strict";
478
- import_zod_json_schema_compat = require("@modelcontextprotocol/sdk/server/zod-json-schema-compat.js");
1870
+ import_zod_json_schema_compat = require("@mcp-use/modelcontextprotocol-sdk/server/zod-json-schema-compat.js");
479
1871
  init_errors();
480
1872
  init_runtime();
1873
+ init_telemetry2();
481
1874
  __name(findSessionContext, "findSessionContext");
482
1875
  __name(sendProgressNotification, "sendProgressNotification");
483
1876
  __name(withTimeout, "withTimeout");
@@ -508,6 +1901,9 @@ var init_tool_execution_helpers = __esm({
508
1901
  __name(isValidLogLevel, "isValidLogLevel");
509
1902
  __name(shouldLogMessage, "shouldLogMessage");
510
1903
  __name(createLogMethod, "createLogMethod");
1904
+ __name(createClientCapabilityChecker, "createClientCapabilityChecker");
1905
+ __name(createSendNotificationMethod, "createSendNotificationMethod");
1906
+ __name(createSendNotificationToSessionMethod, "createSendNotificationToSessionMethod");
511
1907
  __name(createEnhancedContext, "createEnhancedContext");
512
1908
  }
513
1909
  });
@@ -705,6 +2101,8 @@ var init_conversion2 = __esm({
705
2101
  // src/server/index.ts
706
2102
  var server_exports = {};
707
2103
  __export(server_exports, {
2104
+ MCPServer: () => MCPServer,
2105
+ VERSION: () => VERSION,
708
2106
  adaptConnectMiddleware: () => adaptConnectMiddleware,
709
2107
  adaptMiddleware: () => adaptMiddleware,
710
2108
  array: () => array,
@@ -719,6 +2117,7 @@ __export(server_exports, {
719
2117
  css: () => css,
720
2118
  error: () => error,
721
2119
  getAuth: () => getAuth,
2120
+ getPackageVersion: () => getPackageVersion,
722
2121
  getRequestContext: () => getRequestContext,
723
2122
  hasAnyScope: () => hasAnyScope,
724
2123
  hasRequestContext: () => hasRequestContext,
@@ -746,9 +2145,11 @@ __export(server_exports, {
746
2145
  module.exports = __toCommonJS(server_exports);
747
2146
 
748
2147
  // src/server/mcp-server.ts
749
- var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
750
- var import_types2 = require("@modelcontextprotocol/sdk/types.js");
2148
+ var import_mcp2 = require("@mcp-use/modelcontextprotocol-sdk/server/mcp.js");
2149
+ var import_types2 = require("@mcp-use/modelcontextprotocol-sdk/types.js");
751
2150
  var import_zod2 = require("zod");
2151
+ init_telemetry2();
2152
+ init_version();
752
2153
 
753
2154
  // src/server/widgets/index.ts
754
2155
  init_runtime();
@@ -1026,37 +2427,12 @@ function binary(base64Data, mimeType) {
1026
2427
  }
1027
2428
  __name(binary, "binary");
1028
2429
  function widget(config) {
1029
- const {
1030
- name,
1031
- data,
1032
- message,
1033
- invoking,
1034
- invoked,
1035
- widgetAccessible = true,
1036
- resultCanProduceWidget = true,
1037
- buildId
1038
- } = config;
1039
- const randomId = Math.random().toString(36).substring(2, 15);
1040
- const buildIdPart = buildId ? `-${buildId}` : "";
1041
- const uniqueUri = `ui://widget/${name}${buildIdPart}-${randomId}.html`;
1042
- const metadata = {
1043
- "openai/outputTemplate": uniqueUri,
1044
- "openai/widgetAccessible": widgetAccessible,
1045
- "openai/resultCanProduceWidget": resultCanProduceWidget
1046
- };
1047
- if (invoking) {
1048
- metadata["openai/toolInvocation/invoking"] = invoking;
1049
- }
1050
- if (invoked) {
1051
- metadata["openai/toolInvocation/invoked"] = invoked;
1052
- }
1053
- const displayMessage = message || `Displaying ${name}`;
2430
+ const { data, message } = config;
1054
2431
  return {
1055
- _meta: metadata,
1056
2432
  content: [
1057
2433
  {
1058
2434
  type: "text",
1059
- text: displayMessage
2435
+ text: message || ""
1060
2436
  }
1061
2437
  ],
1062
2438
  // structuredContent will be injected as window.openai.toolOutput by Apps SDK
@@ -1734,6 +3110,7 @@ function createWidgetRegistration(widgetName, metadata, html2, serverConfig, isD
1734
3110
  const props = metadata.inputs || {};
1735
3111
  const description = metadata.description || `Widget: ${widgetName}`;
1736
3112
  const title = metadata.title || widgetName;
3113
+ const exposeAsTool = metadata.exposeAsTool !== void 0 ? metadata.exposeAsTool : true;
1737
3114
  const mcp_connect_domain = serverConfig.serverBaseUrl ? new URL(serverConfig.serverBaseUrl || "").origin : null;
1738
3115
  return {
1739
3116
  name: widgetName,
@@ -1749,7 +3126,8 @@ function createWidgetRegistration(widgetName, metadata, html2, serverConfig, isD
1749
3126
  type: "appsSdk",
1750
3127
  props,
1751
3128
  html: html2,
1752
- dev: isDev
3129
+ dev: isDev,
3130
+ exposeAsTool
1753
3131
  },
1754
3132
  ...metadata._meta || {}
1755
3133
  },
@@ -2029,10 +3407,42 @@ if (container && Component) {
2029
3407
  console.log(`[WIDGETS] Watching resources directory: ${resourcesPath}`);
2030
3408
  }
2031
3409
  };
3410
+ const nodeStubsPlugin = {
3411
+ name: "node-stubs",
3412
+ enforce: "pre",
3413
+ resolveId(id) {
3414
+ if (id === "posthog-node" || id.startsWith("posthog-node/")) {
3415
+ return "\0virtual:posthog-node-stub";
3416
+ }
3417
+ return null;
3418
+ },
3419
+ load(id) {
3420
+ if (id === "\0virtual:posthog-node-stub") {
3421
+ return `
3422
+ export class PostHog {
3423
+ constructor() {}
3424
+ capture() {}
3425
+ identify() {}
3426
+ alias() {}
3427
+ flush() { return Promise.resolve(); }
3428
+ shutdown() { return Promise.resolve(); }
3429
+ }
3430
+ export default PostHog;
3431
+ `;
3432
+ }
3433
+ return null;
3434
+ }
3435
+ };
2032
3436
  const viteServer = await createServer({
2033
3437
  root: tempDir,
2034
3438
  base: baseRoute + "/",
2035
- plugins: [ssrCssPlugin, watchResourcesPlugin, tailwindcss(), react()],
3439
+ plugins: [
3440
+ nodeStubsPlugin,
3441
+ ssrCssPlugin,
3442
+ watchResourcesPlugin,
3443
+ tailwindcss(),
3444
+ react()
3445
+ ],
2036
3446
  resolve: {
2037
3447
  alias: {
2038
3448
  "@": pathHelpers.join(getCwd(), resourcesDir)
@@ -2053,12 +3463,15 @@ if (container && Component) {
2053
3463
  // Explicitly tell Vite to watch files outside root
2054
3464
  // This is needed because widget entry files import from resources directory
2055
3465
  optimizeDeps: {
2056
- // Don't optimize dependencies that might change
2057
- exclude: []
3466
+ // Exclude Node.js-only packages from browser bundling
3467
+ // posthog-node is for server-side telemetry and doesn't work in browser
3468
+ exclude: ["posthog-node"]
2058
3469
  },
2059
3470
  ssr: {
2060
3471
  // Force Vite to transform these packages in SSR instead of using external requires
2061
- noExternal: ["@openai/apps-sdk-ui", "react-router"]
3472
+ noExternal: ["@openai/apps-sdk-ui", "react-router"],
3473
+ // Mark Node.js-only packages as external in SSR mode
3474
+ external: ["posthog-node"]
2062
3475
  },
2063
3476
  define: {
2064
3477
  // Define process.env for SSR context
@@ -2317,25 +3730,31 @@ function setupWidgetRoutes(app, serverConfig) {
2317
3730
  __name(setupWidgetRoutes, "setupWidgetRoutes");
2318
3731
 
2319
3732
  // src/server/widgets/ui-resource-registration.ts
2320
- function uiResourceRegistration(definition) {
3733
+ function uiResourceRegistration(server, definition) {
2321
3734
  const displayName = definition.title || definition.name;
3735
+ if (definition.type === "appsSdk" && definition._meta) {
3736
+ server.widgetDefinitions.set(
3737
+ definition.name,
3738
+ definition._meta
3739
+ );
3740
+ }
2322
3741
  let resourceUri;
2323
3742
  let mimeType;
2324
3743
  switch (definition.type) {
2325
3744
  case "externalUrl":
2326
- resourceUri = generateWidgetUri(definition.widget, this.buildId);
3745
+ resourceUri = generateWidgetUri(definition.widget, server.buildId);
2327
3746
  mimeType = "text/uri-list";
2328
3747
  break;
2329
3748
  case "rawHtml":
2330
- resourceUri = generateWidgetUri(definition.name, this.buildId);
3749
+ resourceUri = generateWidgetUri(definition.name, server.buildId);
2331
3750
  mimeType = "text/html";
2332
3751
  break;
2333
3752
  case "remoteDom":
2334
- resourceUri = generateWidgetUri(definition.name, this.buildId);
3753
+ resourceUri = generateWidgetUri(definition.name, server.buildId);
2335
3754
  mimeType = "application/vnd.mcp-ui.remote-dom+javascript";
2336
3755
  break;
2337
3756
  case "appsSdk":
2338
- resourceUri = generateWidgetUri(definition.name, this.buildId, ".html");
3757
+ resourceUri = generateWidgetUri(definition.name, server.buildId, ".html");
2339
3758
  mimeType = "text/html+skybridge";
2340
3759
  break;
2341
3760
  default:
@@ -2344,12 +3763,12 @@ function uiResourceRegistration(definition) {
2344
3763
  );
2345
3764
  }
2346
3765
  const serverConfig = {
2347
- serverHost: this.serverHost,
2348
- serverPort: this.serverPort || 3e3,
2349
- serverBaseUrl: this.serverBaseUrl,
2350
- buildId: this.buildId
3766
+ serverHost: server.serverHost,
3767
+ serverPort: server.serverPort || 3e3,
3768
+ serverBaseUrl: server.serverBaseUrl,
3769
+ buildId: server.buildId
2351
3770
  };
2352
- this.resource({
3771
+ server.resource({
2353
3772
  name: definition.name,
2354
3773
  uri: resourceUri,
2355
3774
  title: definition.title,
@@ -2371,9 +3790,9 @@ function uiResourceRegistration(definition) {
2371
3790
  }, "readCallback")
2372
3791
  });
2373
3792
  if (definition.type === "appsSdk") {
2374
- const buildIdPart = this.buildId ? `-${this.buildId}` : "";
3793
+ const buildIdPart = server.buildId ? `-${server.buildId}` : "";
2375
3794
  const uriTemplate = `ui://widget/${definition.name}${buildIdPart}-{id}.html`;
2376
- this.resourceTemplate({
3795
+ server.resourceTemplate({
2377
3796
  name: `${definition.name}-dynamic`,
2378
3797
  resourceTemplate: {
2379
3798
  uriTemplate,
@@ -2398,70 +3817,77 @@ function uiResourceRegistration(definition) {
2398
3817
  }, "readCallback")
2399
3818
  });
2400
3819
  }
2401
- const toolMetadata = definition._meta || {};
2402
- if (definition.type === "appsSdk" && definition.appsSdkMetadata) {
2403
- toolMetadata["openai/outputTemplate"] = resourceUri;
2404
- const toolMetadataFields = [
2405
- "openai/toolInvocation/invoking",
2406
- "openai/toolInvocation/invoked",
2407
- "openai/widgetAccessible",
2408
- "openai/resultCanProduceWidget"
2409
- ];
2410
- for (const field of toolMetadataFields) {
2411
- if (definition.appsSdkMetadata[field] !== void 0) {
2412
- toolMetadata[field] = definition.appsSdkMetadata[field];
3820
+ const widgetMetadata = definition._meta?.["mcp-use/widget"];
3821
+ const exposeAsTool = definition.exposeAsTool ?? widgetMetadata?.exposeAsTool ?? true;
3822
+ if (exposeAsTool) {
3823
+ const toolMetadata = definition._meta || {};
3824
+ if (definition.type === "appsSdk" && definition.appsSdkMetadata) {
3825
+ toolMetadata["openai/outputTemplate"] = resourceUri;
3826
+ const toolMetadataFields = [
3827
+ "openai/toolInvocation/invoking",
3828
+ "openai/toolInvocation/invoked",
3829
+ "openai/widgetAccessible",
3830
+ "openai/resultCanProduceWidget"
3831
+ ];
3832
+ for (const field of toolMetadataFields) {
3833
+ if (definition.appsSdkMetadata[field] !== void 0) {
3834
+ toolMetadata[field] = definition.appsSdkMetadata[field];
3835
+ }
2413
3836
  }
2414
3837
  }
2415
- }
2416
- this.tool({
2417
- name: definition.name,
2418
- title: definition.title,
2419
- description: definition.description,
2420
- inputs: convertPropsToInputs(definition.props),
2421
- _meta: Object.keys(toolMetadata).length > 0 ? toolMetadata : void 0,
2422
- cb: /* @__PURE__ */ __name(async (params) => {
2423
- const uiResource = await createWidgetUIResource(
2424
- definition,
2425
- params,
2426
- serverConfig
2427
- );
2428
- if (definition.type === "appsSdk") {
2429
- const randomId = Math.random().toString(36).substring(2, 15);
2430
- const uniqueUri = generateWidgetUri(
2431
- definition.name,
2432
- this.buildId,
2433
- ".html",
2434
- randomId
3838
+ server.tool(
3839
+ {
3840
+ name: definition.name,
3841
+ title: definition.title,
3842
+ description: definition.description,
3843
+ inputs: convertPropsToInputs(definition.props),
3844
+ annotations: definition.toolAnnotations,
3845
+ _meta: Object.keys(toolMetadata).length > 0 ? toolMetadata : void 0
3846
+ },
3847
+ async (params) => {
3848
+ const uiResource = await createWidgetUIResource(
3849
+ definition,
3850
+ params,
3851
+ serverConfig
2435
3852
  );
2436
- const uniqueToolMetadata = {
2437
- ...toolMetadata,
2438
- "openai/outputTemplate": uniqueUri
2439
- };
3853
+ if (definition.type === "appsSdk") {
3854
+ const randomId = Math.random().toString(36).substring(2, 15);
3855
+ const uniqueUri = generateWidgetUri(
3856
+ definition.name,
3857
+ server.buildId,
3858
+ ".html",
3859
+ randomId
3860
+ );
3861
+ const uniqueToolMetadata = {
3862
+ ...toolMetadata,
3863
+ "openai/outputTemplate": uniqueUri
3864
+ };
3865
+ return {
3866
+ _meta: uniqueToolMetadata,
3867
+ content: [
3868
+ {
3869
+ type: "text",
3870
+ text: `Displaying ${displayName}`
3871
+ }
3872
+ ],
3873
+ // structuredContent will be injected as window.openai.toolOutput by Apps SDK
3874
+ structuredContent: params
3875
+ };
3876
+ }
2440
3877
  return {
2441
- _meta: uniqueToolMetadata,
2442
3878
  content: [
2443
3879
  {
2444
3880
  type: "text",
2445
- text: `Displaying ${displayName}`
2446
- }
2447
- ],
2448
- // structuredContent will be injected as window.openai.toolOutput by Apps SDK
2449
- structuredContent: params
3881
+ text: `Displaying ${displayName}`,
3882
+ description: `Show MCP-UI widget for ${displayName}`
3883
+ },
3884
+ uiResource
3885
+ ]
2450
3886
  };
2451
3887
  }
2452
- return {
2453
- content: [
2454
- {
2455
- type: "text",
2456
- text: `Displaying ${displayName}`,
2457
- description: `Show MCP-UI widget for ${displayName}`
2458
- },
2459
- uiResource
2460
- ]
2461
- };
2462
- }, "cb")
2463
- });
2464
- return this;
3888
+ );
3889
+ }
3890
+ return server;
2465
3891
  }
2466
3892
  __name(uiResourceRegistration, "uiResourceRegistration");
2467
3893
 
@@ -2599,7 +4025,7 @@ function toolRegistration(toolDefinition, callback) {
2599
4025
  const initialRequestContext = getRequestContext();
2600
4026
  const extraProgressToken = extra?._meta?.progressToken;
2601
4027
  const extraSendNotification = extra?.sendNotification;
2602
- const { requestContext, progressToken, sendNotification: sendNotification2 } = findSessionContext(
4028
+ const { requestContext, session, progressToken, sendNotification: sendNotification2 } = findSessionContext(
2603
4029
  this.sessions,
2604
4030
  initialRequestContext,
2605
4031
  extraProgressToken,
@@ -2610,7 +4036,9 @@ function toolRegistration(toolDefinition, callback) {
2610
4036
  this.createMessage.bind(this),
2611
4037
  this.server.server.elicitInput.bind(this.server.server),
2612
4038
  progressToken,
2613
- sendNotification2
4039
+ sendNotification2,
4040
+ session?.logLevel,
4041
+ session?.clientCapabilities
2614
4042
  );
2615
4043
  const executeCallback = /* @__PURE__ */ __name(async () => {
2616
4044
  if (actualCallback.length >= 2) {
@@ -2633,11 +4061,11 @@ __name(toolRegistration, "toolRegistration");
2633
4061
  init_tool_execution_helpers();
2634
4062
 
2635
4063
  // src/server/resources/index.ts
2636
- var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
4064
+ var import_mcp = require("@mcp-use/modelcontextprotocol-sdk/server/mcp.js");
2637
4065
  init_conversion();
2638
4066
 
2639
4067
  // src/server/resources/subscriptions.ts
2640
- var import_types = require("@modelcontextprotocol/sdk/types.js");
4068
+ var import_types = require("@mcp-use/modelcontextprotocol-sdk/types.js");
2641
4069
  init_context_storage();
2642
4070
  var ResourceSubscriptionManager = class {
2643
4071
  static {
@@ -2839,24 +4267,25 @@ function registerResourceTemplate(resourceTemplateDefinition, callback) {
2839
4267
  `Resource template '${resourceTemplateDefinition.name}' must have either a readCallback property or a callback parameter`
2840
4268
  );
2841
4269
  }
2842
- const template = new import_mcp.ResourceTemplate(
2843
- resourceTemplateDefinition.resourceTemplate.uriTemplate,
2844
- {
2845
- list: void 0,
2846
- // Optional: callback to list all matching resources
2847
- complete: void 0
2848
- // Optional: callback for auto-completion
2849
- }
2850
- );
4270
+ const isFlatStructure = "uriTemplate" in resourceTemplateDefinition;
4271
+ const uriTemplate = isFlatStructure ? resourceTemplateDefinition.uriTemplate : resourceTemplateDefinition.resourceTemplate.uriTemplate;
4272
+ const mimeType = isFlatStructure ? resourceTemplateDefinition.mimeType : resourceTemplateDefinition.resourceTemplate.mimeType;
4273
+ const templateDescription = isFlatStructure ? void 0 : resourceTemplateDefinition.resourceTemplate.description;
4274
+ const template = new import_mcp.ResourceTemplate(uriTemplate, {
4275
+ list: void 0,
4276
+ // Optional: callback to list all matching resources
4277
+ complete: void 0
4278
+ // Optional: callback for auto-completion
4279
+ });
2851
4280
  const metadata = {};
2852
4281
  if (resourceTemplateDefinition.title) {
2853
4282
  metadata.title = resourceTemplateDefinition.title;
2854
4283
  }
2855
- if (resourceTemplateDefinition.description || resourceTemplateDefinition.resourceTemplate.description) {
2856
- metadata.description = resourceTemplateDefinition.description || resourceTemplateDefinition.resourceTemplate.description;
4284
+ if (resourceTemplateDefinition.description || templateDescription) {
4285
+ metadata.description = resourceTemplateDefinition.description || templateDescription;
2857
4286
  }
2858
- if (resourceTemplateDefinition.resourceTemplate.mimeType) {
2859
- metadata.mimeType = resourceTemplateDefinition.resourceTemplate.mimeType;
4287
+ if (mimeType) {
4288
+ metadata.mimeType = mimeType;
2860
4289
  }
2861
4290
  if (resourceTemplateDefinition.annotations) {
2862
4291
  metadata.annotations = resourceTemplateDefinition.annotations;
@@ -2866,10 +4295,7 @@ function registerResourceTemplate(resourceTemplateDefinition, callback) {
2866
4295
  template,
2867
4296
  metadata,
2868
4297
  async (uri) => {
2869
- const params = this.parseTemplateUri(
2870
- resourceTemplateDefinition.resourceTemplate.uriTemplate,
2871
- uri.toString()
2872
- );
4298
+ const params = this.parseTemplateUri(uriTemplate, uri.toString());
2873
4299
  const { getRequestContext: getRequestContext2, runWithContext: runWithContext2 } = await Promise.resolve().then(() => (init_context_storage(), context_storage_exports));
2874
4300
  const { findSessionContext: findSessionContext2 } = await Promise.resolve().then(() => (init_tool_execution_helpers(), tool_execution_helpers_exports));
2875
4301
  const initialRequestContext = getRequestContext2();
@@ -2884,8 +4310,12 @@ function registerResourceTemplate(resourceTemplateDefinition, callback) {
2884
4310
  const executeCallback = /* @__PURE__ */ __name(async () => {
2885
4311
  if (actualCallback.length >= 3) {
2886
4312
  return await actualCallback(uri, params, enhancedContext);
4313
+ } else if (actualCallback.length === 2) {
4314
+ return await actualCallback(uri, params);
4315
+ } else if (actualCallback.length === 1) {
4316
+ return await actualCallback(uri);
2887
4317
  }
2888
- return await actualCallback(uri, params);
4318
+ return await actualCallback();
2889
4319
  }, "executeCallback");
2890
4320
  const result = requestContext ? await runWithContext2(requestContext, executeCallback) : await executeCallback();
2891
4321
  if ("contents" in result && Array.isArray(result.contents)) {
@@ -3229,8 +4659,9 @@ __name(startIdleCleanup, "startIdleCleanup");
3229
4659
 
3230
4660
  // src/server/endpoints/mount-mcp.ts
3231
4661
  init_runtime();
4662
+ init_telemetry2();
3232
4663
  async function mountMcp(app, mcpServerInstance, sessions, config, isProductionMode2) {
3233
- const { FetchStreamableHTTPServerTransport } = await import("@modelcontextprotocol/sdk/experimental/fetch-streamable-http/index.js");
4664
+ const { FetchStreamableHTTPServerTransport } = await import("@mcp-use/modelcontextprotocol-sdk/experimental/fetch-streamable-http/index.js");
3234
4665
  const idleTimeoutMs = config.sessionIdleTimeoutMs ?? 3e5;
3235
4666
  const transports = /* @__PURE__ */ new Map();
3236
4667
  let idleCleanupInterval;
@@ -3266,6 +4697,27 @@ async function mountMcp(app, mcpServerInstance, sessions, config, isProductionMo
3266
4697
  context: c,
3267
4698
  honoContext: c
3268
4699
  });
4700
+ server.server.oninitialized = () => {
4701
+ const clientCapabilities = server.server.getClientCapabilities();
4702
+ const clientInfo = server.server.getClientInfo?.() || {};
4703
+ const protocolVersion = server.server.getProtocolVersion?.() || "unknown";
4704
+ if (clientCapabilities && sessions.has(sid)) {
4705
+ const session = sessions.get(sid);
4706
+ session.clientCapabilities = clientCapabilities;
4707
+ console.log(
4708
+ `[MCP] Captured client capabilities for session ${sid}:`,
4709
+ Object.keys(clientCapabilities)
4710
+ );
4711
+ }
4712
+ Telemetry.getInstance().trackServerInitialize({
4713
+ protocolVersion: String(protocolVersion),
4714
+ clientInfo: clientInfo || {},
4715
+ clientCapabilities: clientCapabilities || {},
4716
+ sessionId: sid
4717
+ }).catch(
4718
+ (e) => console.debug(`Failed to track server initialize: ${e}`)
4719
+ );
4720
+ };
3269
4721
  }, "onsessioninitialized"),
3270
4722
  onsessionclosed: /* @__PURE__ */ __name((sid) => {
3271
4723
  console.log(`[MCP] Session closed: ${sid}`);
@@ -3509,12 +4961,13 @@ function createBearerAuthMiddleware(provider, baseUrl) {
3509
4961
  const result = await provider.verifyToken(token);
3510
4962
  const payload = result.payload;
3511
4963
  const user = provider.getUserInfo(payload);
4964
+ const scope = payload.scope;
3512
4965
  const authInfo = {
3513
4966
  user,
3514
4967
  payload,
3515
4968
  accessToken: token,
3516
4969
  // Extract scopes from scope claim (OAuth standard)
3517
- scopes: payload.scope ? payload.scope.split(" ") : [],
4970
+ scopes: scope ? scope.split(" ") : [],
3518
4971
  // Extract permissions (Auth0 style, or custom)
3519
4972
  permissions: payload.permissions || []
3520
4973
  };
@@ -3562,9 +5015,16 @@ async function setupOAuthForServer(app, oauthProvider, baseUrl, state) {
3562
5015
  __name(setupOAuthForServer, "setupOAuthForServer");
3563
5016
 
3564
5017
  // src/server/mcp-server.ts
3565
- var McpServer = class {
5018
+ var MCPServerClass = class {
3566
5019
  static {
3567
- __name(this, "McpServer");
5020
+ __name(this, "MCPServerClass");
5021
+ }
5022
+ /**
5023
+ * Get the mcp-use package version.
5024
+ * Works in all environments (Node.js, browser, Cloudflare Workers, Deno, etc.)
5025
+ */
5026
+ static getPackageVersion() {
5027
+ return getPackageVersion();
3568
5028
  }
3569
5029
  /**
3570
5030
  * Native MCP server instance from @modelcontextprotocol/sdk
@@ -3588,8 +5048,6 @@ var McpServer = class {
3588
5048
  buildId;
3589
5049
  sessions = /* @__PURE__ */ new Map();
3590
5050
  idleCleanupInterval;
3591
- oauthConfig;
3592
- // Store OAuth config for lazy initialization
3593
5051
  oauthSetupState = {
3594
5052
  complete: false,
3595
5053
  provider: void 0,
@@ -3598,15 +5056,21 @@ var McpServer = class {
3598
5056
  oauthProvider;
3599
5057
  oauthMiddleware;
3600
5058
  /**
3601
- * Storage for registration "recipes" that can be replayed on new server instances
5059
+ * Storage for registrations that can be replayed on new server instances
3602
5060
  * Following the official SDK pattern where each session gets its own server instance
5061
+ * @internal Exposed for telemetry purposes
3603
5062
  */
3604
- registrationRecipes = {
5063
+ registrations = {
3605
5064
  tools: /* @__PURE__ */ new Map(),
3606
5065
  prompts: /* @__PURE__ */ new Map(),
3607
5066
  resources: /* @__PURE__ */ new Map(),
3608
5067
  resourceTemplates: /* @__PURE__ */ new Map()
3609
5068
  };
5069
+ /**
5070
+ * Storage for widget definitions, used to inject metadata into tool responses
5071
+ * when using the widget() helper with returnsWidget option
5072
+ */
5073
+ widgetDefinitions = /* @__PURE__ */ new Map();
3610
5074
  /**
3611
5075
  * Resource subscription manager for tracking and notifying resource updates
3612
5076
  */
@@ -3631,7 +5095,7 @@ var McpServer = class {
3631
5095
  * access to Hono methods while preserving MCP server functionality.
3632
5096
  *
3633
5097
  * @param config - Server configuration including name, version, and description
3634
- * @returns A proxied McpServer instance that supports both MCP and Hono methods
5098
+ * @returns A proxied MCPServer instance that supports both MCP and Hono methods
3635
5099
  */
3636
5100
  constructor(config) {
3637
5101
  this.config = config;
@@ -3653,12 +5117,12 @@ var McpServer = class {
3653
5117
  }
3654
5118
  );
3655
5119
  this.app = createHonoApp(requestLogger);
3656
- this.oauthConfig = config.oauth;
5120
+ this.oauthProvider = config.oauth;
3657
5121
  this.wrapRegistrationMethods();
3658
5122
  return createHonoProxy(this, this.app);
3659
5123
  }
3660
5124
  /**
3661
- * Wrap registration methods to capture recipes following official SDK pattern.
5125
+ * Wrap registration methods to capture registrations following official SDK pattern.
3662
5126
  * Each session will get a fresh server instance with all registrations replayed.
3663
5127
  */
3664
5128
  wrapRegistrationMethods() {
@@ -3668,38 +5132,94 @@ var McpServer = class {
3668
5132
  const originalResourceTemplate = registerResourceTemplate;
3669
5133
  const self = this;
3670
5134
  this.tool = ((toolDefinition, callback) => {
3671
- const actualCallback = callback || toolDefinition.cb;
3672
- self.registrationRecipes.tools.set(toolDefinition.name, {
3673
- config: toolDefinition,
3674
- handler: actualCallback
3675
- });
3676
- return originalTool.call(self, toolDefinition, callback);
5135
+ const widgetConfig = toolDefinition.widget;
5136
+ const widgetName = widgetConfig?.name;
5137
+ if (widgetConfig && widgetName) {
5138
+ const buildIdPart = self.buildId ? `-${self.buildId}` : "";
5139
+ const outputTemplate = `ui://widget/${widgetName}${buildIdPart}.html`;
5140
+ toolDefinition._meta = {
5141
+ ...toolDefinition._meta,
5142
+ "openai/outputTemplate": outputTemplate,
5143
+ "openai/toolInvocation/invoking": widgetConfig.invoking ?? `Loading ${widgetName}...`,
5144
+ "openai/toolInvocation/invoked": widgetConfig.invoked ?? `${widgetName} ready`,
5145
+ "openai/widgetAccessible": widgetConfig.widgetAccessible ?? true,
5146
+ "openai/resultCanProduceWidget": widgetConfig.resultCanProduceWidget ?? true
5147
+ };
5148
+ }
5149
+ let actualCallback = callback || toolDefinition.cb;
5150
+ if (widgetConfig && widgetName && actualCallback) {
5151
+ const originalCallback = actualCallback;
5152
+ actualCallback = /* @__PURE__ */ __name((async (params, ctx) => {
5153
+ const result = await originalCallback(params, ctx);
5154
+ const widgetDef = self.widgetDefinitions.get(widgetName);
5155
+ if (result && typeof result === "object") {
5156
+ const randomId = Math.random().toString(36).substring(2, 15);
5157
+ const buildIdPart = self.buildId ? `-${self.buildId}` : "";
5158
+ const uniqueUri = `ui://widget/${widgetName}${buildIdPart}-${randomId}.html`;
5159
+ const responseMeta = {
5160
+ ...widgetDef || {},
5161
+ // Include mcp-use/widget and other widget metadata
5162
+ "openai/outputTemplate": uniqueUri,
5163
+ "openai/toolInvocation/invoking": widgetConfig.invoking ?? `Loading ${widgetName}...`,
5164
+ "openai/toolInvocation/invoked": widgetConfig.invoked ?? `${widgetName} ready`,
5165
+ "openai/widgetAccessible": widgetConfig.widgetAccessible ?? true,
5166
+ "openai/resultCanProduceWidget": widgetConfig.resultCanProduceWidget ?? true
5167
+ };
5168
+ result._meta = responseMeta;
5169
+ if (result.content?.[0]?.type === "text" && !result.content[0].text) {
5170
+ result.content[0].text = `Displaying ${widgetName}`;
5171
+ }
5172
+ }
5173
+ return result;
5174
+ }), "actualCallback");
5175
+ }
5176
+ if (actualCallback) {
5177
+ self.registrations.tools.set(toolDefinition.name, {
5178
+ config: toolDefinition,
5179
+ handler: actualCallback
5180
+ });
5181
+ }
5182
+ return originalTool.call(self, toolDefinition, actualCallback);
3677
5183
  });
3678
- this.prompt = function(promptDefinition, callback) {
5184
+ this.prompt = ((promptDefinition, callback) => {
3679
5185
  const actualCallback = callback || promptDefinition.cb;
3680
- self.registrationRecipes.prompts.set(promptDefinition.name, {
3681
- config: promptDefinition,
3682
- handler: actualCallback
3683
- });
3684
- return originalPrompt.call(self, promptDefinition, callback);
3685
- };
3686
- this.resource = function(resourceDefinition, callback) {
5186
+ if (actualCallback) {
5187
+ self.registrations.prompts.set(promptDefinition.name, {
5188
+ config: promptDefinition,
5189
+ handler: actualCallback
5190
+ });
5191
+ }
5192
+ return originalPrompt.call(
5193
+ self,
5194
+ promptDefinition,
5195
+ callback
5196
+ );
5197
+ });
5198
+ this.resource = ((resourceDefinition, callback) => {
3687
5199
  const actualCallback = callback || resourceDefinition.readCallback;
3688
- const resourceKey = `${resourceDefinition.name}:${resourceDefinition.uri}`;
3689
- self.registrationRecipes.resources.set(resourceKey, {
3690
- config: resourceDefinition,
3691
- handler: actualCallback
3692
- });
5200
+ if (actualCallback) {
5201
+ const resourceKey = `${resourceDefinition.name}:${resourceDefinition.uri}`;
5202
+ self.registrations.resources.set(resourceKey, {
5203
+ config: resourceDefinition,
5204
+ handler: actualCallback
5205
+ });
5206
+ }
3693
5207
  return originalResource.call(self, resourceDefinition, callback);
3694
- };
3695
- this.resourceTemplate = function(templateDefinition, callback) {
5208
+ });
5209
+ this.resourceTemplate = ((templateDefinition, callback) => {
3696
5210
  const actualCallback = callback || templateDefinition.readCallback;
3697
- self.registrationRecipes.resourceTemplates.set(templateDefinition.name, {
3698
- config: templateDefinition,
3699
- handler: actualCallback
3700
- });
3701
- return originalResourceTemplate.call(self, templateDefinition, callback);
3702
- };
5211
+ if (actualCallback) {
5212
+ self.registrations.resourceTemplates.set(templateDefinition.name, {
5213
+ config: templateDefinition,
5214
+ handler: actualCallback
5215
+ });
5216
+ }
5217
+ return originalResourceTemplate.call(
5218
+ self,
5219
+ templateDefinition,
5220
+ callback
5221
+ );
5222
+ });
3703
5223
  }
3704
5224
  /**
3705
5225
  * Create a new server instance for a session following official SDK pattern.
@@ -3717,8 +5237,8 @@ var McpServer = class {
3717
5237
  }
3718
5238
  }
3719
5239
  );
3720
- for (const [name, recipe] of this.registrationRecipes.tools) {
3721
- const { config, handler: actualCallback } = recipe;
5240
+ for (const [name, registration] of this.registrations.tools) {
5241
+ const { config, handler: actualCallback } = registration;
3722
5242
  let inputSchema;
3723
5243
  if (config.schema) {
3724
5244
  inputSchema = this.convertZodSchemaToParams(config.schema);
@@ -3737,6 +5257,15 @@ var McpServer = class {
3737
5257
  extraProgressToken,
3738
5258
  extraSendNotification
3739
5259
  );
5260
+ let sessionId;
5261
+ if (session) {
5262
+ for (const [id, s] of this.sessions.entries()) {
5263
+ if (s === session) {
5264
+ sessionId = id;
5265
+ break;
5266
+ }
5267
+ }
5268
+ }
3740
5269
  const createMessageWithLogging = /* @__PURE__ */ __name(async (params2, options) => {
3741
5270
  console.log("[createMessage] About to call server.createMessage");
3742
5271
  console.log("[createMessage] Has server:", !!newServer);
@@ -3748,11 +5277,12 @@ var McpServer = class {
3748
5277
  console.log("[createMessage] Got result successfully");
3749
5278
  return result;
3750
5279
  } catch (err) {
5280
+ const error2 = err;
3751
5281
  console.error(
3752
5282
  "[createMessage] Error:",
3753
- err.message,
5283
+ error2.message,
3754
5284
  "Code:",
3755
- err.code
5285
+ error2.code
3756
5286
  );
3757
5287
  throw err;
3758
5288
  }
@@ -3763,7 +5293,10 @@ var McpServer = class {
3763
5293
  newServer.server.elicitInput.bind(newServer.server),
3764
5294
  progressToken,
3765
5295
  sendNotification2,
3766
- session?.logLevel
5296
+ session?.logLevel,
5297
+ session?.clientCapabilities,
5298
+ sessionId,
5299
+ this.sessions
3767
5300
  );
3768
5301
  const executeCallback = /* @__PURE__ */ __name(async () => {
3769
5302
  if (actualCallback.length >= 2) {
@@ -3771,10 +5304,26 @@ var McpServer = class {
3771
5304
  }
3772
5305
  return await actualCallback(params);
3773
5306
  }, "executeCallback");
3774
- if (requestContext) {
3775
- return await runWithContext(requestContext, executeCallback);
5307
+ const startTime = Date.now();
5308
+ let success = true;
5309
+ let errorType = null;
5310
+ try {
5311
+ const result = requestContext ? await runWithContext(requestContext, executeCallback) : await executeCallback();
5312
+ return result;
5313
+ } catch (err) {
5314
+ success = false;
5315
+ errorType = err instanceof Error ? err.name : "unknown_error";
5316
+ throw err;
5317
+ } finally {
5318
+ const executionTimeMs = Date.now() - startTime;
5319
+ Telemetry.getInstance().trackServerToolCall({
5320
+ toolName: name,
5321
+ lengthInputArgument: JSON.stringify(params).length,
5322
+ success,
5323
+ errorType,
5324
+ executionTimeMs
5325
+ }).catch((e) => console.debug(`Failed to track tool call: ${e}`));
3776
5326
  }
3777
- return await executeCallback();
3778
5327
  }, "wrappedHandler");
3779
5328
  newServer.registerTool(
3780
5329
  name,
@@ -3788,8 +5337,8 @@ var McpServer = class {
3788
5337
  wrappedHandler
3789
5338
  );
3790
5339
  }
3791
- for (const [name, recipe] of this.registrationRecipes.prompts) {
3792
- const { config, handler } = recipe;
5340
+ for (const [name, registration] of this.registrations.prompts) {
5341
+ const { config, handler } = registration;
3793
5342
  let argsSchema;
3794
5343
  if (config.schema) {
3795
5344
  argsSchema = this.convertZodSchemaToParams(config.schema);
@@ -3798,13 +5347,28 @@ var McpServer = class {
3798
5347
  } else {
3799
5348
  argsSchema = void 0;
3800
5349
  }
3801
- const wrappedHandler = /* @__PURE__ */ __name(async (params) => {
3802
- const result = await handler(params);
3803
- if ("messages" in result && Array.isArray(result.messages)) {
3804
- return result;
5350
+ const wrappedHandler = /* @__PURE__ */ __name(async (params, extra) => {
5351
+ let success = true;
5352
+ let errorType = null;
5353
+ try {
5354
+ const result = await handler(params, extra);
5355
+ if ("messages" in result && Array.isArray(result.messages)) {
5356
+ return result;
5357
+ }
5358
+ const { convertToolResultToPromptResult: convertToolResultToPromptResult2 } = await Promise.resolve().then(() => (init_conversion2(), conversion_exports2));
5359
+ return convertToolResultToPromptResult2(result);
5360
+ } catch (err) {
5361
+ success = false;
5362
+ errorType = err instanceof Error ? err.name : "unknown_error";
5363
+ throw err;
5364
+ } finally {
5365
+ Telemetry.getInstance().trackServerPromptCall({
5366
+ name,
5367
+ description: config.description ?? null,
5368
+ success,
5369
+ errorType
5370
+ }).catch((e) => console.debug(`Failed to track prompt call: ${e}`));
3805
5371
  }
3806
- const { convertToolResultToPromptResult: convertToolResultToPromptResult2 } = await Promise.resolve().then(() => (init_conversion2(), conversion_exports2));
3807
- return convertToolResultToPromptResult2(result);
3808
5372
  }, "wrappedHandler");
3809
5373
  newServer.registerPrompt(
3810
5374
  name,
@@ -3816,15 +5380,42 @@ var McpServer = class {
3816
5380
  wrappedHandler
3817
5381
  );
3818
5382
  }
3819
- for (const [_key, recipe] of this.registrationRecipes.resources) {
3820
- const { config, handler } = recipe;
3821
- const wrappedHandler = /* @__PURE__ */ __name(async () => {
3822
- const result = await handler();
3823
- if ("contents" in result && Array.isArray(result.contents)) {
3824
- return result;
5383
+ for (const [_key, registration] of this.registrations.resources) {
5384
+ const { config, handler } = registration;
5385
+ const wrappedHandler = /* @__PURE__ */ __name(async (extra) => {
5386
+ let success = true;
5387
+ let errorType = null;
5388
+ let contents = [];
5389
+ try {
5390
+ const result = await handler(extra);
5391
+ if ("contents" in result && Array.isArray(result.contents)) {
5392
+ contents = result.contents;
5393
+ return result;
5394
+ }
5395
+ const { convertToolResultToResourceResult: convertToolResultToResourceResult2 } = await Promise.resolve().then(() => (init_conversion(), conversion_exports));
5396
+ const converted = convertToolResultToResourceResult2(
5397
+ config.uri,
5398
+ result
5399
+ );
5400
+ contents = converted.contents || [];
5401
+ return converted;
5402
+ } catch (err) {
5403
+ success = false;
5404
+ errorType = err instanceof Error ? err.name : "unknown_error";
5405
+ throw err;
5406
+ } finally {
5407
+ Telemetry.getInstance().trackServerResourceCall({
5408
+ name: config.name,
5409
+ description: config.description ?? null,
5410
+ contents: contents.map((c) => ({
5411
+ mime_type: c.mimeType ?? null,
5412
+ text: c.text ? `[text: ${c.text.length} chars]` : null,
5413
+ blob: c.blob ? `[blob: ${c.blob.length} bytes]` : null
5414
+ })),
5415
+ success,
5416
+ errorType
5417
+ }).catch((e) => console.debug(`Failed to track resource call: ${e}`));
3825
5418
  }
3826
- const { convertToolResultToResourceResult: convertToolResultToResourceResult2 } = await Promise.resolve().then(() => (init_conversion(), conversion_exports));
3827
- return convertToolResultToResourceResult2(config.uri, result);
3828
5419
  }, "wrappedHandler");
3829
5420
  newServer.registerResource(
3830
5421
  config.name,
@@ -3837,24 +5428,25 @@ var McpServer = class {
3837
5428
  wrappedHandler
3838
5429
  );
3839
5430
  }
3840
- for (const [_name, recipe] of this.registrationRecipes.resourceTemplates) {
3841
- const { config, handler } = recipe;
3842
- const template = new import_mcp2.ResourceTemplate(
3843
- config.resourceTemplate.uriTemplate,
3844
- {
3845
- list: void 0,
3846
- complete: void 0
3847
- }
3848
- );
5431
+ for (const [_name, registration] of this.registrations.resourceTemplates) {
5432
+ const { config, handler } = registration;
5433
+ const isFlatStructure = "uriTemplate" in config;
5434
+ const uriTemplate = isFlatStructure ? config.uriTemplate : config.resourceTemplate.uriTemplate;
5435
+ const mimeType = isFlatStructure ? config.mimeType : config.resourceTemplate.mimeType;
5436
+ const templateDescription = isFlatStructure ? void 0 : config.resourceTemplate.description;
5437
+ const template = new import_mcp2.ResourceTemplate(uriTemplate, {
5438
+ list: void 0,
5439
+ complete: void 0
5440
+ });
3849
5441
  const metadata = {};
3850
5442
  if (config.title) {
3851
5443
  metadata.title = config.title;
3852
5444
  }
3853
- if (config.description || config.resourceTemplate.description) {
3854
- metadata.description = config.description || config.resourceTemplate.description;
5445
+ if (config.description || templateDescription) {
5446
+ metadata.description = config.description || templateDescription;
3855
5447
  }
3856
- if (config.resourceTemplate.mimeType) {
3857
- metadata.mimeType = config.resourceTemplate.mimeType;
5448
+ if (mimeType) {
5449
+ metadata.mimeType = mimeType;
3858
5450
  }
3859
5451
  if (config.annotations) {
3860
5452
  metadata.annotations = config.annotations;
@@ -3863,23 +5455,49 @@ var McpServer = class {
3863
5455
  config.name,
3864
5456
  template,
3865
5457
  metadata,
3866
- async (uri) => {
3867
- const params = this.parseTemplateUri(
3868
- config.resourceTemplate.uriTemplate,
3869
- uri.toString()
3870
- );
3871
- const result = await handler(uri, params);
3872
- if ("contents" in result && Array.isArray(result.contents)) {
3873
- return result;
5458
+ async (uri, extra) => {
5459
+ let success = true;
5460
+ let errorType = null;
5461
+ let contents = [];
5462
+ try {
5463
+ const params = this.parseTemplateUri(uriTemplate, uri.toString());
5464
+ const result = await handler(uri, params, extra);
5465
+ if ("contents" in result && Array.isArray(result.contents)) {
5466
+ contents = result.contents;
5467
+ return result;
5468
+ }
5469
+ const { convertToolResultToResourceResult: convertToolResultToResourceResult2 } = await Promise.resolve().then(() => (init_conversion(), conversion_exports));
5470
+ const converted = convertToolResultToResourceResult2(
5471
+ uri.toString(),
5472
+ result
5473
+ );
5474
+ contents = converted.contents || [];
5475
+ return converted;
5476
+ } catch (err) {
5477
+ success = false;
5478
+ errorType = err instanceof Error ? err.name : "unknown_error";
5479
+ throw err;
5480
+ } finally {
5481
+ Telemetry.getInstance().trackServerResourceCall({
5482
+ name: config.name,
5483
+ description: config.description ?? null,
5484
+ contents: contents.map((c) => ({
5485
+ mimeType: c.mimeType ?? null,
5486
+ text: c.text ? `[text: ${c.text.length} chars]` : null,
5487
+ blob: c.blob ? `[blob: ${c.blob.length} bytes]` : null
5488
+ })),
5489
+ success,
5490
+ errorType
5491
+ }).catch(
5492
+ (e) => console.debug(`Failed to track resource template call: ${e}`)
5493
+ );
3874
5494
  }
3875
- const { convertToolResultToResourceResult: convertToolResultToResourceResult2 } = await Promise.resolve().then(() => (init_conversion(), conversion_exports));
3876
- return convertToolResultToResourceResult2(uri.toString(), result);
3877
5495
  }
3878
5496
  );
3879
5497
  }
3880
5498
  newServer.server.setRequestHandler(
3881
5499
  import_zod2.z.object({ method: import_zod2.z.literal("logging/setLevel") }).passthrough(),
3882
- async (request) => {
5500
+ (async (request, extra) => {
3883
5501
  const level = request.params?.level;
3884
5502
  if (!level) {
3885
5503
  throw new import_types2.McpError(
@@ -3918,7 +5536,7 @@ var McpServer = class {
3918
5536
  "[MCP] Could not find session for logging/setLevel request"
3919
5537
  );
3920
5538
  throw new import_types2.McpError(import_types2.ErrorCode.InternalError, "Could not find session");
3921
- }
5539
+ })
3922
5540
  );
3923
5541
  this.subscriptionManager.registerHandlers(newServer, this.sessions);
3924
5542
  return newServer;
@@ -3934,18 +5552,18 @@ var McpServer = class {
3934
5552
  this.serverPort
3935
5553
  );
3936
5554
  }
3937
- // Tool registration helper
3938
- tool = toolRegistration;
5555
+ // Tool registration helper - type is set in wrapRegistrationMethods
5556
+ tool;
3939
5557
  // Schema conversion helpers (used by tool registration)
3940
5558
  convertZodSchemaToParams = convertZodSchemaToParams;
3941
5559
  createParamsSchema = createParamsSchema;
3942
5560
  // Template URI parsing helper (used by resource templates)
3943
5561
  parseTemplateUri = parseTemplateUri;
3944
- // Resource registration helpers
3945
- resource = registerResource;
3946
- resourceTemplate = registerResourceTemplate;
3947
- // Prompt registration helper
3948
- prompt = registerPrompt;
5562
+ // Resource registration helpers - types are set in wrapRegistrationMethods
5563
+ resource;
5564
+ resourceTemplate;
5565
+ // Prompt registration helper - type is set in wrapRegistrationMethods
5566
+ prompt;
3949
5567
  // Notification helpers
3950
5568
  getActiveSessions = getActiveSessions;
3951
5569
  sendNotification = sendNotification;
@@ -3968,7 +5586,9 @@ var McpServer = class {
3968
5586
  async notifyResourceUpdated(uri) {
3969
5587
  return this.subscriptionManager.notifyResourceUpdated(uri, this.sessions);
3970
5588
  }
3971
- uiResource = uiResourceRegistration;
5589
+ uiResource = /* @__PURE__ */ __name((definition) => {
5590
+ return uiResourceRegistration(this, definition);
5591
+ }, "uiResource");
3972
5592
  /**
3973
5593
  * Mount MCP server endpoints at /mcp and /sse
3974
5594
  *
@@ -3993,7 +5613,7 @@ var McpServer = class {
3993
5613
  const result = await mountMcp(
3994
5614
  this.app,
3995
5615
  this,
3996
- // Pass the McpServer instance so mountMcp can call getServerForSession()
5616
+ // Pass the MCPServer instance so mountMcp can call getServerForSession()
3997
5617
  this.sessions,
3998
5618
  this.config,
3999
5619
  isProductionMode()
@@ -4056,7 +5676,7 @@ var McpServer = class {
4056
5676
  this.serverHost,
4057
5677
  this.serverPort
4058
5678
  );
4059
- if (this.oauthConfig && !this.oauthSetupState.complete) {
5679
+ if (this.oauthProvider && !this.oauthSetupState.complete) {
4060
5680
  await setupOAuthForServer(
4061
5681
  this.app,
4062
5682
  this.oauthProvider,
@@ -4071,10 +5691,14 @@ var McpServer = class {
4071
5691
  await this.mountMcp();
4072
5692
  await this.mountInspector();
4073
5693
  this.logRegisteredItems();
5694
+ this._trackServerRun("http");
4074
5695
  await startServer(this.app, this.serverPort, this.serverHost, {
4075
5696
  onDenoRequest: rewriteSupabaseRequest
4076
5697
  });
4077
5698
  }
5699
+ _trackServerRun(transport) {
5700
+ Telemetry.getInstance().trackServerRunFromServer(this, transport).catch((e) => console.debug(`Failed to track server run: ${e}`));
5701
+ }
4078
5702
  /**
4079
5703
  * Get the fetch handler for the server after mounting all endpoints
4080
5704
  *
@@ -4093,7 +5717,7 @@ var McpServer = class {
4093
5717
  * @example
4094
5718
  * ```typescript
4095
5719
  * // For Supabase Edge Functions (handles path rewriting automatically)
4096
- * const server = createMCPServer('my-server');
5720
+ * const server = new MCPServer({ name: 'my-server', version: '1.0.0' });
4097
5721
  * server.tool({ ... });
4098
5722
  * const handler = await server.getHandler({ provider: 'supabase' });
4099
5723
  * Deno.serve(handler);
@@ -4102,14 +5726,14 @@ var McpServer = class {
4102
5726
  * @example
4103
5727
  * ```typescript
4104
5728
  * // For Cloudflare Workers
4105
- * const server = createMCPServer('my-server');
5729
+ * const server = new MCPServer({ name: 'my-server', version: '1.0.0' });
4106
5730
  * server.tool({ ... });
4107
5731
  * const handler = await server.getHandler();
4108
5732
  * export default { fetch: handler };
4109
5733
  * ```
4110
5734
  */
4111
5735
  async getHandler(options) {
4112
- if (this.oauthConfig && !this.oauthSetupState.complete) {
5736
+ if (this.oauthProvider && !this.oauthSetupState.complete) {
4113
5737
  await setupOAuthForServer(
4114
5738
  this.app,
4115
5739
  this.oauthProvider,
@@ -4128,6 +5752,8 @@ var McpServer = class {
4128
5752
  console.log("[MCP] Mounting inspector");
4129
5753
  await this.mountInspector();
4130
5754
  console.log("[MCP] Mounted inspector");
5755
+ const provider = options?.provider || "fetch";
5756
+ this._trackServerRun(provider);
4131
5757
  const fetchHandler = this.app.fetch.bind(this.app);
4132
5758
  if (options?.provider === "supabase") {
4133
5759
  return async (req) => {
@@ -4179,8 +5805,9 @@ var McpServer = class {
4179
5805
  }
4180
5806
  }
4181
5807
  };
5808
+ var MCPServer = MCPServerClass;
4182
5809
  function createMCPServer(name, config = {}) {
4183
- const instance = new McpServer({
5810
+ const instance = new MCPServerClass({
4184
5811
  name,
4185
5812
  version: config.version || "1.0.0",
4186
5813
  description: config.description,
@@ -4196,6 +5823,7 @@ function createMCPServer(name, config = {}) {
4196
5823
  __name(createMCPServer, "createMCPServer");
4197
5824
 
4198
5825
  // src/server/index.ts
5826
+ init_version();
4199
5827
  init_context_storage();
4200
5828
 
4201
5829
  // src/server/oauth/providers/supabase.ts
@@ -4262,12 +5890,13 @@ var SupabaseOAuthProvider = class {
4262
5890
  }
4263
5891
  }
4264
5892
  getUserInfo(payload) {
5893
+ const userMetadata = payload.user_metadata;
4265
5894
  return {
4266
5895
  userId: payload.sub || payload.user_id,
4267
5896
  email: payload.email,
4268
- name: payload.user_metadata?.name || payload.user_metadata?.full_name,
4269
- username: payload.user_metadata?.username,
4270
- picture: payload.user_metadata?.avatar_url,
5897
+ name: userMetadata?.name || userMetadata?.full_name,
5898
+ username: userMetadata?.username,
5899
+ picture: userMetadata?.avatar_url,
4271
5900
  roles: payload.role ? [payload.role] : [],
4272
5901
  permissions: payload.aal ? [`aal:${payload.aal}`] : [],
4273
5902
  // Include Supabase-specific claims
@@ -4340,6 +5969,7 @@ var Auth0OAuthProvider = class {
4340
5969
  }
4341
5970
  }
4342
5971
  getUserInfo(payload) {
5972
+ const scope = payload.scope;
4343
5973
  return {
4344
5974
  userId: payload.sub,
4345
5975
  email: payload.email,
@@ -4352,7 +5982,7 @@ var Auth0OAuthProvider = class {
4352
5982
  // Auth0 can include roles (if configured)
4353
5983
  roles: payload.roles || payload["https://your-app.com/roles"] || [],
4354
5984
  // Include scope as well
4355
- scopes: payload.scope ? payload.scope.split(" ") : [],
5985
+ scopes: scope ? scope.split(" ") : [],
4356
5986
  // Additional Auth0-specific claims
4357
5987
  email_verified: payload.email_verified,
4358
5988
  updated_at: payload.updated_at
@@ -4424,8 +6054,10 @@ var KeycloakOAuthProvider = class {
4424
6054
  }
4425
6055
  }
4426
6056
  getUserInfo(payload) {
4427
- const realmRoles = payload.realm_access?.roles || [];
4428
- const clientRoles = this.config.clientId && payload.resource_access?.[this.config.clientId]?.roles || [];
6057
+ const realmAccess = payload.realm_access;
6058
+ const realmRoles = realmAccess?.roles || [];
6059
+ const resourceAccess = payload.resource_access;
6060
+ const clientRoles = this.config.clientId && (resourceAccess?.[this.config.clientId]?.roles || []) || [];
4429
6061
  const allRoles = [...realmRoles, ...clientRoles];
4430
6062
  const permissions = [];
4431
6063
  if (payload.resource_access) {
@@ -4439,6 +6071,7 @@ var KeycloakOAuthProvider = class {
4439
6071
  }
4440
6072
  );
4441
6073
  }
6074
+ const scope = payload.scope;
4442
6075
  return {
4443
6076
  userId: payload.sub,
4444
6077
  email: payload.email,
@@ -4449,7 +6082,7 @@ var KeycloakOAuthProvider = class {
4449
6082
  roles: allRoles,
4450
6083
  permissions,
4451
6084
  // Include scope as well
4452
- scopes: payload.scope ? payload.scope.split(" ") : [],
6085
+ scopes: scope ? scope.split(" ") : [],
4453
6086
  // Keycloak-specific claims
4454
6087
  email_verified: payload.email_verified,
4455
6088
  given_name: payload.given_name,
@@ -4578,7 +6211,7 @@ var CustomOAuthProvider = class {
4578
6211
  async verifyToken(token) {
4579
6212
  try {
4580
6213
  const result = await this.config.verifyToken(token);
4581
- return { payload: result };
6214
+ return result;
4582
6215
  } catch (error2) {
4583
6216
  throw new Error(`Custom OAuth verification failed: ${error2}`);
4584
6217
  }
@@ -4587,16 +6220,19 @@ var CustomOAuthProvider = class {
4587
6220
  if (this.config.getUserInfo) {
4588
6221
  return this.config.getUserInfo(payload);
4589
6222
  }
6223
+ const scope = payload.scope;
6224
+ const roles = payload.roles;
6225
+ const permissions = payload.permissions;
4590
6226
  return {
4591
6227
  userId: payload.sub || payload.user_id || payload.id,
4592
- email: payload.email,
4593
- name: payload.name,
4594
- username: payload.username || payload.preferred_username,
4595
- nickname: payload.nickname,
4596
- picture: payload.picture || payload.avatar_url,
4597
- roles: payload.roles || [],
4598
- permissions: payload.permissions || [],
4599
- scopes: payload.scope ? payload.scope.split(" ") : []
6228
+ email: payload.email ? payload.email : void 0,
6229
+ name: payload.name ? payload.name : void 0,
6230
+ username: payload.username || payload.preferred_username ? payload.username || payload.preferred_username : void 0,
6231
+ nickname: payload.nickname ? payload.nickname : void 0,
6232
+ picture: payload.picture || payload.avatar_url ? payload.picture || payload.avatar_url : void 0,
6233
+ roles: Array.isArray(roles) ? roles : [],
6234
+ permissions: Array.isArray(permissions) ? permissions : [],
6235
+ scopes: scope ? scope.split(" ") : []
4600
6236
  };
4601
6237
  }
4602
6238
  getIssuer() {