@machina.ai/cell-cli-core 1.0.13-rc9 → 1.0.17-rc1

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 (312) hide show
  1. package/dist/package.json +4 -3
  2. package/dist/src/code_assist/converter.d.ts +2 -1
  3. package/dist/src/code_assist/converter.js +2 -1
  4. package/dist/src/code_assist/converter.js.map +1 -1
  5. package/dist/src/code_assist/converter.test.js +13 -10
  6. package/dist/src/code_assist/converter.test.js.map +1 -1
  7. package/dist/src/code_assist/oauth2.js +8 -0
  8. package/dist/src/code_assist/oauth2.js.map +1 -1
  9. package/dist/src/code_assist/oauth2.test.js +97 -7
  10. package/dist/src/code_assist/oauth2.test.js.map +1 -1
  11. package/dist/src/code_assist/server.d.ts +2 -2
  12. package/dist/src/code_assist/server.js +4 -4
  13. package/dist/src/code_assist/server.js.map +1 -1
  14. package/dist/src/code_assist/server.test.js +9 -9
  15. package/dist/src/code_assist/server.test.js.map +1 -1
  16. package/dist/src/code_assist/setup.js +1 -1
  17. package/dist/src/code_assist/setup.js.map +1 -1
  18. package/dist/src/code_assist/setup.test.js +2 -2
  19. package/dist/src/code_assist/setup.test.js.map +1 -1
  20. package/dist/src/config/config.d.ts +37 -9
  21. package/dist/src/config/config.js +84 -29
  22. package/dist/src/config/config.js.map +1 -1
  23. package/dist/src/config/config.test.js +95 -24
  24. package/dist/src/config/config.test.js.map +1 -1
  25. package/dist/src/config/flashFallback.test.js +23 -47
  26. package/dist/src/config/flashFallback.test.js.map +1 -1
  27. package/dist/src/config/models.d.ts +1 -0
  28. package/dist/src/config/models.js +1 -0
  29. package/dist/src/config/models.js.map +1 -1
  30. package/dist/src/core/client.d.ts +4 -1
  31. package/dist/src/core/client.js +82 -22
  32. package/dist/src/core/client.js.map +1 -1
  33. package/dist/src/core/client.test.js +188 -38
  34. package/dist/src/core/client.test.js.map +1 -1
  35. package/dist/src/core/contentGenerator.d.ts +2 -2
  36. package/dist/src/core/contentGenerator.js.map +1 -1
  37. package/dist/src/core/coreToolScheduler.d.ts +1 -3
  38. package/dist/src/core/coreToolScheduler.js +25 -16
  39. package/dist/src/core/coreToolScheduler.js.map +1 -1
  40. package/dist/src/core/coreToolScheduler.test.js +76 -1
  41. package/dist/src/core/coreToolScheduler.test.js.map +1 -1
  42. package/dist/src/core/geminiChat.d.ts +2 -1
  43. package/dist/src/core/geminiChat.js +9 -11
  44. package/dist/src/core/geminiChat.js.map +1 -1
  45. package/dist/src/core/geminiChat.test.js +2 -2
  46. package/dist/src/core/geminiChat.test.js.map +1 -1
  47. package/dist/src/core/geminiRequest.js +2 -37
  48. package/dist/src/core/geminiRequest.js.map +1 -1
  49. package/dist/src/core/logger.d.ts +1 -0
  50. package/dist/src/core/logger.js +24 -4
  51. package/dist/src/core/logger.js.map +1 -1
  52. package/dist/src/core/logger.test.js +60 -9
  53. package/dist/src/core/logger.test.js.map +1 -1
  54. package/dist/src/core/nonInteractiveToolExecutor.js +11 -3
  55. package/dist/src/core/nonInteractiveToolExecutor.js.map +1 -1
  56. package/dist/src/core/prompts.js +41 -17
  57. package/dist/src/core/prompts.js.map +1 -1
  58. package/dist/src/core/prompts.test.js +118 -1
  59. package/dist/src/core/prompts.test.js.map +1 -1
  60. package/dist/src/core/tokenLimits.js +1 -0
  61. package/dist/src/core/tokenLimits.js.map +1 -1
  62. package/dist/src/core/turn.d.ts +3 -0
  63. package/dist/src/core/turn.js +3 -0
  64. package/dist/src/core/turn.js.map +1 -1
  65. package/dist/src/ide/detect-ide.d.ts +10 -0
  66. package/dist/src/ide/detect-ide.js +27 -0
  67. package/dist/src/ide/detect-ide.js.map +1 -0
  68. package/dist/src/ide/ide-client.d.ts +40 -0
  69. package/dist/src/ide/ide-client.js +152 -0
  70. package/dist/src/ide/ide-client.js.map +1 -0
  71. package/dist/src/ide/ide-installer.d.ts +14 -0
  72. package/dist/src/ide/ide-installer.js +109 -0
  73. package/dist/src/ide/ide-installer.js.map +1 -0
  74. package/dist/src/ide/ide-installer.test.js +55 -0
  75. package/dist/src/ide/ide-installer.test.js.map +1 -0
  76. package/dist/src/ide/ideContext.d.ts +279 -0
  77. package/dist/src/ide/ideContext.js +102 -0
  78. package/dist/src/ide/ideContext.js.map +1 -0
  79. package/dist/src/ide/ideContext.test.js +265 -0
  80. package/dist/src/ide/ideContext.test.js.map +1 -0
  81. package/dist/src/index.d.ts +11 -1
  82. package/dist/src/index.js +14 -1
  83. package/dist/src/index.js.map +1 -1
  84. package/dist/src/mcp/google-auth-provider.d.ts +23 -0
  85. package/dist/src/mcp/google-auth-provider.js +63 -0
  86. package/dist/src/mcp/google-auth-provider.js.map +1 -0
  87. package/dist/src/mcp/google-auth-provider.test.d.ts +6 -0
  88. package/dist/src/mcp/google-auth-provider.test.js +54 -0
  89. package/dist/src/mcp/google-auth-provider.test.js.map +1 -0
  90. package/dist/src/mcp/oauth-provider.d.ts +5 -1
  91. package/dist/src/mcp/oauth-provider.js +44 -15
  92. package/dist/src/mcp/oauth-provider.js.map +1 -1
  93. package/dist/src/mcp/oauth-provider.test.js +94 -14
  94. package/dist/src/mcp/oauth-provider.test.js.map +1 -1
  95. package/dist/src/mcp/oauth-token-storage.d.ts +3 -1
  96. package/dist/src/mcp/oauth-token-storage.js +3 -1
  97. package/dist/src/mcp/oauth-token-storage.js.map +1 -1
  98. package/dist/src/mcp/oauth-utils.js +2 -2
  99. package/dist/src/mcp/oauth-utils.js.map +1 -1
  100. package/dist/src/mcp/oauth-utils.test.js +1 -1
  101. package/dist/src/mcp/oauth-utils.test.js.map +1 -1
  102. package/dist/src/prompts/mcp-prompts.d.ts +8 -0
  103. package/dist/src/prompts/mcp-prompts.js +13 -0
  104. package/dist/src/prompts/mcp-prompts.js.map +1 -0
  105. package/dist/src/prompts/prompt-registry.d.ts +26 -0
  106. package/dist/src/prompts/prompt-registry.js +47 -0
  107. package/dist/src/prompts/prompt-registry.js.map +1 -0
  108. package/dist/src/services/fileDiscoveryService.test.js +101 -60
  109. package/dist/src/services/fileDiscoveryService.test.js.map +1 -1
  110. package/dist/src/services/gitService.test.js +67 -86
  111. package/dist/src/services/gitService.test.js.map +1 -1
  112. package/dist/src/services/loopDetectionService.d.ts +51 -5
  113. package/dist/src/services/loopDetectionService.js +140 -36
  114. package/dist/src/services/loopDetectionService.js.map +1 -1
  115. package/dist/src/services/loopDetectionService.test.js +105 -99
  116. package/dist/src/services/loopDetectionService.test.js.map +1 -1
  117. package/dist/src/services/shellExecutionService.d.ts +70 -0
  118. package/dist/src/services/shellExecutionService.js +155 -0
  119. package/dist/src/services/shellExecutionService.js.map +1 -0
  120. package/dist/src/services/shellExecutionService.test.d.ts +6 -0
  121. package/dist/src/services/shellExecutionService.test.js +264 -0
  122. package/dist/src/services/shellExecutionService.test.js.map +1 -0
  123. package/dist/src/telemetry/clearcut-logger/clearcut-logger.d.ts +4 -1
  124. package/dist/src/telemetry/clearcut-logger/clearcut-logger.js +97 -34
  125. package/dist/src/telemetry/clearcut-logger/clearcut-logger.js.map +1 -1
  126. package/dist/src/telemetry/clearcut-logger/event-metadata-key.d.ts +6 -1
  127. package/dist/src/telemetry/clearcut-logger/event-metadata-key.js +19 -0
  128. package/dist/src/telemetry/clearcut-logger/event-metadata-key.js.map +1 -1
  129. package/dist/src/telemetry/constants.d.ts +2 -0
  130. package/dist/src/telemetry/constants.js +2 -0
  131. package/dist/src/telemetry/constants.js.map +1 -1
  132. package/dist/src/telemetry/file-exporters.d.ts +28 -0
  133. package/dist/src/telemetry/file-exporters.js +62 -0
  134. package/dist/src/telemetry/file-exporters.js.map +1 -0
  135. package/dist/src/telemetry/index.d.ts +2 -2
  136. package/dist/src/telemetry/index.js +2 -2
  137. package/dist/src/telemetry/index.js.map +1 -1
  138. package/dist/src/telemetry/loggers.d.ts +3 -1
  139. package/dist/src/telemetry/loggers.js +33 -1
  140. package/dist/src/telemetry/loggers.js.map +1 -1
  141. package/dist/src/telemetry/loggers.test.circular.js +2 -0
  142. package/dist/src/telemetry/loggers.test.circular.js.map +1 -1
  143. package/dist/src/telemetry/loggers.test.js +8 -3
  144. package/dist/src/telemetry/loggers.test.js.map +1 -1
  145. package/dist/src/telemetry/sdk.js +17 -6
  146. package/dist/src/telemetry/sdk.js.map +1 -1
  147. package/dist/src/telemetry/telemetry.test.js +2 -0
  148. package/dist/src/telemetry/telemetry.test.js.map +1 -1
  149. package/dist/src/telemetry/types.d.ts +24 -2
  150. package/dist/src/telemetry/types.js +40 -2
  151. package/dist/src/telemetry/types.js.map +1 -1
  152. package/dist/src/telemetry/uiTelemetry.test.js +3 -0
  153. package/dist/src/telemetry/uiTelemetry.test.js.map +1 -1
  154. package/dist/src/test-utils/mockWorkspaceContext.d.ts +13 -0
  155. package/dist/src/test-utils/mockWorkspaceContext.js +24 -0
  156. package/dist/src/test-utils/mockWorkspaceContext.js.map +1 -0
  157. package/dist/src/tools/edit.js +27 -3
  158. package/dist/src/tools/edit.js.map +1 -1
  159. package/dist/src/tools/edit.test.js +104 -1
  160. package/dist/src/tools/edit.test.js.map +1 -1
  161. package/dist/src/tools/glob.js +53 -17
  162. package/dist/src/tools/glob.js.map +1 -1
  163. package/dist/src/tools/glob.test.js +32 -6
  164. package/dist/src/tools/glob.test.js.map +1 -1
  165. package/dist/src/tools/grep.d.ts +1 -1
  166. package/dist/src/tools/grep.js +81 -29
  167. package/dist/src/tools/grep.js.map +1 -1
  168. package/dist/src/tools/grep.test.js +76 -9
  169. package/dist/src/tools/grep.test.js.map +1 -1
  170. package/dist/src/tools/ls.js +4 -3
  171. package/dist/src/tools/ls.js.map +1 -1
  172. package/dist/src/tools/ls.test.d.ts +6 -0
  173. package/dist/src/tools/ls.test.js +356 -0
  174. package/dist/src/tools/ls.test.js.map +1 -0
  175. package/dist/src/tools/mcp-client.d.ts +31 -3
  176. package/dist/src/tools/mcp-client.js +503 -57
  177. package/dist/src/tools/mcp-client.js.map +1 -1
  178. package/dist/src/tools/mcp-client.test.js +133 -7
  179. package/dist/src/tools/mcp-client.test.js.map +1 -1
  180. package/dist/src/tools/mcp-tool.js +104 -45
  181. package/dist/src/tools/mcp-tool.js.map +1 -1
  182. package/dist/src/tools/mcp-tool.test.js +314 -2
  183. package/dist/src/tools/mcp-tool.test.js.map +1 -1
  184. package/dist/src/tools/memoryTool.d.ts +17 -2
  185. package/dist/src/tools/memoryTool.js +130 -13
  186. package/dist/src/tools/memoryTool.js.map +1 -1
  187. package/dist/src/tools/memoryTool.test.js +88 -3
  188. package/dist/src/tools/memoryTool.test.js.map +1 -1
  189. package/dist/src/tools/modifiable-tool.test.js +51 -62
  190. package/dist/src/tools/modifiable-tool.test.js.map +1 -1
  191. package/dist/src/tools/read-file.js +8 -6
  192. package/dist/src/tools/read-file.js.map +1 -1
  193. package/dist/src/tools/read-file.test.js +125 -68
  194. package/dist/src/tools/read-file.test.js.map +1 -1
  195. package/dist/src/tools/read-many-files.d.ts +0 -1
  196. package/dist/src/tools/read-many-files.js +29 -20
  197. package/dist/src/tools/read-many-files.js.map +1 -1
  198. package/dist/src/tools/read-many-files.test.js +35 -2
  199. package/dist/src/tools/read-many-files.test.js.map +1 -1
  200. package/dist/src/tools/shell.d.ts +3 -23
  201. package/dist/src/tools/shell.js +173 -300
  202. package/dist/src/tools/shell.js.map +1 -1
  203. package/dist/src/tools/shell.test.js +278 -384
  204. package/dist/src/tools/shell.test.js.map +1 -1
  205. package/dist/src/tools/tool-error.d.ts +22 -0
  206. package/dist/src/tools/tool-error.js +27 -0
  207. package/dist/src/tools/tool-error.js.map +1 -0
  208. package/dist/src/tools/tool-registry.d.ts +13 -1
  209. package/dist/src/tools/tool-registry.js +46 -2
  210. package/dist/src/tools/tool-registry.js.map +1 -1
  211. package/dist/src/tools/tool-registry.test.js +13 -5
  212. package/dist/src/tools/tool-registry.test.js.map +1 -1
  213. package/dist/src/tools/tools.d.ts +8 -0
  214. package/dist/src/tools/tools.js.map +1 -1
  215. package/dist/src/tools/write-file.js +7 -5
  216. package/dist/src/tools/write-file.js.map +1 -1
  217. package/dist/src/tools/write-file.test.js +56 -2
  218. package/dist/src/tools/write-file.test.js.map +1 -1
  219. package/dist/src/utils/bfsFileSearch.js +51 -27
  220. package/dist/src/utils/bfsFileSearch.js.map +1 -1
  221. package/dist/src/utils/bfsFileSearch.test.js +163 -134
  222. package/dist/src/utils/bfsFileSearch.test.js.map +1 -1
  223. package/dist/src/utils/editCorrector.js +2 -2
  224. package/dist/src/utils/editCorrector.js.map +1 -1
  225. package/dist/src/utils/editor.d.ts +1 -1
  226. package/dist/src/utils/editor.js +9 -0
  227. package/dist/src/utils/editor.js.map +1 -1
  228. package/dist/src/utils/editor.test.js +21 -1
  229. package/dist/src/utils/editor.test.js.map +1 -1
  230. package/dist/src/utils/errorReporting.d.ts +1 -1
  231. package/dist/src/utils/errorReporting.js +2 -2
  232. package/dist/src/utils/errorReporting.js.map +1 -1
  233. package/dist/src/utils/errorReporting.test.js +44 -38
  234. package/dist/src/utils/errorReporting.test.js.map +1 -1
  235. package/dist/src/utils/fileUtils.js +13 -2
  236. package/dist/src/utils/fileUtils.js.map +1 -1
  237. package/dist/src/utils/fileUtils.test.js +42 -1
  238. package/dist/src/utils/fileUtils.test.js.map +1 -1
  239. package/dist/src/utils/flashFallback.integration.test.js +8 -0
  240. package/dist/src/utils/flashFallback.integration.test.js.map +1 -1
  241. package/dist/src/utils/formatters.d.ts +6 -0
  242. package/dist/src/utils/formatters.js +16 -0
  243. package/dist/src/utils/formatters.js.map +1 -0
  244. package/dist/src/utils/getFolderStructure.test.js +11 -13
  245. package/dist/src/utils/getFolderStructure.test.js.map +1 -1
  246. package/dist/src/utils/gitIgnoreParser.js +5 -11
  247. package/dist/src/utils/gitIgnoreParser.js.map +1 -1
  248. package/dist/src/utils/gitIgnoreParser.test.js +58 -61
  249. package/dist/src/utils/gitIgnoreParser.test.js.map +1 -1
  250. package/dist/src/utils/memoryDiscovery.d.ts +1 -1
  251. package/dist/src/utils/memoryDiscovery.js +69 -79
  252. package/dist/src/utils/memoryDiscovery.js.map +1 -1
  253. package/dist/src/utils/memoryDiscovery.test.js +119 -370
  254. package/dist/src/utils/memoryDiscovery.test.js.map +1 -1
  255. package/dist/src/utils/memoryImportProcessor.d.ts +19 -12
  256. package/dist/src/utils/memoryImportProcessor.js +241 -82
  257. package/dist/src/utils/memoryImportProcessor.js.map +1 -1
  258. package/dist/src/utils/memoryImportProcessor.test.js +595 -50
  259. package/dist/src/utils/memoryImportProcessor.test.js.map +1 -1
  260. package/dist/src/utils/nextSpeakerChecker.js +3 -23
  261. package/dist/src/utils/nextSpeakerChecker.js.map +1 -1
  262. package/dist/src/utils/nextSpeakerChecker.test.js +2 -2
  263. package/dist/src/utils/nextSpeakerChecker.test.js.map +1 -1
  264. package/dist/src/utils/partUtils.d.ts +14 -0
  265. package/dist/src/utils/partUtils.js +65 -0
  266. package/dist/src/utils/partUtils.js.map +1 -0
  267. package/dist/src/utils/partUtils.test.d.ts +6 -0
  268. package/dist/src/utils/partUtils.test.js +130 -0
  269. package/dist/src/utils/partUtils.test.js.map +1 -0
  270. package/dist/src/utils/paths.d.ts +11 -2
  271. package/dist/src/utils/paths.js +24 -7
  272. package/dist/src/utils/paths.js.map +1 -1
  273. package/dist/src/utils/paths.test.d.ts +6 -0
  274. package/dist/src/utils/paths.test.js +153 -0
  275. package/dist/src/utils/paths.test.js.map +1 -0
  276. package/dist/src/utils/retry.d.ts +3 -0
  277. package/dist/src/utils/retry.js.map +1 -1
  278. package/dist/src/utils/retry.test.js.map +1 -1
  279. package/dist/src/utils/secure-browser-launcher.d.ts +23 -0
  280. package/dist/src/utils/secure-browser-launcher.js +164 -0
  281. package/dist/src/utils/secure-browser-launcher.js.map +1 -0
  282. package/dist/src/utils/secure-browser-launcher.test.d.ts +6 -0
  283. package/dist/src/utils/secure-browser-launcher.test.js +149 -0
  284. package/dist/src/utils/secure-browser-launcher.test.js.map +1 -0
  285. package/dist/src/utils/shell-utils.d.ts +78 -0
  286. package/dist/src/utils/shell-utils.js +306 -0
  287. package/dist/src/utils/shell-utils.js.map +1 -0
  288. package/dist/src/utils/shell-utils.test.d.ts +6 -0
  289. package/dist/src/utils/shell-utils.test.js +200 -0
  290. package/dist/src/utils/shell-utils.test.js.map +1 -0
  291. package/dist/src/utils/summarizer.js +3 -32
  292. package/dist/src/utils/summarizer.js.map +1 -1
  293. package/dist/src/utils/textUtils.d.ts +13 -0
  294. package/dist/src/utils/textUtils.js +28 -0
  295. package/dist/src/utils/textUtils.js.map +1 -0
  296. package/dist/src/utils/workspaceContext.d.ts +51 -0
  297. package/dist/src/utils/workspaceContext.js +139 -0
  298. package/dist/src/utils/workspaceContext.js.map +1 -0
  299. package/dist/src/utils/workspaceContext.test.d.ts +6 -0
  300. package/dist/src/utils/workspaceContext.test.js +209 -0
  301. package/dist/src/utils/workspaceContext.test.js.map +1 -0
  302. package/dist/tsconfig.tsbuildinfo +1 -1
  303. package/package.json +4 -3
  304. package/dist/src/core/geminiRequest.test.js +0 -72
  305. package/dist/src/core/geminiRequest.test.js.map +0 -1
  306. package/dist/src/services/ideContext.d.ts +0 -178
  307. package/dist/src/services/ideContext.js +0 -105
  308. package/dist/src/services/ideContext.js.map +0 -1
  309. package/dist/src/services/ideContext.test.js +0 -111
  310. package/dist/src/services/ideContext.test.js.map +0 -1
  311. /package/dist/src/{core/geminiRequest.test.d.ts → ide/ide-installer.test.d.ts} +0 -0
  312. /package/dist/src/{services → ide}/ideContext.test.d.ts +0 -0
@@ -7,10 +7,15 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
7
7
  import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
8
8
  import { SSEClientTransport, } from '@modelcontextprotocol/sdk/client/sse.js';
9
9
  import { StreamableHTTPClientTransport, } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
10
+ import { ListPromptsResultSchema, GetPromptResultSchema, } from '@modelcontextprotocol/sdk/types.js';
10
11
  import { parse } from 'shell-quote';
12
+ import { AuthProviderType } from '../config/config.js';
13
+ import { GoogleCredentialProvider } from '../mcp/google-auth-provider.js';
11
14
  import { DiscoveredMCPTool } from './mcp-tool.js';
12
15
  import { mcpToTool } from '@google/genai';
13
- import { OpenFilesNotificationSchema, IDE_SERVER_NAME, ideContext, } from '../services/ideContext.js';
16
+ import { MCPOAuthProvider } from '../mcp/oauth-provider.js';
17
+ import { OAuthUtils } from '../mcp/oauth-utils.js';
18
+ import { MCPOAuthTokenStorage } from '../mcp/oauth-token-storage.js';
14
19
  import { getErrorMessage } from '../utils/errors.js';
15
20
  export const MCP_DEFAULT_TIMEOUT_MSEC = 10 * 60 * 1000; // default to 10 minutes
16
21
  /**
@@ -40,11 +45,15 @@ export var MCPDiscoveryState;
40
45
  /**
41
46
  * Map to track the status of each MCP server within the core package
42
47
  */
43
- const mcpServerStatusesInternal = new Map();
48
+ const serverStatuses = new Map();
44
49
  /**
45
50
  * Track the overall MCP discovery state
46
51
  */
47
52
  let mcpDiscoveryState = MCPDiscoveryState.NOT_STARTED;
53
+ /**
54
+ * Map to track which MCP servers have been discovered to require OAuth
55
+ */
56
+ export const mcpServerRequiresOAuth = new Map();
48
57
  const statusChangeListeners = [];
49
58
  /**
50
59
  * Add a listener for MCP server status changes
@@ -65,7 +74,7 @@ export function removeMCPStatusChangeListener(listener) {
65
74
  * Update the status of an MCP server
66
75
  */
67
76
  function updateMCPServerStatus(serverName, status) {
68
- mcpServerStatusesInternal.set(serverName, status);
77
+ serverStatuses.set(serverName, status);
69
78
  // Notify all listeners
70
79
  for (const listener of statusChangeListeners) {
71
80
  listener(serverName, status);
@@ -75,13 +84,13 @@ function updateMCPServerStatus(serverName, status) {
75
84
  * Get the current status of an MCP server
76
85
  */
77
86
  export function getMCPServerStatus(serverName) {
78
- return (mcpServerStatusesInternal.get(serverName) || MCPServerStatus.DISCONNECTED);
87
+ return serverStatuses.get(serverName) || MCPServerStatus.DISCONNECTED;
79
88
  }
80
89
  /**
81
90
  * Get all MCP server statuses
82
91
  */
83
92
  export function getAllMCPServerStatuses() {
84
- return new Map(mcpServerStatusesInternal);
93
+ return new Map(serverStatuses);
85
94
  }
86
95
  /**
87
96
  * Get the current MCP discovery state
@@ -89,6 +98,121 @@ export function getAllMCPServerStatuses() {
89
98
  export function getMCPDiscoveryState() {
90
99
  return mcpDiscoveryState;
91
100
  }
101
+ /**
102
+ * Extract WWW-Authenticate header from error message string.
103
+ * This is a more robust approach than regex matching.
104
+ *
105
+ * @param errorString The error message string
106
+ * @returns The www-authenticate header value if found, null otherwise
107
+ */
108
+ function extractWWWAuthenticateHeader(errorString) {
109
+ // Try multiple patterns to extract the header
110
+ const patterns = [
111
+ /www-authenticate:\s*([^\n\r]+)/i,
112
+ /WWW-Authenticate:\s*([^\n\r]+)/i,
113
+ /"www-authenticate":\s*"([^"]+)"/i,
114
+ /'www-authenticate':\s*'([^']+)'/i,
115
+ ];
116
+ for (const pattern of patterns) {
117
+ const match = errorString.match(pattern);
118
+ if (match) {
119
+ return match[1].trim();
120
+ }
121
+ }
122
+ return null;
123
+ }
124
+ /**
125
+ * Handle automatic OAuth discovery and authentication for a server.
126
+ *
127
+ * @param mcpServerName The name of the MCP server
128
+ * @param mcpServerConfig The MCP server configuration
129
+ * @param wwwAuthenticate The www-authenticate header value
130
+ * @returns True if OAuth was successfully configured and authenticated, false otherwise
131
+ */
132
+ async function handleAutomaticOAuth(mcpServerName, mcpServerConfig, wwwAuthenticate) {
133
+ try {
134
+ console.log(`🔐 '${mcpServerName}' requires OAuth authentication`);
135
+ // Always try to parse the resource metadata URI from the www-authenticate header
136
+ let oauthConfig;
137
+ const resourceMetadataUri = OAuthUtils.parseWWWAuthenticateHeader(wwwAuthenticate);
138
+ if (resourceMetadataUri) {
139
+ oauthConfig = await OAuthUtils.discoverOAuthConfig(resourceMetadataUri);
140
+ }
141
+ else if (mcpServerConfig.url) {
142
+ // Fallback: try to discover OAuth config from the base URL for SSE
143
+ const sseUrl = new URL(mcpServerConfig.url);
144
+ const baseUrl = `${sseUrl.protocol}//${sseUrl.host}`;
145
+ oauthConfig = await OAuthUtils.discoverOAuthConfig(baseUrl);
146
+ }
147
+ else if (mcpServerConfig.httpUrl) {
148
+ // Fallback: try to discover OAuth config from the base URL for HTTP
149
+ const httpUrl = new URL(mcpServerConfig.httpUrl);
150
+ const baseUrl = `${httpUrl.protocol}//${httpUrl.host}`;
151
+ oauthConfig = await OAuthUtils.discoverOAuthConfig(baseUrl);
152
+ }
153
+ if (!oauthConfig) {
154
+ console.error(`❌ Could not configure OAuth for '${mcpServerName}' - please authenticate manually with /mcp auth ${mcpServerName}`);
155
+ return false;
156
+ }
157
+ // OAuth configuration discovered - proceed with authentication
158
+ // Create OAuth configuration for authentication
159
+ const oauthAuthConfig = {
160
+ enabled: true,
161
+ authorizationUrl: oauthConfig.authorizationUrl,
162
+ tokenUrl: oauthConfig.tokenUrl,
163
+ scopes: oauthConfig.scopes || [],
164
+ };
165
+ // Perform OAuth authentication
166
+ console.log(`Starting OAuth authentication for server '${mcpServerName}'...`);
167
+ await MCPOAuthProvider.authenticate(mcpServerName, oauthAuthConfig);
168
+ console.log(`OAuth authentication successful for server '${mcpServerName}'`);
169
+ return true;
170
+ }
171
+ catch (error) {
172
+ console.error(`Failed to handle automatic OAuth for server '${mcpServerName}': ${getErrorMessage(error)}`);
173
+ return false;
174
+ }
175
+ }
176
+ /**
177
+ * Create a transport with OAuth token for the given server configuration.
178
+ *
179
+ * @param mcpServerName The name of the MCP server
180
+ * @param mcpServerConfig The MCP server configuration
181
+ * @param accessToken The OAuth access token
182
+ * @returns The transport with OAuth token, or null if creation fails
183
+ */
184
+ async function createTransportWithOAuth(mcpServerName, mcpServerConfig, accessToken) {
185
+ try {
186
+ if (mcpServerConfig.httpUrl) {
187
+ // Create HTTP transport with OAuth token
188
+ const oauthTransportOptions = {
189
+ requestInit: {
190
+ headers: {
191
+ ...mcpServerConfig.headers,
192
+ Authorization: `Bearer ${accessToken}`,
193
+ },
194
+ },
195
+ };
196
+ return new StreamableHTTPClientTransport(new URL(mcpServerConfig.httpUrl), oauthTransportOptions);
197
+ }
198
+ else if (mcpServerConfig.url) {
199
+ // Create SSE transport with OAuth token in Authorization header
200
+ return new SSEClientTransport(new URL(mcpServerConfig.url), {
201
+ requestInit: {
202
+ headers: {
203
+ ...mcpServerConfig.headers,
204
+ Authorization: `Bearer ${accessToken}`,
205
+ },
206
+ },
207
+ });
208
+ }
209
+ return null;
210
+ }
211
+ catch (error) {
212
+ console.error(`Failed to create OAuth transport for server '${mcpServerName}': ${getErrorMessage(error)}`);
213
+ return null;
214
+ }
215
+ }
92
216
  /**
93
217
  * Discovers tools from all configured MCP servers and registers them with the tool registry.
94
218
  * It orchestrates the connection and discovery process for each server defined in the
@@ -99,11 +223,11 @@ export function getMCPDiscoveryState() {
99
223
  * @param toolRegistry The central registry where discovered tools will be registered.
100
224
  * @returns A promise that resolves when the discovery process has been attempted for all servers.
101
225
  */
102
- export async function discoverMcpTools(mcpServers, mcpServerCommand, toolRegistry, debugMode) {
226
+ export async function discoverMcpTools(mcpServers, mcpServerCommand, toolRegistry, promptRegistry, debugMode) {
103
227
  mcpDiscoveryState = MCPDiscoveryState.IN_PROGRESS;
104
228
  try {
105
229
  mcpServers = populateMcpServerCommand(mcpServers, mcpServerCommand);
106
- const discoveryPromises = Object.entries(mcpServers).map(([mcpServerName, mcpServerConfig]) => connectAndDiscover(mcpServerName, mcpServerConfig, toolRegistry, debugMode));
230
+ const discoveryPromises = Object.entries(mcpServers).map(([mcpServerName, mcpServerConfig]) => connectAndDiscover(mcpServerName, mcpServerConfig, toolRegistry, promptRegistry, debugMode));
107
231
  await Promise.all(discoveryPromises);
108
232
  }
109
233
  finally {
@@ -136,35 +260,33 @@ export function populateMcpServerCommand(mcpServers, mcpServerCommand) {
136
260
  * @param toolRegistry The registry to register discovered tools with
137
261
  * @returns Promise that resolves when discovery is complete
138
262
  */
139
- export async function connectAndDiscover(mcpServerName, mcpServerConfig, toolRegistry, debugMode) {
263
+ export async function connectAndDiscover(mcpServerName, mcpServerConfig, toolRegistry, promptRegistry, debugMode) {
140
264
  updateMCPServerStatus(mcpServerName, MCPServerStatus.CONNECTING);
265
+ let mcpClient;
141
266
  try {
142
- const mcpClient = await connectToMcpServer(mcpServerName, mcpServerConfig, debugMode);
143
- try {
144
- updateMCPServerStatus(mcpServerName, MCPServerStatus.CONNECTED);
145
- mcpClient.onerror = (error) => {
146
- console.error(`MCP ERROR (${mcpServerName}):`, error.toString());
147
- updateMCPServerStatus(mcpServerName, MCPServerStatus.DISCONNECTED);
148
- if (mcpServerName === IDE_SERVER_NAME) {
149
- ideContext.clearOpenFilesContext();
150
- }
151
- };
152
- if (mcpServerName === IDE_SERVER_NAME) {
153
- mcpClient.setNotificationHandler(OpenFilesNotificationSchema, (notification) => {
154
- ideContext.setOpenFilesContext(notification.params);
155
- });
156
- }
157
- const tools = await discoverTools(mcpServerName, mcpServerConfig, mcpClient);
158
- for (const tool of tools) {
159
- toolRegistry.registerTool(tool);
160
- }
267
+ mcpClient = await connectToMcpServer(mcpServerName, mcpServerConfig, debugMode);
268
+ mcpClient.onerror = (error) => {
269
+ console.error(`MCP ERROR (${mcpServerName}):`, error.toString());
270
+ updateMCPServerStatus(mcpServerName, MCPServerStatus.DISCONNECTED);
271
+ };
272
+ // Attempt to discover both prompts and tools
273
+ const prompts = await discoverPrompts(mcpServerName, mcpClient, promptRegistry);
274
+ const tools = await discoverTools(mcpServerName, mcpServerConfig, mcpClient);
275
+ // If we have neither prompts nor tools, it's a failed discovery
276
+ if (prompts.length === 0 && tools.length === 0) {
277
+ throw new Error('No prompts or tools found on the server.');
161
278
  }
162
- catch (error) {
163
- mcpClient.close();
164
- throw error;
279
+ // If we found anything, the server is connected
280
+ updateMCPServerStatus(mcpServerName, MCPServerStatus.CONNECTED);
281
+ // Register any discovered tools
282
+ for (const tool of tools) {
283
+ toolRegistry.registerTool(tool);
165
284
  }
166
285
  }
167
286
  catch (error) {
287
+ if (mcpClient) {
288
+ mcpClient.close();
289
+ }
168
290
  console.error(`Error connecting to MCP server '${mcpServerName}': ${getErrorMessage(error)}`);
169
291
  updateMCPServerStatus(mcpServerName, MCPServerStatus.DISCONNECTED);
170
292
  }
@@ -185,22 +307,86 @@ export async function discoverTools(mcpServerName, mcpServerConfig, mcpClient) {
185
307
  const mcpCallableTool = mcpToTool(mcpClient);
186
308
  const tool = await mcpCallableTool.tool();
187
309
  if (!Array.isArray(tool.functionDeclarations)) {
188
- throw new Error(`Server did not return valid function declarations.`);
310
+ // This is a valid case for a prompt-only server
311
+ return [];
189
312
  }
190
313
  const discoveredTools = [];
191
314
  for (const funcDecl of tool.functionDeclarations) {
192
- if (!isEnabled(funcDecl, mcpServerName, mcpServerConfig)) {
193
- continue;
315
+ try {
316
+ if (!isEnabled(funcDecl, mcpServerName, mcpServerConfig)) {
317
+ continue;
318
+ }
319
+ discoveredTools.push(new DiscoveredMCPTool(mcpCallableTool, mcpServerName, funcDecl.name, funcDecl.description ?? '', funcDecl.parametersJsonSchema ?? { type: 'object', properties: {} }, mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC, mcpServerConfig.trust));
320
+ }
321
+ catch (error) {
322
+ console.error(`Error discovering tool: '${funcDecl.name}' from MCP server '${mcpServerName}': ${error.message}`);
194
323
  }
195
- discoveredTools.push(new DiscoveredMCPTool(mcpCallableTool, mcpServerName, funcDecl.name, funcDecl.description ?? '', funcDecl.parametersJsonSchema ?? { type: 'object', properties: {} }, mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC, mcpServerConfig.trust));
196
- }
197
- if (discoveredTools.length === 0) {
198
- throw Error('No enabled tools found');
199
324
  }
200
325
  return discoveredTools;
201
326
  }
202
327
  catch (error) {
203
- throw new Error(`Error discovering tools: ${error}`);
328
+ if (error instanceof Error &&
329
+ !error.message?.includes('Method not found')) {
330
+ console.error(`Error discovering tools from ${mcpServerName}: ${getErrorMessage(error)}`);
331
+ }
332
+ return [];
333
+ }
334
+ }
335
+ /**
336
+ * Discovers and logs prompts from a connected MCP client.
337
+ * It retrieves prompt declarations from the client and logs their names.
338
+ *
339
+ * @param mcpServerName The name of the MCP server.
340
+ * @param mcpClient The active MCP client instance.
341
+ */
342
+ export async function discoverPrompts(mcpServerName, mcpClient, promptRegistry) {
343
+ try {
344
+ const response = await mcpClient.request({ method: 'prompts/list', params: {} }, ListPromptsResultSchema);
345
+ for (const prompt of response.prompts) {
346
+ promptRegistry.registerPrompt({
347
+ ...prompt,
348
+ serverName: mcpServerName,
349
+ invoke: (params) => invokeMcpPrompt(mcpServerName, mcpClient, prompt.name, params),
350
+ });
351
+ }
352
+ return response.prompts;
353
+ }
354
+ catch (error) {
355
+ // It's okay if this fails, not all servers will have prompts.
356
+ // Don't log an error if the method is not found, which is a common case.
357
+ if (error instanceof Error &&
358
+ !error.message?.includes('Method not found')) {
359
+ console.error(`Error discovering prompts from ${mcpServerName}: ${getErrorMessage(error)}`);
360
+ }
361
+ return [];
362
+ }
363
+ }
364
+ /**
365
+ * Invokes a prompt on a connected MCP client.
366
+ *
367
+ * @param mcpServerName The name of the MCP server.
368
+ * @param mcpClient The active MCP client instance.
369
+ * @param promptName The name of the prompt to invoke.
370
+ * @param promptParams The parameters to pass to the prompt.
371
+ * @returns A promise that resolves to the result of the prompt invocation.
372
+ */
373
+ export async function invokeMcpPrompt(mcpServerName, mcpClient, promptName, promptParams) {
374
+ try {
375
+ const response = await mcpClient.request({
376
+ method: 'prompts/get',
377
+ params: {
378
+ name: promptName,
379
+ arguments: promptParams,
380
+ },
381
+ }, GetPromptResultSchema);
382
+ return response;
383
+ }
384
+ catch (error) {
385
+ if (error instanceof Error &&
386
+ !error.message?.includes('Method not found')) {
387
+ console.error(`Error invoking prompt '${promptName}' from ${mcpServerName} ${promptParams}: ${getErrorMessage(error)}`);
388
+ }
389
+ throw error;
204
390
  }
205
391
  }
206
392
  /**
@@ -230,7 +416,7 @@ export async function connectToMcpServer(mcpServerName, mcpServerConfig, debugMo
230
416
  };
231
417
  }
232
418
  try {
233
- const transport = createTransport(mcpServerName, mcpServerConfig, debugMode);
419
+ const transport = await createTransport(mcpServerName, mcpServerConfig, debugMode);
234
420
  try {
235
421
  await mcpClient.connect(transport, {
236
422
  timeout: mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC,
@@ -243,29 +429,280 @@ export async function connectToMcpServer(mcpServerName, mcpServerConfig, debugMo
243
429
  }
244
430
  }
245
431
  catch (error) {
246
- // Create a safe config object that excludes sensitive information
247
- const safeConfig = {
248
- command: mcpServerConfig.command,
249
- url: mcpServerConfig.url,
250
- httpUrl: mcpServerConfig.httpUrl,
251
- cwd: mcpServerConfig.cwd,
252
- timeout: mcpServerConfig.timeout,
253
- trust: mcpServerConfig.trust,
254
- // Exclude args, env, and headers which may contain sensitive data
255
- };
256
- let errorString = `failed to start or connect to MCP server '${mcpServerName}' ` +
257
- `${JSON.stringify(safeConfig)}; \n${error}`;
258
- if (process.env.SANDBOX) {
259
- errorString += `\nMake sure it is available in the sandbox`;
432
+ // Check if this is a 401 error that might indicate OAuth is required
433
+ const errorString = String(error);
434
+ if (errorString.includes('401') &&
435
+ (mcpServerConfig.httpUrl || mcpServerConfig.url)) {
436
+ mcpServerRequiresOAuth.set(mcpServerName, true);
437
+ // Only trigger automatic OAuth discovery for HTTP servers or when OAuth is explicitly configured
438
+ // For SSE servers, we should not trigger new OAuth flows automatically
439
+ const shouldTriggerOAuth = mcpServerConfig.httpUrl || mcpServerConfig.oauth?.enabled;
440
+ if (!shouldTriggerOAuth) {
441
+ // For SSE servers without explicit OAuth config, if a token was found but rejected, report it accurately.
442
+ const credentials = await MCPOAuthTokenStorage.getToken(mcpServerName);
443
+ if (credentials) {
444
+ const hasStoredTokens = await MCPOAuthProvider.getValidToken(mcpServerName, {
445
+ // Pass client ID if available
446
+ clientId: credentials.clientId,
447
+ });
448
+ if (hasStoredTokens) {
449
+ console.log(`Stored OAuth token for SSE server '${mcpServerName}' was rejected. ` +
450
+ `Please re-authenticate using: /mcp auth ${mcpServerName}`);
451
+ }
452
+ else {
453
+ console.log(`401 error received for SSE server '${mcpServerName}' without OAuth configuration. ` +
454
+ `Please authenticate using: /mcp auth ${mcpServerName}`);
455
+ }
456
+ }
457
+ throw new Error(`401 error received for SSE server '${mcpServerName}' without OAuth configuration. ` +
458
+ `Please authenticate using: /mcp auth ${mcpServerName}`);
459
+ }
460
+ // Try to extract www-authenticate header from the error
461
+ let wwwAuthenticate = extractWWWAuthenticateHeader(errorString);
462
+ // If we didn't get the header from the error string, try to get it from the server
463
+ if (!wwwAuthenticate && mcpServerConfig.url) {
464
+ console.log(`No www-authenticate header in error, trying to fetch it from server...`);
465
+ try {
466
+ const response = await fetch(mcpServerConfig.url, {
467
+ method: 'HEAD',
468
+ headers: {
469
+ Accept: 'text/event-stream',
470
+ },
471
+ signal: AbortSignal.timeout(5000),
472
+ });
473
+ if (response.status === 401) {
474
+ wwwAuthenticate = response.headers.get('www-authenticate');
475
+ if (wwwAuthenticate) {
476
+ console.log(`Found www-authenticate header from server: ${wwwAuthenticate}`);
477
+ }
478
+ }
479
+ }
480
+ catch (fetchError) {
481
+ console.debug(`Failed to fetch www-authenticate header: ${getErrorMessage(fetchError)}`);
482
+ }
483
+ }
484
+ if (wwwAuthenticate) {
485
+ console.log(`Received 401 with www-authenticate header: ${wwwAuthenticate}`);
486
+ // Try automatic OAuth discovery and authentication
487
+ const oauthSuccess = await handleAutomaticOAuth(mcpServerName, mcpServerConfig, wwwAuthenticate);
488
+ if (oauthSuccess) {
489
+ // Retry connection with OAuth token
490
+ console.log(`Retrying connection to '${mcpServerName}' with OAuth token...`);
491
+ // Get the valid token - we need to create a proper OAuth config
492
+ // The token should already be available from the authentication process
493
+ const credentials = await MCPOAuthTokenStorage.getToken(mcpServerName);
494
+ if (credentials) {
495
+ const accessToken = await MCPOAuthProvider.getValidToken(mcpServerName, {
496
+ // Pass client ID if available
497
+ clientId: credentials.clientId,
498
+ });
499
+ if (accessToken) {
500
+ // Create transport with OAuth token
501
+ const oauthTransport = await createTransportWithOAuth(mcpServerName, mcpServerConfig, accessToken);
502
+ if (oauthTransport) {
503
+ try {
504
+ await mcpClient.connect(oauthTransport, {
505
+ timeout: mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC,
506
+ });
507
+ // Connection successful with OAuth
508
+ return mcpClient;
509
+ }
510
+ catch (retryError) {
511
+ console.error(`Failed to connect with OAuth token: ${getErrorMessage(retryError)}`);
512
+ throw retryError;
513
+ }
514
+ }
515
+ else {
516
+ console.error(`Failed to create OAuth transport for server '${mcpServerName}'`);
517
+ throw new Error(`Failed to create OAuth transport for server '${mcpServerName}'`);
518
+ }
519
+ }
520
+ else {
521
+ console.error(`Failed to get OAuth token for server '${mcpServerName}'`);
522
+ throw new Error(`Failed to get OAuth token for server '${mcpServerName}'`);
523
+ }
524
+ }
525
+ else {
526
+ console.error(`Failed to get credentials for server '${mcpServerName}' after successful OAuth authentication`);
527
+ throw new Error(`Failed to get credentials for server '${mcpServerName}' after successful OAuth authentication`);
528
+ }
529
+ }
530
+ else {
531
+ console.error(`Failed to handle automatic OAuth for server '${mcpServerName}'`);
532
+ throw new Error(`Failed to handle automatic OAuth for server '${mcpServerName}'`);
533
+ }
534
+ }
535
+ else {
536
+ // No www-authenticate header found, but we got a 401
537
+ // Only try OAuth discovery for HTTP servers or when OAuth is explicitly configured
538
+ // For SSE servers, we should not trigger new OAuth flows automatically
539
+ const shouldTryDiscovery = mcpServerConfig.httpUrl || mcpServerConfig.oauth?.enabled;
540
+ if (!shouldTryDiscovery) {
541
+ const credentials = await MCPOAuthTokenStorage.getToken(mcpServerName);
542
+ if (credentials) {
543
+ const hasStoredTokens = await MCPOAuthProvider.getValidToken(mcpServerName, {
544
+ // Pass client ID if available
545
+ clientId: credentials.clientId,
546
+ });
547
+ if (hasStoredTokens) {
548
+ console.log(`Stored OAuth token for SSE server '${mcpServerName}' was rejected. ` +
549
+ `Please re-authenticate using: /mcp auth ${mcpServerName}`);
550
+ }
551
+ else {
552
+ console.log(`401 error received for SSE server '${mcpServerName}' without OAuth configuration. ` +
553
+ `Please authenticate using: /mcp auth ${mcpServerName}`);
554
+ }
555
+ }
556
+ throw new Error(`401 error received for SSE server '${mcpServerName}' without OAuth configuration. ` +
557
+ `Please authenticate using: /mcp auth ${mcpServerName}`);
558
+ }
559
+ // For SSE servers, try to discover OAuth configuration from the base URL
560
+ console.log(`🔍 Attempting OAuth discovery for '${mcpServerName}'...`);
561
+ if (mcpServerConfig.url) {
562
+ const sseUrl = new URL(mcpServerConfig.url);
563
+ const baseUrl = `${sseUrl.protocol}//${sseUrl.host}`;
564
+ try {
565
+ // Try to discover OAuth configuration from the base URL
566
+ const oauthConfig = await OAuthUtils.discoverOAuthConfig(baseUrl);
567
+ if (oauthConfig) {
568
+ console.log(`Discovered OAuth configuration from base URL for server '${mcpServerName}'`);
569
+ // Create OAuth configuration for authentication
570
+ const oauthAuthConfig = {
571
+ enabled: true,
572
+ authorizationUrl: oauthConfig.authorizationUrl,
573
+ tokenUrl: oauthConfig.tokenUrl,
574
+ scopes: oauthConfig.scopes || [],
575
+ };
576
+ // Perform OAuth authentication
577
+ console.log(`Starting OAuth authentication for server '${mcpServerName}'...`);
578
+ await MCPOAuthProvider.authenticate(mcpServerName, oauthAuthConfig);
579
+ // Retry connection with OAuth token
580
+ const credentials = await MCPOAuthTokenStorage.getToken(mcpServerName);
581
+ if (credentials) {
582
+ const accessToken = await MCPOAuthProvider.getValidToken(mcpServerName, {
583
+ // Pass client ID if available
584
+ clientId: credentials.clientId,
585
+ });
586
+ if (accessToken) {
587
+ // Create transport with OAuth token
588
+ const oauthTransport = await createTransportWithOAuth(mcpServerName, mcpServerConfig, accessToken);
589
+ if (oauthTransport) {
590
+ try {
591
+ await mcpClient.connect(oauthTransport, {
592
+ timeout: mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC,
593
+ });
594
+ // Connection successful with OAuth
595
+ return mcpClient;
596
+ }
597
+ catch (retryError) {
598
+ console.error(`Failed to connect with OAuth token: ${getErrorMessage(retryError)}`);
599
+ throw retryError;
600
+ }
601
+ }
602
+ else {
603
+ console.error(`Failed to create OAuth transport for server '${mcpServerName}'`);
604
+ throw new Error(`Failed to create OAuth transport for server '${mcpServerName}'`);
605
+ }
606
+ }
607
+ else {
608
+ console.error(`Failed to get OAuth token for server '${mcpServerName}'`);
609
+ throw new Error(`Failed to get OAuth token for server '${mcpServerName}'`);
610
+ }
611
+ }
612
+ else {
613
+ console.error(`Failed to get stored credentials for server '${mcpServerName}'`);
614
+ throw new Error(`Failed to get stored credentials for server '${mcpServerName}'`);
615
+ }
616
+ }
617
+ else {
618
+ console.error(`❌ Could not configure OAuth for '${mcpServerName}' - please authenticate manually with /mcp auth ${mcpServerName}`);
619
+ throw new Error(`OAuth configuration failed for '${mcpServerName}'. Please authenticate manually with /mcp auth ${mcpServerName}`);
620
+ }
621
+ }
622
+ catch (discoveryError) {
623
+ console.error(`❌ OAuth discovery failed for '${mcpServerName}' - please authenticate manually with /mcp auth ${mcpServerName}`);
624
+ throw discoveryError;
625
+ }
626
+ }
627
+ else {
628
+ console.error(`❌ '${mcpServerName}' requires authentication but no OAuth configuration found`);
629
+ throw new Error(`MCP server '${mcpServerName}' requires authentication. Please configure OAuth or check server settings.`);
630
+ }
631
+ }
632
+ }
633
+ else {
634
+ // Handle other connection errors
635
+ // Create a concise error message
636
+ const errorMessage = error.message || String(error);
637
+ const isNetworkError = errorMessage.includes('ENOTFOUND') ||
638
+ errorMessage.includes('ECONNREFUSED');
639
+ let conciseError;
640
+ if (isNetworkError) {
641
+ conciseError = `Cannot connect to '${mcpServerName}' - server may be down or URL incorrect`;
642
+ }
643
+ else {
644
+ conciseError = `Connection failed for '${mcpServerName}': ${errorMessage}`;
645
+ }
646
+ if (process.env.SANDBOX) {
647
+ conciseError += ` (check sandbox availability)`;
648
+ }
649
+ throw new Error(conciseError);
260
650
  }
261
- throw new Error(errorString);
262
651
  }
263
652
  }
264
653
  /** Visible for Testing */
265
- export function createTransport(mcpServerName, mcpServerConfig, debugMode) {
654
+ export async function createTransport(mcpServerName, mcpServerConfig, debugMode) {
655
+ if (mcpServerConfig.authProviderType === AuthProviderType.GOOGLE_CREDENTIALS) {
656
+ const provider = new GoogleCredentialProvider(mcpServerConfig);
657
+ const transportOptions = {
658
+ authProvider: provider,
659
+ };
660
+ if (mcpServerConfig.httpUrl) {
661
+ return new StreamableHTTPClientTransport(new URL(mcpServerConfig.httpUrl), transportOptions);
662
+ }
663
+ else if (mcpServerConfig.url) {
664
+ return new SSEClientTransport(new URL(mcpServerConfig.url), transportOptions);
665
+ }
666
+ throw new Error('No URL configured for Google Credentials MCP server');
667
+ }
668
+ // Check if we have OAuth configuration or stored tokens
669
+ let accessToken = null;
670
+ let hasOAuthConfig = mcpServerConfig.oauth?.enabled;
671
+ if (hasOAuthConfig && mcpServerConfig.oauth) {
672
+ accessToken = await MCPOAuthProvider.getValidToken(mcpServerName, mcpServerConfig.oauth);
673
+ if (!accessToken) {
674
+ console.error(`MCP server '${mcpServerName}' requires OAuth authentication. ` +
675
+ `Please authenticate using the /mcp auth command.`);
676
+ throw new Error(`MCP server '${mcpServerName}' requires OAuth authentication. ` +
677
+ `Please authenticate using the /mcp auth command.`);
678
+ }
679
+ }
680
+ else {
681
+ // Check if we have stored OAuth tokens for this server (from previous authentication)
682
+ const credentials = await MCPOAuthTokenStorage.getToken(mcpServerName);
683
+ if (credentials) {
684
+ accessToken = await MCPOAuthProvider.getValidToken(mcpServerName, {
685
+ // Pass client ID if available
686
+ clientId: credentials.clientId,
687
+ });
688
+ if (accessToken) {
689
+ hasOAuthConfig = true;
690
+ console.log(`Found stored OAuth token for server '${mcpServerName}'`);
691
+ }
692
+ }
693
+ }
266
694
  if (mcpServerConfig.httpUrl) {
267
695
  const transportOptions = {};
268
- if (mcpServerConfig.headers) {
696
+ // Set up headers with OAuth token if available
697
+ if (hasOAuthConfig && accessToken) {
698
+ transportOptions.requestInit = {
699
+ headers: {
700
+ ...mcpServerConfig.headers,
701
+ Authorization: `Bearer ${accessToken}`,
702
+ },
703
+ };
704
+ }
705
+ else if (mcpServerConfig.headers) {
269
706
  transportOptions.requestInit = {
270
707
  headers: mcpServerConfig.headers,
271
708
  };
@@ -274,7 +711,16 @@ export function createTransport(mcpServerName, mcpServerConfig, debugMode) {
274
711
  }
275
712
  if (mcpServerConfig.url) {
276
713
  const transportOptions = {};
277
- if (mcpServerConfig.headers) {
714
+ // Set up headers with OAuth token if available
715
+ if (hasOAuthConfig && accessToken) {
716
+ transportOptions.requestInit = {
717
+ headers: {
718
+ ...mcpServerConfig.headers,
719
+ Authorization: `Bearer ${accessToken}`,
720
+ },
721
+ };
722
+ }
723
+ else if (mcpServerConfig.headers) {
278
724
  transportOptions.requestInit = {
279
725
  headers: mcpServerConfig.headers,
280
726
  };