@herbertgao/pi-extensions 2026.9.17 → 2026.9.18

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 (266) hide show
  1. package/README.md +14 -15
  2. package/node_modules/@herbertgao/pi-bark/package.json +2 -2
  3. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +4 -1
  4. package/node_modules/@herbertgao/pi-cc-extensions/README.md +4 -1
  5. package/node_modules/@herbertgao/pi-cc-extensions/package.json +75 -75
  6. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +6 -0
  7. package/node_modules/@herbertgao/pi-subagents/package.json +7 -7
  8. package/node_modules/@herbertgao/resume-from/package.json +4 -2
  9. package/node_modules/@herbertgao/sol-pi/package.json +6 -6
  10. package/node_modules/@juicesharp/rpiv-ask-user-question/package.json +99 -99
  11. package/node_modules/@pi-plugins/fast-mode/package.json +1 -1
  12. package/node_modules/@tifan/pi-handoff/package.json +1 -1
  13. package/node_modules/@tifan/pi-handoff/src/index.ts +56 -26
  14. package/node_modules/@tifan/pi-mermaid-open/package.json +1 -1
  15. package/node_modules/@tifan/pi-preferred-thinking/package.json +1 -1
  16. package/node_modules/@tifan/pi-recap/package.json +1 -1
  17. package/node_modules/@tifan/pi-rename/package.json +1 -1
  18. package/node_modules/pi-antigravity/package.json +2 -2
  19. package/node_modules/pi-lens/package.json +158 -158
  20. package/node_modules/pi-multi-account/package.json +2 -2
  21. package/node_modules/pi-typesafe/README.md +1 -1
  22. package/node_modules/pi-typesafe/dist/auth.d.ts +9 -5
  23. package/node_modules/pi-typesafe/dist/auth.js +7 -3
  24. package/node_modules/pi-typesafe/dist/backends.d.ts +33 -3
  25. package/node_modules/pi-typesafe/dist/backends.js +95 -1
  26. package/node_modules/pi-typesafe/dist/client.d.ts +5 -5
  27. package/node_modules/pi-typesafe/dist/client.js +12 -9
  28. package/node_modules/pi-typesafe/dist/credentials.d.ts +14 -8
  29. package/node_modules/pi-typesafe/dist/credentials.js +10 -7
  30. package/node_modules/pi-typesafe/dist/errors.d.ts +2 -2
  31. package/node_modules/pi-typesafe/dist/index.d.ts +2 -2
  32. package/node_modules/pi-typesafe/dist/index.js +1 -1
  33. package/node_modules/pi-typesafe/dist/login.d.ts +2 -2
  34. package/node_modules/pi-typesafe/dist/login.js +2 -2
  35. package/node_modules/pi-typesafe/package.json +5 -5
  36. package/node_modules/pi-web-access/package.json +2 -2
  37. package/node_modules/remote-pi/package.json +5 -1
  38. package/package.json +16 -28
  39. package/node_modules/pi-mcp-adapter/CHANGELOG.md +0 -1013
  40. package/node_modules/pi-mcp-adapter/LICENSE +0 -21
  41. package/node_modules/pi-mcp-adapter/OAUTH.md +0 -369
  42. package/node_modules/pi-mcp-adapter/README.md +0 -1021
  43. package/node_modules/pi-mcp-adapter/abort.ts +0 -34
  44. package/node_modules/pi-mcp-adapter/agent-dir.ts +0 -68
  45. package/node_modules/pi-mcp-adapter/agent-plugin-loader.ts +0 -416
  46. package/node_modules/pi-mcp-adapter/agent-plugin-provenance.ts +0 -36
  47. package/node_modules/pi-mcp-adapter/app-bridge.bundle.js +0 -67
  48. package/node_modules/pi-mcp-adapter/banner.png +0 -0
  49. package/node_modules/pi-mcp-adapter/bearer-command-resolver.ts +0 -193
  50. package/node_modules/pi-mcp-adapter/claude-plugin-loader.ts +0 -365
  51. package/node_modules/pi-mcp-adapter/cli.js +0 -454
  52. package/node_modules/pi-mcp-adapter/commands.ts +0 -861
  53. package/node_modules/pi-mcp-adapter/config.ts +0 -1565
  54. package/node_modules/pi-mcp-adapter/consent-manager.ts +0 -95
  55. package/node_modules/pi-mcp-adapter/direct-tool-surface.ts +0 -244
  56. package/node_modules/pi-mcp-adapter/direct-tools.ts +0 -428
  57. package/node_modules/pi-mcp-adapter/dist/abort.d.ts +0 -2
  58. package/node_modules/pi-mcp-adapter/dist/abort.js +0 -36
  59. package/node_modules/pi-mcp-adapter/dist/abort.js.map +0 -1
  60. package/node_modules/pi-mcp-adapter/dist/agent-dir.d.ts +0 -10
  61. package/node_modules/pi-mcp-adapter/dist/agent-dir.js +0 -63
  62. package/node_modules/pi-mcp-adapter/dist/agent-dir.js.map +0 -1
  63. package/node_modules/pi-mcp-adapter/dist/agent-plugin-loader.d.ts +0 -8
  64. package/node_modules/pi-mcp-adapter/dist/agent-plugin-loader.js +0 -398
  65. package/node_modules/pi-mcp-adapter/dist/agent-plugin-loader.js.map +0 -1
  66. package/node_modules/pi-mcp-adapter/dist/agent-plugin-provenance.d.ts +0 -1
  67. package/node_modules/pi-mcp-adapter/dist/agent-plugin-provenance.js +0 -31
  68. package/node_modules/pi-mcp-adapter/dist/agent-plugin-provenance.js.map +0 -1
  69. package/node_modules/pi-mcp-adapter/dist/bearer-command-resolver.d.ts +0 -6
  70. package/node_modules/pi-mcp-adapter/dist/bearer-command-resolver.js +0 -194
  71. package/node_modules/pi-mcp-adapter/dist/bearer-command-resolver.js.map +0 -1
  72. package/node_modules/pi-mcp-adapter/dist/claude-plugin-loader.d.ts +0 -9
  73. package/node_modules/pi-mcp-adapter/dist/claude-plugin-loader.js +0 -362
  74. package/node_modules/pi-mcp-adapter/dist/claude-plugin-loader.js.map +0 -1
  75. package/node_modules/pi-mcp-adapter/dist/config.d.ts +0 -134
  76. package/node_modules/pi-mcp-adapter/dist/config.js +0 -1361
  77. package/node_modules/pi-mcp-adapter/dist/config.js.map +0 -1
  78. package/node_modules/pi-mcp-adapter/dist/consent-manager.d.ts +0 -18
  79. package/node_modules/pi-mcp-adapter/dist/consent-manager.js +0 -88
  80. package/node_modules/pi-mcp-adapter/dist/consent-manager.js.map +0 -1
  81. package/node_modules/pi-mcp-adapter/dist/elicitation-handler.d.ts +0 -17
  82. package/node_modules/pi-mcp-adapter/dist/elicitation-handler.js +0 -316
  83. package/node_modules/pi-mcp-adapter/dist/elicitation-handler.js.map +0 -1
  84. package/node_modules/pi-mcp-adapter/dist/errors.d.ts +0 -131
  85. package/node_modules/pi-mcp-adapter/dist/errors.js +0 -278
  86. package/node_modules/pi-mcp-adapter/dist/errors.js.map +0 -1
  87. package/node_modules/pi-mcp-adapter/dist/http-ca.d.ts +0 -8
  88. package/node_modules/pi-mcp-adapter/dist/http-ca.js +0 -88
  89. package/node_modules/pi-mcp-adapter/dist/http-ca.js.map +0 -1
  90. package/node_modules/pi-mcp-adapter/dist/jev-client.d.ts +0 -14
  91. package/node_modules/pi-mcp-adapter/dist/jev-client.js +0 -367
  92. package/node_modules/pi-mcp-adapter/dist/jev-client.js.map +0 -1
  93. package/node_modules/pi-mcp-adapter/dist/jev-contracts.d.ts +0 -77
  94. package/node_modules/pi-mcp-adapter/dist/jev-contracts.js +0 -2
  95. package/node_modules/pi-mcp-adapter/dist/jev-contracts.js.map +0 -1
  96. package/node_modules/pi-mcp-adapter/dist/jev-key-store.d.ts +0 -51
  97. package/node_modules/pi-mcp-adapter/dist/jev-key-store.js +0 -205
  98. package/node_modules/pi-mcp-adapter/dist/jev-key-store.js.map +0 -1
  99. package/node_modules/pi-mcp-adapter/dist/json-schema-validator.d.ts +0 -2
  100. package/node_modules/pi-mcp-adapter/dist/json-schema-validator.js +0 -68
  101. package/node_modules/pi-mcp-adapter/dist/json-schema-validator.js.map +0 -1
  102. package/node_modules/pi-mcp-adapter/dist/lifecycle.d.ts +0 -56
  103. package/node_modules/pi-mcp-adapter/dist/lifecycle.js +0 -410
  104. package/node_modules/pi-mcp-adapter/dist/lifecycle.js.map +0 -1
  105. package/node_modules/pi-mcp-adapter/dist/logger.d.ts +0 -51
  106. package/node_modules/pi-mcp-adapter/dist/logger.js +0 -131
  107. package/node_modules/pi-mcp-adapter/dist/logger.js.map +0 -1
  108. package/node_modules/pi-mcp-adapter/dist/mcp-auth-fetch.d.ts +0 -26
  109. package/node_modules/pi-mcp-adapter/dist/mcp-auth-fetch.js +0 -103
  110. package/node_modules/pi-mcp-adapter/dist/mcp-auth-fetch.js.map +0 -1
  111. package/node_modules/pi-mcp-adapter/dist/mcp-auth-flow.d.ts +0 -118
  112. package/node_modules/pi-mcp-adapter/dist/mcp-auth-flow.js +0 -1097
  113. package/node_modules/pi-mcp-adapter/dist/mcp-auth-flow.js.map +0 -1
  114. package/node_modules/pi-mcp-adapter/dist/mcp-auth.d.ts +0 -170
  115. package/node_modules/pi-mcp-adapter/dist/mcp-auth.js +0 -1142
  116. package/node_modules/pi-mcp-adapter/dist/mcp-auth.js.map +0 -1
  117. package/node_modules/pi-mcp-adapter/dist/mcp-bearer-store.d.ts +0 -24
  118. package/node_modules/pi-mcp-adapter/dist/mcp-bearer-store.js +0 -203
  119. package/node_modules/pi-mcp-adapter/dist/mcp-bearer-store.js.map +0 -1
  120. package/node_modules/pi-mcp-adapter/dist/mcp-callback-server.d.ts +0 -53
  121. package/node_modules/pi-mcp-adapter/dist/mcp-callback-server.js +0 -441
  122. package/node_modules/pi-mcp-adapter/dist/mcp-callback-server.js.map +0 -1
  123. package/node_modules/pi-mcp-adapter/dist/mcp-oauth-provider.d.ts +0 -148
  124. package/node_modules/pi-mcp-adapter/dist/mcp-oauth-provider.js +0 -689
  125. package/node_modules/pi-mcp-adapter/dist/mcp-oauth-provider.js.map +0 -1
  126. package/node_modules/pi-mcp-adapter/dist/mcp-probe.d.ts +0 -6
  127. package/node_modules/pi-mcp-adapter/dist/mcp-probe.js +0 -166
  128. package/node_modules/pi-mcp-adapter/dist/mcp-probe.js.map +0 -1
  129. package/node_modules/pi-mcp-adapter/dist/mcp-tasks.d.ts +0 -102
  130. package/node_modules/pi-mcp-adapter/dist/mcp-tasks.js +0 -369
  131. package/node_modules/pi-mcp-adapter/dist/mcp-tasks.js.map +0 -1
  132. package/node_modules/pi-mcp-adapter/dist/mcp-trace.d.ts +0 -95
  133. package/node_modules/pi-mcp-adapter/dist/mcp-trace.js +0 -242
  134. package/node_modules/pi-mcp-adapter/dist/mcp-trace.js.map +0 -1
  135. package/node_modules/pi-mcp-adapter/dist/metadata-cache.d.ts +0 -19
  136. package/node_modules/pi-mcp-adapter/dist/metadata-cache.js +0 -301
  137. package/node_modules/pi-mcp-adapter/dist/metadata-cache.js.map +0 -1
  138. package/node_modules/pi-mcp-adapter/dist/npx-resolver.d.ts +0 -6
  139. package/node_modules/pi-mcp-adapter/dist/npx-resolver.js +0 -505
  140. package/node_modules/pi-mcp-adapter/dist/npx-resolver.js.map +0 -1
  141. package/node_modules/pi-mcp-adapter/dist/package-mcp-loader.d.ts +0 -2
  142. package/node_modules/pi-mcp-adapter/dist/package-mcp-loader.js +0 -144
  143. package/node_modules/pi-mcp-adapter/dist/package-mcp-loader.js.map +0 -1
  144. package/node_modules/pi-mcp-adapter/dist/request-headers-command.d.ts +0 -10
  145. package/node_modules/pi-mcp-adapter/dist/request-headers-command.js +0 -312
  146. package/node_modules/pi-mcp-adapter/dist/request-headers-command.js.map +0 -1
  147. package/node_modules/pi-mcp-adapter/dist/resource-tools.d.ts +0 -1
  148. package/node_modules/pi-mcp-adapter/dist/resource-tools.js +0 -15
  149. package/node_modules/pi-mcp-adapter/dist/resource-tools.js.map +0 -1
  150. package/node_modules/pi-mcp-adapter/dist/runtime-owner.d.ts +0 -13
  151. package/node_modules/pi-mcp-adapter/dist/runtime-owner.js +0 -97
  152. package/node_modules/pi-mcp-adapter/dist/runtime-owner.js.map +0 -1
  153. package/node_modules/pi-mcp-adapter/dist/sampling-handler.d.ts +0 -17
  154. package/node_modules/pi-mcp-adapter/dist/sampling-handler.js +0 -203
  155. package/node_modules/pi-mcp-adapter/dist/sampling-handler.js.map +0 -1
  156. package/node_modules/pi-mcp-adapter/dist/secure-keyring.d.ts +0 -11
  157. package/node_modules/pi-mcp-adapter/dist/secure-keyring.js +0 -172
  158. package/node_modules/pi-mcp-adapter/dist/secure-keyring.js.map +0 -1
  159. package/node_modules/pi-mcp-adapter/dist/server-manager.d.ts +0 -157
  160. package/node_modules/pi-mcp-adapter/dist/server-manager.js +0 -1745
  161. package/node_modules/pi-mcp-adapter/dist/server-manager.js.map +0 -1
  162. package/node_modules/pi-mcp-adapter/dist/session-approvals.d.ts +0 -34
  163. package/node_modules/pi-mcp-adapter/dist/session-approvals.js +0 -140
  164. package/node_modules/pi-mcp-adapter/dist/session-approvals.js.map +0 -1
  165. package/node_modules/pi-mcp-adapter/dist/session-recovery.d.ts +0 -26
  166. package/node_modules/pi-mcp-adapter/dist/session-recovery.js +0 -142
  167. package/node_modules/pi-mcp-adapter/dist/session-recovery.js.map +0 -1
  168. package/node_modules/pi-mcp-adapter/dist/state.d.ts +0 -73
  169. package/node_modules/pi-mcp-adapter/dist/state.js +0 -2
  170. package/node_modules/pi-mcp-adapter/dist/state.js.map +0 -1
  171. package/node_modules/pi-mcp-adapter/dist/types.d.ts +0 -642
  172. package/node_modules/pi-mcp-adapter/dist/types.js +0 -331
  173. package/node_modules/pi-mcp-adapter/dist/types.js.map +0 -1
  174. package/node_modules/pi-mcp-adapter/dist/ui-app-bridge-helpers.d.ts +0 -6
  175. package/node_modules/pi-mcp-adapter/dist/ui-app-bridge-helpers.js +0 -37
  176. package/node_modules/pi-mcp-adapter/dist/ui-app-bridge-helpers.js.map +0 -1
  177. package/node_modules/pi-mcp-adapter/dist/ui-resource-handler.d.ts +0 -17
  178. package/node_modules/pi-mcp-adapter/dist/ui-resource-handler.js +0 -219
  179. package/node_modules/pi-mcp-adapter/dist/ui-resource-handler.js.map +0 -1
  180. package/node_modules/pi-mcp-adapter/dist/ui-stream-types.d.ts +0 -104
  181. package/node_modules/pi-mcp-adapter/dist/ui-stream-types.js +0 -59
  182. package/node_modules/pi-mcp-adapter/dist/ui-stream-types.js.map +0 -1
  183. package/node_modules/pi-mcp-adapter/dist/ui-tool-visibility.d.ts +0 -4
  184. package/node_modules/pi-mcp-adapter/dist/ui-tool-visibility.js +0 -27
  185. package/node_modules/pi-mcp-adapter/dist/ui-tool-visibility.js.map +0 -1
  186. package/node_modules/pi-mcp-adapter/dist/unix-socket-transport.d.ts +0 -15
  187. package/node_modules/pi-mcp-adapter/dist/unix-socket-transport.js +0 -85
  188. package/node_modules/pi-mcp-adapter/dist/unix-socket-transport.js.map +0 -1
  189. package/node_modules/pi-mcp-adapter/dist/utils.d.ts +0 -41
  190. package/node_modules/pi-mcp-adapter/dist/utils.js +0 -417
  191. package/node_modules/pi-mcp-adapter/dist/utils.js.map +0 -1
  192. package/node_modules/pi-mcp-adapter/elicitation-handler.ts +0 -358
  193. package/node_modules/pi-mcp-adapter/error-signal.ts +0 -32
  194. package/node_modules/pi-mcp-adapter/errors.ts +0 -364
  195. package/node_modules/pi-mcp-adapter/examples/jev-accessibility-loop.mjs +0 -85
  196. package/node_modules/pi-mcp-adapter/examples/jev-semantic-filter.mjs +0 -34
  197. package/node_modules/pi-mcp-adapter/failure-backoff.ts +0 -23
  198. package/node_modules/pi-mcp-adapter/glimpse-ui.ts +0 -80
  199. package/node_modules/pi-mcp-adapter/host-html-template.ts +0 -515
  200. package/node_modules/pi-mcp-adapter/http-ca.ts +0 -84
  201. package/node_modules/pi-mcp-adapter/index.ts +0 -2106
  202. package/node_modules/pi-mcp-adapter/init.ts +0 -721
  203. package/node_modules/pi-mcp-adapter/jev-client.ts +0 -300
  204. package/node_modules/pi-mcp-adapter/jev-contracts.ts +0 -53
  205. package/node_modules/pi-mcp-adapter/jev-key-store.ts +0 -192
  206. package/node_modules/pi-mcp-adapter/json-schema-validator.ts +0 -83
  207. package/node_modules/pi-mcp-adapter/lazy-loader.ts +0 -7
  208. package/node_modules/pi-mcp-adapter/lifecycle.ts +0 -457
  209. package/node_modules/pi-mcp-adapter/logger.ts +0 -169
  210. package/node_modules/pi-mcp-adapter/mcp-auth-fetch.ts +0 -113
  211. package/node_modules/pi-mcp-adapter/mcp-auth-flow.ts +0 -1296
  212. package/node_modules/pi-mcp-adapter/mcp-auth.ts +0 -1287
  213. package/node_modules/pi-mcp-adapter/mcp-bearer-store.ts +0 -250
  214. package/node_modules/pi-mcp-adapter/mcp-callback-server.ts +0 -534
  215. package/node_modules/pi-mcp-adapter/mcp-code.ts +0 -495
  216. package/node_modules/pi-mcp-adapter/mcp-install.ts +0 -60
  217. package/node_modules/pi-mcp-adapter/mcp-keyring-helper.cjs +0 -89
  218. package/node_modules/pi-mcp-adapter/mcp-oauth-provider.ts +0 -819
  219. package/node_modules/pi-mcp-adapter/mcp-output-guard.ts +0 -511
  220. package/node_modules/pi-mcp-adapter/mcp-panel-theme.ts +0 -104
  221. package/node_modules/pi-mcp-adapter/mcp-panel.ts +0 -1099
  222. package/node_modules/pi-mcp-adapter/mcp-probe.ts +0 -201
  223. package/node_modules/pi-mcp-adapter/mcp-references.ts +0 -373
  224. package/node_modules/pi-mcp-adapter/mcp-script-worker.mjs +0 -137
  225. package/node_modules/pi-mcp-adapter/mcp-setup-panel.ts +0 -747
  226. package/node_modules/pi-mcp-adapter/mcp-status.ts +0 -105
  227. package/node_modules/pi-mcp-adapter/mcp-tasks.ts +0 -467
  228. package/node_modules/pi-mcp-adapter/mcp-trace.ts +0 -306
  229. package/node_modules/pi-mcp-adapter/metadata-cache.ts +0 -362
  230. package/node_modules/pi-mcp-adapter/namespace-tools.ts +0 -334
  231. package/node_modules/pi-mcp-adapter/npx-resolver.ts +0 -543
  232. package/node_modules/pi-mcp-adapter/oauth-handler.ts +0 -30
  233. package/node_modules/pi-mcp-adapter/oauth.ts +0 -52
  234. package/node_modules/pi-mcp-adapter/onboarding-state.ts +0 -76
  235. package/node_modules/pi-mcp-adapter/package-mcp-loader.ts +0 -156
  236. package/node_modules/pi-mcp-adapter/package.json +0 -219
  237. package/node_modules/pi-mcp-adapter/panel-keys.ts +0 -53
  238. package/node_modules/pi-mcp-adapter/prompts.ts +0 -385
  239. package/node_modules/pi-mcp-adapter/proxy-modes.ts +0 -1735
  240. package/node_modules/pi-mcp-adapter/request-headers-command.ts +0 -333
  241. package/node_modules/pi-mcp-adapter/resource-tools.ts +0 -17
  242. package/node_modules/pi-mcp-adapter/runtime-owner.ts +0 -106
  243. package/node_modules/pi-mcp-adapter/sampling-handler.ts +0 -261
  244. package/node_modules/pi-mcp-adapter/sandbox-proxy-template.ts +0 -144
  245. package/node_modules/pi-mcp-adapter/search-ranking.ts +0 -309
  246. package/node_modules/pi-mcp-adapter/secure-keyring.ts +0 -170
  247. package/node_modules/pi-mcp-adapter/semantic-search.ts +0 -186
  248. package/node_modules/pi-mcp-adapter/server-manager.ts +0 -2088
  249. package/node_modules/pi-mcp-adapter/session-approvals.ts +0 -201
  250. package/node_modules/pi-mcp-adapter/session-recovery.ts +0 -158
  251. package/node_modules/pi-mcp-adapter/skills/mcp-scripting/SKILL.md +0 -49
  252. package/node_modules/pi-mcp-adapter/state.ts +0 -71
  253. package/node_modules/pi-mcp-adapter/tool-approval.ts +0 -205
  254. package/node_modules/pi-mcp-adapter/tool-metadata.ts +0 -302
  255. package/node_modules/pi-mcp-adapter/tool-registrar.ts +0 -255
  256. package/node_modules/pi-mcp-adapter/tool-result-renderer.ts +0 -573
  257. package/node_modules/pi-mcp-adapter/ts-shape.ts +0 -149
  258. package/node_modules/pi-mcp-adapter/types.ts +0 -1120
  259. package/node_modules/pi-mcp-adapter/ui-app-bridge-helpers.ts +0 -40
  260. package/node_modules/pi-mcp-adapter/ui-resource-handler.ts +0 -266
  261. package/node_modules/pi-mcp-adapter/ui-server.ts +0 -993
  262. package/node_modules/pi-mcp-adapter/ui-session.ts +0 -624
  263. package/node_modules/pi-mcp-adapter/ui-stream-types.ts +0 -89
  264. package/node_modules/pi-mcp-adapter/ui-tool-visibility.ts +0 -25
  265. package/node_modules/pi-mcp-adapter/unix-socket-transport.ts +0 -85
  266. package/node_modules/pi-mcp-adapter/utils.ts +0 -464
@@ -1,2088 +0,0 @@
1
- import { mkdirSync, statSync } from "node:fs";
2
- import { BlockList, isIP } from "node:net";
3
- import { isDeepStrictEqual } from "node:util";
4
- import {
5
- Client,
6
- SdkError,
7
- SdkErrorCode,
8
- SdkHttpError,
9
- SseError,
10
- SSEClientTransport,
11
- StreamableHTTPClientTransport,
12
- UnauthorizedError,
13
- type FetchLike,
14
- type GetPromptResult,
15
- type ListToolsResult,
16
- type ReadResourceResult,
17
- type McpSubscription,
18
- type SubscriptionFilter,
19
- type CacheableRequestOptions,
20
- type RequestOptions,
21
- type UrlElicitationRequiredError,
22
- type VersionNegotiationOptions,
23
- } from "@modelcontextprotocol/client";
24
- import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
25
- import { UnixSocketClientTransport } from "./unix-socket-transport.ts";
26
- import { probeMcpEndpoint } from "./mcp-probe.ts";
27
- import {
28
- isServerDisabled,
29
- type McpTool,
30
- type McpResource,
31
- type McpPrompt,
32
- type ServerDefinition,
33
- type ServerStreamResultPatchNotification,
34
- type Transport,
35
- type McpTraceSettings,
36
- type McpListenState,
37
- SERVER_STREAM_RESULT_PATCH_METHOD,
38
- serverStreamResultPatchNotificationSchema,
39
- } from "./types.ts";
40
- import { resolveNpxBinary } from "./npx-resolver.ts";
41
- import { createJsonSchemaValidator } from "./json-schema-validator.ts";
42
- import { logger } from "./logger.ts";
43
- import { RESOURCE_MIME_TYPE } from "./ui-app-bridge-helpers.ts";
44
- import { isBuiltInAgentPlugin } from "./agent-plugin-provenance.ts";
45
- import { McpOAuthProvider } from "./mcp-oauth-provider.ts";
46
- import { extractOAuthConfig, supportsOAuth, type McpOAuthRuntime } from "./mcp-auth-flow.ts";
47
- import {
48
- captureOAuthAuthority,
49
- inspectAuthForUrl,
50
- invalidateAuthEntryCache,
51
- type AuthStorageOptions,
52
- type OAuthAuthority,
53
- } from "./mcp-auth.ts";
54
- import { getBearerTokenForUrl } from "./mcp-bearer-store.ts";
55
- import { handleSamplingRequest, registerSamplingHandler, type ServerSamplingConfig } from "./sampling-handler.ts";
56
- import {
57
- handleElicitationRequest,
58
- handleUrlElicitation,
59
- registerElicitationHandler,
60
- type ServerElicitationConfig,
61
- } from "./elicitation-handler.ts";
62
- import { attachTaskSession, type RawRequestChannel } from "./mcp-tasks.ts";
63
- import type { TaskEnabledSession } from "@modelcontextprotocol/ext-tasks/client";
64
- import {
65
- interpolateEnvVars,
66
- expandHomePath,
67
- resolveBearerToken,
68
- resolveCommandSecret,
69
- resolveCommandSecretsRecord,
70
- resolveConfigPath,
71
- resolveServerUrl,
72
- } from "./utils.ts";
73
- import { abortable, throwIfAborted } from "./abort.ts";
74
- import { combineAbortSignals } from "./runtime-owner.ts";
75
- import {
76
- createMcpTraceWriter,
77
- isMcpTraceEnabled,
78
- McpTraceWriter,
79
- type McpTraceObserver,
80
- traceTransportKind,
81
- wrapTransportWithMcpTrace,
82
- } from "./mcp-trace.ts";
83
- import { createOAuthFetch, resolveOAuthHeaders } from "./mcp-auth-fetch.ts";
84
- import { createRequestHeadersCommandFetch } from "./request-headers-command.ts";
85
- import { createCaFetch, validateCaFile } from "./http-ca.ts";
86
- import { BearerCommandResolver } from "./bearer-command-resolver.ts";
87
-
88
- const MAX_CAPTURED_STDERR_BYTES = 8 * 1024;
89
- const MAX_CAPTURED_STDERR_LINES = 3;
90
- const abortCleanupPromises = new WeakMap<object, Promise<void>>();
91
-
92
- type HttpAuthProviderState =
93
- | { status: "disabled" }
94
- | { status: "implicit-deferred" }
95
- | { status: "implicit-stored"; provider: McpOAuthProvider }
96
- | { status: "explicit"; provider: McpOAuthProvider }
97
- | { status: "implicit-challenged"; provider: McpOAuthProvider };
98
-
99
- function isLiteralLocalAddress(url: string): boolean {
100
- const hostname = new URL(url).hostname.replace(/^\[|\]$/g, "");
101
- const family = isIP(hostname);
102
- if (!family) return false;
103
- const local = new BlockList();
104
- local.addSubnet("10.0.0.0", 8);
105
- local.addSubnet("172.16.0.0", 12);
106
- local.addSubnet("192.168.0.0", 16);
107
- local.addSubnet("169.254.0.0", 16);
108
- local.addSubnet("fc00::", 7, "ipv6");
109
- local.addSubnet("fe80::", 10, "ipv6");
110
- return local.check(hostname, family === 6 ? "ipv6" : "ipv4");
111
- }
112
-
113
- function localNetworkFailureCodes(error: unknown, seen = new Set<object>()): string[] {
114
- if (typeof error !== "object" || error === null || seen.has(error)) return [];
115
- seen.add(error);
116
- const codes: string[] = [];
117
- if ("code" in error && typeof error.code === "string"
118
- && ["EHOSTUNREACH", "ENETUNREACH", "EACCES"].includes(error.code)) {
119
- codes.push(error.code);
120
- }
121
- if ("cause" in error) codes.push(...localNetworkFailureCodes(error.cause, seen));
122
- if (error instanceof AggregateError) {
123
- for (const nested of error.errors) codes.push(...localNetworkFailureCodes(nested, seen));
124
- }
125
- return [...new Set(codes)];
126
- }
127
-
128
- export function isUnauthorizedHttpError(error: unknown): boolean {
129
- return error instanceof UnauthorizedError
130
- || (error instanceof SdkHttpError && error.status === 401)
131
- // Some pinned-SDK transport paths emit this plain Error when bearer
132
- // request headers are used without an OAuth authProvider.
133
- || (error instanceof Error && /^Error POSTing to endpoint \(HTTP 401\):/.test(error.message));
134
- }
135
-
136
- function shouldFallbackToSse(error: unknown, definition: ServerDefinition): boolean {
137
- if (definition.protocolVersion === "2026-07-28") return false;
138
- return error instanceof SdkHttpError && [404, 405, 406, 415].includes(error.status);
139
- }
140
-
141
- function resolveVersionNegotiation(definition: ServerDefinition): VersionNegotiationOptions | undefined {
142
- switch (definition.protocolVersion) {
143
- case undefined:
144
- case "legacy":
145
- return undefined;
146
- case "auto":
147
- return { mode: "auto" };
148
- case "2026-07-28":
149
- return { mode: { pin: "2026-07-28" } };
150
- default:
151
- throw new Error(`Invalid MCP protocolVersion: ${String(definition.protocolVersion)}`);
152
- }
153
- }
154
-
155
- function boundedStderrChunk(chunk: Buffer | string): Buffer {
156
- if (Buffer.isBuffer(chunk)) {
157
- const start = Math.max(0, chunk.byteLength - MAX_CAPTURED_STDERR_BYTES);
158
- return Buffer.from(chunk.subarray(start));
159
- }
160
-
161
- // Limit string conversion before encoding; Buffer.from(largeString) would
162
- // otherwise allocate the entire stderr event before applying the cap.
163
- const suffix = chunk.length > MAX_CAPTURED_STDERR_BYTES
164
- ? chunk.slice(-MAX_CAPTURED_STDERR_BYTES)
165
- : chunk;
166
- const bytes = Buffer.from(suffix, "utf8");
167
- return bytes.byteLength > MAX_CAPTURED_STDERR_BYTES
168
- ? Buffer.from(bytes.subarray(bytes.byteLength - MAX_CAPTURED_STDERR_BYTES))
169
- : bytes;
170
- }
171
-
172
- function appendStderrTail(tail: Buffer, chunk: Buffer | string): Buffer {
173
- const bytes = boundedStderrChunk(chunk);
174
- if (bytes.length === 0) return tail;
175
- if (tail.length === 0) return bytes;
176
- const combined = Buffer.concat([tail, bytes]);
177
- return combined.length > MAX_CAPTURED_STDERR_BYTES
178
- ? Buffer.from(combined.subarray(combined.length - MAX_CAPTURED_STDERR_BYTES))
179
- : combined;
180
- }
181
-
182
- export interface ServerConnection {
183
- client: Client;
184
- transport: Transport;
185
- definition: ServerDefinition;
186
- tools: McpTool[];
187
- /** Cache hints from the server's aggregated tools/list result. */
188
- toolListHints?: Partial<Pick<ListToolsResult, "ttlMs" | "cacheScope">> | undefined;
189
- /** Monotonic guard against older refresh responses replacing newer notifications. */
190
- toolsRevision?: number;
191
- resources: McpResource[];
192
- /** True when resources were advertised but resources/list failed. */
193
- resourceDiscoveryFailed?: boolean;
194
- prompts: McpPrompt[];
195
- /** True when prompts were advertised but prompts/list failed. */
196
- promptDiscoveryFailed?: boolean;
197
- instructions?: string;
198
- lastUsedAt: number;
199
- inFlight: number;
200
- status: "connected" | "closed" | "needs-auth";
201
- /** Catalog subscription health, tracked independently from transport health. */
202
- listenState: McpListenState;
203
- /** ext-tasks requester session, attached when `tasks: true` and the server advertises the extension. */
204
- taskSession?: TaskEnabledSession;
205
- /** Raw JSON-RPC channel backing the task session on 2026-07-28 connections. */
206
- taskChannel?: RawRequestChannel;
207
- listenSubscription?: McpSubscription;
208
- /** Last requested filter; the server's honored filter may be a subset. */
209
- listenFilter?: SubscriptionFilter;
210
- /** True when recovery has an active listen but could not confirm every catalog list. */
211
- listenCatalogStale?: boolean;
212
- listenPromise?: Promise<void>;
213
- listenRetryAfter?: number;
214
- listenStopped?: boolean;
215
- recentResourceUris?: Map<string, number>;
216
- resourceReadRefreshUris?: Set<string>;
217
- /** True once this needs-auth episode discarded the cached credential. */
218
- credentialsInvalidated?: boolean;
219
- }
220
-
221
-
222
- type UiStreamListener = (serverName: string, notification: ServerStreamResultPatchNotification["params"]) => void;
223
- type MetadataListChangedListener = (serverName: string, reason: string) => void;
224
- type ListenStateChangedListener = (serverName: string, state: McpListenState) => void;
225
- type ResourceUpdatedListener = (serverName: string, uri: string) => void;
226
-
227
- export type ToolRefreshResult = "updated" | "unchanged" | "superseded" | "refresh-timeout";
228
-
229
- type ToolListCacheHints = Partial<Pick<ListToolsResult, "ttlMs" | "cacheScope">>;
230
- type ToolListResult = { tools: McpTool[]; hints?: ToolListCacheHints };
231
- type ResourceListResult = { resources: McpResource[]; failed: boolean };
232
-
233
- const KEEP_ALIVE_REFRESH_TIMEOUT_MS = 5_000;
234
- const LISTEN_RETRY_DELAY_MS = 5_000;
235
- const RECENT_RESOURCE_TTL_MS = 10 * 60_000;
236
- const MAX_RESOURCE_SUBSCRIPTIONS = 32;
237
-
238
- export function isTransientHttpConnectError(error: unknown): boolean {
239
- let current: unknown = error;
240
- while (current instanceof Error) {
241
- if (current instanceof SdkHttpError && current.status === 503) return true;
242
- current = current.cause;
243
- }
244
- return false;
245
- }
246
-
247
- /** Wrap a FetchLike so each request re-resolves the bearer token via the resolver. */
248
- function createBearerCommandFetch(
249
- resolver: BearerCommandResolver,
250
- delegate: FetchLike | undefined,
251
- ): FetchLike {
252
- const innerFetch = delegate
253
- ? (input: URL | RequestInfo, init?: RequestInit) => delegate(input as URL, init)
254
- : (input: URL | RequestInfo, init?: RequestInit) => globalThis.fetch(input, init);
255
- return async (input, init) => {
256
- const request = new Request(input, init);
257
- const token = await resolver.resolve(request.signal);
258
- const headers = new Headers(request.headers);
259
- headers.set("Authorization", `Bearer ${token}`);
260
- // Composed runtime fetches accept Request despite the SDK's narrower type.
261
- return innerFetch(new Request(request, { headers }));
262
- };
263
- }
264
-
265
- export class McpServerManager {
266
- private connections = new Map<string, ServerConnection>();
267
- private connectPromises = new Map<string, Promise<ServerConnection>>();
268
- private connectOAuthAuthorities = new Map<string, OAuthAuthority>();
269
- private reconnectPromises = new Map<string, Promise<ServerConnection>>();
270
- private reconnectOAuthAuthorities = new Map<string, OAuthAuthority>();
271
- private reconnectAttempts = new Map<string, AbortController>();
272
- private uiStreamListeners = new Map<string, UiStreamListener>();
273
- private samplingConfig: ServerSamplingConfig | undefined;
274
- private metadataListChangedListener: MetadataListChangedListener | undefined;
275
- private listenStateChangedListener: ListenStateChangedListener | undefined;
276
- private resourceUpdatedListeners = new Map<string, {
277
- serverName: string;
278
- uri: string;
279
- listener: ResourceUpdatedListener;
280
- }>();
281
- private pendingMetadataPublications = new Map<
282
- string,
283
- { connection: ServerConnection; reason: string }
284
- >();
285
- private elicitationConfig: ServerElicitationConfig | undefined;
286
- private authStorageOptions: AuthStorageOptions = {};
287
- private oauthRuntime: McpOAuthRuntime | undefined;
288
- private acceptedUrlElicitations = new Map<string, Set<string>>();
289
- private defaultRequestTimeoutMs: number | undefined;
290
- private runtimeSignal: AbortSignal | undefined;
291
- private closePromises = new Map<string, Promise<void>>();
292
- private closeGenerations = new Map<string, number>();
293
- private connectAttempts = new Map<string, AbortController>();
294
- private traceSettings: McpTraceSettings | undefined;
295
- private traceWriter: McpTraceWriter | undefined;
296
- private stopped = false;
297
-
298
- /** Default cwd for stdio servers without an explicit config `cwd`. */
299
- constructor(private readonly defaultCwd?: string) {}
300
-
301
- setSamplingConfig(config: ServerSamplingConfig | undefined): void {
302
- this.samplingConfig = config;
303
- }
304
-
305
- setMetadataListChangedListener(listener: MetadataListChangedListener | undefined): void {
306
- this.metadataListChangedListener = listener;
307
- }
308
-
309
- setListenStateChangedListener(listener: ListenStateChangedListener | undefined): void {
310
- this.listenStateChangedListener = listener;
311
- }
312
-
313
- publishMetadataChanged(
314
- name: string,
315
- expectedConnection: ServerConnection,
316
- reason: string,
317
- ): boolean {
318
- const current = this.connections.get(name);
319
- if (current !== expectedConnection || current.status !== "connected") return false;
320
- try {
321
- this.metadataListChangedListener?.(name, reason);
322
- this.pendingMetadataPublications.delete(name);
323
- return true;
324
- } catch (error) {
325
- this.pendingMetadataPublications.set(name, { connection: expectedConnection, reason });
326
- const message = error instanceof Error ? error.message : String(error);
327
- logger.debug(`MCP: metadata publication failed for ${name}; queued for retry: ${message}`);
328
- return false;
329
- }
330
- }
331
-
332
- setElicitationConfig(config: ServerElicitationConfig | undefined): void {
333
- this.elicitationConfig = config;
334
- }
335
-
336
- setRuntimeSignal(signal: AbortSignal | undefined): void {
337
- this.runtimeSignal = signal;
338
- }
339
-
340
- setDefaultRequestTimeoutMs(timeoutMs: number | undefined): void {
341
- this.defaultRequestTimeoutMs = normalizeRequestTimeoutMs(timeoutMs);
342
- }
343
-
344
- setTraceConfig(settings: McpTraceSettings | undefined): void {
345
- this.traceSettings = settings;
346
- }
347
-
348
- setAuthStorageOptions(options: AuthStorageOptions): void {
349
- this.authStorageOptions = options;
350
- }
351
-
352
- setOAuthRuntime(runtime: McpOAuthRuntime): void {
353
- this.oauthRuntime = runtime;
354
- }
355
-
356
- getRequestOptions(name: string, signal?: AbortSignal): RequestOptions | undefined {
357
- const connection = this.connections.get(name);
358
- return this.buildRequestOptions(connection?.definition, signal);
359
- }
360
-
361
- private getResolvedRequestTimeoutMs(definition?: ServerDefinition): number | undefined {
362
- if (definition?.requestTimeoutMs !== undefined) {
363
- return normalizeRequestTimeoutMs(definition.requestTimeoutMs);
364
- }
365
- return this.defaultRequestTimeoutMs;
366
- }
367
-
368
- private buildRequestOptions(
369
- definition?: ServerDefinition,
370
- signal?: AbortSignal,
371
- ): RequestOptions | undefined {
372
- const timeout = this.getResolvedRequestTimeoutMs(definition);
373
- const ownedSignal = combineAbortSignals(this.runtimeSignal, signal);
374
-
375
- if (!ownedSignal && timeout === undefined) {
376
- return undefined;
377
- }
378
-
379
- return {
380
- ...(ownedSignal ? { signal: ownedSignal } : {}),
381
- ...(timeout !== undefined ? { timeout } : {}),
382
- };
383
- }
384
-
385
- private arbitrateConnectionAttempt(
386
- name: string,
387
- oauthAuthority: OAuthAuthority | undefined,
388
- promises: Map<string, Promise<ServerConnection>>,
389
- authorities: Map<string, OAuthAuthority>,
390
- attempts: Map<string, AbortController>,
391
- ): Promise<ServerConnection> | undefined {
392
- const existingPromise = promises.get(name);
393
- if (!existingPromise) return undefined;
394
-
395
- const existingAuthority = authorities.get(name);
396
- let reusable = oauthAuthority === undefined && existingAuthority === undefined;
397
- if (oauthAuthority && existingAuthority) {
398
- try {
399
- existingAuthority();
400
- reusable = true;
401
- } catch {
402
- reusable = false;
403
- }
404
- }
405
- if (reusable) return existingPromise;
406
-
407
- const replacedAttempt = attempts.get(name);
408
- replacedAttempt?.abort(new Error(`MCP connection ${name} was replaced`));
409
- if (attempts.get(name) === replacedAttempt) attempts.delete(name);
410
- if (promises.get(name) === existingPromise) promises.delete(name);
411
- if (authorities.get(name) === existingAuthority) authorities.delete(name);
412
- return undefined;
413
- }
414
-
415
- async connect(name: string, definition: ServerDefinition, signal?: AbortSignal): Promise<ServerConnection> {
416
- validateCaFile(definition);
417
- if (isServerDisabled(definition)) throw new Error(`MCP server "${name}" is disabled`);
418
- if (this.stopped) throw new Error("MCP server manager is closed");
419
- const ownedSignal = combineAbortSignals(this.runtimeSignal, signal);
420
- throwIfAborted(ownedSignal);
421
- const oauthAuthority = definition.url && supportsOAuth(definition)
422
- ? captureOAuthAuthority(name, false)
423
- : undefined;
424
- const closing = this.closePromises.get(name);
425
- if (closing) await abortable(closing, ownedSignal);
426
- throwIfAborted(ownedSignal);
427
-
428
- // Dedupe concurrent connection attempts.
429
- const existingConnect = this.arbitrateConnectionAttempt(
430
- name,
431
- oauthAuthority,
432
- this.connectPromises,
433
- this.connectOAuthAuthorities,
434
- this.connectAttempts,
435
- );
436
- if (existingConnect) return abortable(existingConnect, ownedSignal);
437
-
438
- const existing = this.connections.get(name);
439
- if (existing?.status === "connected") {
440
- existing.lastUsedAt = Date.now();
441
- return existing;
442
- }
443
-
444
- // A needs-auth route can be retried through either public path. Share an
445
- // authority-compatible reconnect candidate instead of creating a second
446
- // owner for the same server.
447
- const existingReconnect = this.arbitrateConnectionAttempt(
448
- name,
449
- oauthAuthority,
450
- this.reconnectPromises,
451
- this.reconnectOAuthAuthorities,
452
- this.reconnectAttempts,
453
- );
454
- if (existingReconnect) return abortable(existingReconnect, ownedSignal);
455
-
456
- const credentialsInvalidated = existing?.status === "needs-auth"
457
- && existing.credentialsInvalidated === true;
458
- const generation = this.closeGenerations.get(name) ?? 0;
459
- const attemptController = new AbortController();
460
- const attemptSignal = combineAbortSignals(ownedSignal, attemptController.signal);
461
- const connectionAttempt = this.createConnection(
462
- name,
463
- definition,
464
- attemptSignal,
465
- ownedSignal,
466
- credentialsInvalidated,
467
- oauthAuthority,
468
- attemptController,
469
- );
470
- const promise = definition.url
471
- ? connectionAttempt.catch(async error => { throw await this.enrichHttpConnectionError(definition, error); })
472
- : connectionAttempt;
473
- this.connectPromises.set(name, promise);
474
- if (oauthAuthority) this.connectOAuthAuthorities.set(name, oauthAuthority);
475
- this.connectAttempts.set(name, attemptController);
476
-
477
- try {
478
- const connection = await promise;
479
- if (attemptController.signal.aborted || (this.closeGenerations.get(name) ?? 0) !== generation) {
480
- await this.disposeConnection(connection);
481
- throwIfAborted(attemptSignal);
482
- throw new Error(`MCP connection for ${name} was closed while connecting`);
483
- }
484
- this.connections.set(name, connection);
485
- this.watchListenSubscription(name, connection, connection.listenSubscription);
486
- if ([...this.resourceUpdatedListeners.values()].some(registration => registration.serverName === name)) {
487
- void this.ensureListen(name, connection);
488
- }
489
- return connection;
490
- } finally {
491
- if (this.connectPromises.get(name) === promise) this.connectPromises.delete(name);
492
- if (this.connectOAuthAuthorities.get(name) === oauthAuthority) {
493
- this.connectOAuthAuthorities.delete(name);
494
- }
495
- if (this.connectAttempts.get(name) === attemptController) this.connectAttempts.delete(name);
496
- }
497
- }
498
-
499
- /**
500
- * Reconnect a server whose connection was proven stale (e.g. by a 404
501
- * "session no longer exists" response). Single-flight per server name —
502
- * concurrent callers that raced to the same failure share one reconnect —
503
- * and identity-guarded: `staleConnection` is only torn down if it is
504
- * still the manager's current connection for `name`. If a concurrent
505
- * reconnect (or an unrelated connect()) already replaced it with a fresh
506
- * connection, that fresh connection is returned untouched.
507
- */
508
- async reconnect(
509
- name: string,
510
- definition: ServerDefinition,
511
- staleConnection: ServerConnection,
512
- signal?: AbortSignal,
513
- ): Promise<ServerConnection> {
514
- validateCaFile(definition);
515
- if (isServerDisabled(definition)) throw new Error(`MCP server "${name}" is disabled`);
516
- if (this.stopped) throw new Error("MCP server manager is closed");
517
- const ownedSignal = combineAbortSignals(this.runtimeSignal, signal);
518
- throwIfAborted(ownedSignal);
519
- const oauthAuthority = definition.url && supportsOAuth(definition)
520
- ? captureOAuthAuthority(name, false)
521
- : undefined;
522
- // connect() and reconnect() are interchangeable retry entry points for a
523
- // published needs-auth route. They must not create competing OAuth owners.
524
- const existingConnect = this.arbitrateConnectionAttempt(
525
- name,
526
- oauthAuthority,
527
- this.connectPromises,
528
- this.connectOAuthAuthorities,
529
- this.connectAttempts,
530
- );
531
- if (existingConnect) return abortable(existingConnect, ownedSignal);
532
- const inFlight = this.arbitrateConnectionAttempt(
533
- name,
534
- oauthAuthority,
535
- this.reconnectPromises,
536
- this.reconnectOAuthAuthorities,
537
- this.reconnectAttempts,
538
- );
539
- if (inFlight) return abortable(inFlight, ownedSignal);
540
-
541
- const attemptController = new AbortController();
542
- const attemptSignal = combineAbortSignals(ownedSignal, attemptController.signal);
543
- const promise = this.doReconnect(
544
- name,
545
- definition,
546
- staleConnection,
547
- attemptSignal,
548
- oauthAuthority,
549
- attemptController,
550
- )
551
- .catch(error => {
552
- if (attemptController.signal.aborted && !this.containsCleanupFailure(error)) {
553
- throw new Error(`MCP connection for ${name} was closed while reconnecting`, { cause: error });
554
- }
555
- throw error;
556
- })
557
- .finally(() => {
558
- if (this.reconnectPromises.get(name) === promise) {
559
- this.reconnectPromises.delete(name);
560
- }
561
- if (this.reconnectAttempts.get(name) === attemptController) {
562
- this.reconnectAttempts.delete(name);
563
- }
564
- if (this.reconnectOAuthAuthorities.get(name) === oauthAuthority) {
565
- this.reconnectOAuthAuthorities.delete(name);
566
- }
567
- });
568
- this.reconnectPromises.set(name, promise);
569
- if (oauthAuthority) this.reconnectOAuthAuthorities.set(name, oauthAuthority);
570
- this.reconnectAttempts.set(name, attemptController);
571
- return abortable(promise, ownedSignal);
572
- }
573
-
574
- /**
575
- * Fetch the authoritative tool catalog for a connection that still appears
576
- * connected. The SDK response cache is explicitly bypassed so this request
577
- * also proves the remote Streamable HTTP session is usable. Results are
578
- * identity-guarded: a late response from a replaced connection is ignored.
579
- */
580
- async refreshTools(
581
- name: string,
582
- expectedConnection: ServerConnection,
583
- signal?: AbortSignal,
584
- ): Promise<ToolRefreshResult> {
585
- if (this.stopped) throw new Error("MCP server manager is closed");
586
- const ownedSignal = combineAbortSignals(this.runtimeSignal, signal);
587
- throwIfAborted(ownedSignal);
588
-
589
- const current = this.connections.get(name);
590
- if (current !== expectedConnection || current.status !== "connected") {
591
- return "superseded";
592
- }
593
-
594
- await this.ensureListen(name, expectedConnection);
595
-
596
- const requestOptions = this.buildRequestOptions(expectedConnection.definition, signal);
597
- const timeout = Math.min(requestOptions?.timeout ?? KEEP_ALIVE_REFRESH_TIMEOUT_MS, KEEP_ALIVE_REFRESH_TIMEOUT_MS);
598
- const healthOptions = {
599
- ...requestOptions,
600
- timeout,
601
- };
602
- if (!expectedConnection.client.getServerCapabilities?.()?.tools) {
603
- await expectedConnection.client.ping(healthOptions);
604
- throwIfAborted(ownedSignal);
605
- if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected") {
606
- return "superseded";
607
- }
608
- this.retryPendingMetadataPublication(name, expectedConnection);
609
- return "unchanged";
610
- }
611
-
612
- const toolsRevision = expectedConnection.toolsRevision ?? 0;
613
- const refreshSignal = combineAbortSignals(healthOptions.signal, AbortSignal.timeout(timeout));
614
- let toolResult: ToolListResult;
615
- try {
616
- toolResult = await this.fetchAllTools(expectedConnection.client, {
617
- ...healthOptions,
618
- ...(refreshSignal ? { signal: refreshSignal } : {}),
619
- cacheMode: "refresh",
620
- });
621
- } catch (error) {
622
- throwIfAborted(ownedSignal);
623
- if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected") {
624
- return "superseded";
625
- }
626
- if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) {
627
- return "refresh-timeout";
628
- }
629
- throw error;
630
- }
631
- throwIfAborted(ownedSignal);
632
-
633
- if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected") {
634
- return "superseded";
635
- }
636
- if ((expectedConnection.toolsRevision ?? 0) !== toolsRevision) {
637
- return "superseded";
638
- }
639
-
640
- if (
641
- isDeepStrictEqual(expectedConnection.tools, toolResult.tools) &&
642
- isDeepStrictEqual(expectedConnection.toolListHints, toolResult.hints)
643
- ) {
644
- this.retryPendingMetadataPublication(name, expectedConnection);
645
- return "unchanged";
646
- }
647
-
648
- const previousTools = expectedConnection.tools;
649
- const previousToolListHints = expectedConnection.toolListHints;
650
- expectedConnection.tools = toolResult.tools;
651
- expectedConnection.toolListHints = toolResult.hints;
652
- expectedConnection.toolsRevision = toolsRevision + 1;
653
- try {
654
- await this.metadataListChangedListener?.(name, "keep-alive-refresh");
655
- this.pendingMetadataPublications.delete(name);
656
- } catch (error) {
657
- if (
658
- this.connections.get(name) === expectedConnection &&
659
- expectedConnection.tools === toolResult.tools &&
660
- expectedConnection.toolListHints === toolResult.hints
661
- ) {
662
- expectedConnection.tools = previousTools;
663
- expectedConnection.toolListHints = previousToolListHints;
664
- expectedConnection.toolsRevision = toolsRevision;
665
- }
666
- throw error;
667
- }
668
- return "updated";
669
- }
670
-
671
- private retryPendingMetadataPublication(name: string, connection: ServerConnection): void {
672
- const pendingPublication = this.pendingMetadataPublications.get(name);
673
- if (pendingPublication?.connection !== connection) return;
674
- this.metadataListChangedListener?.(name, pendingPublication.reason);
675
- if (this.pendingMetadataPublications.get(name) === pendingPublication) {
676
- this.pendingMetadataPublications.delete(name);
677
- }
678
- }
679
-
680
- private setListenState(name: string, connection: ServerConnection, state: McpListenState): void {
681
- if (connection.listenState === state) return;
682
- connection.listenState = state;
683
- if (this.connections.get(name) === connection) {
684
- try {
685
- this.listenStateChangedListener?.(name, state);
686
- } catch {
687
- // Status consumers must not interrupt listen lifecycle recovery.
688
- }
689
- }
690
- }
691
-
692
- private catalogListenFilter(connection: ServerConnection): SubscriptionFilter {
693
- const capabilities = connection.client.getServerCapabilities?.();
694
- return {
695
- ...(capabilities?.tools?.listChanged ? { toolsListChanged: true } : {}),
696
- ...(capabilities?.prompts?.listChanged ? { promptsListChanged: true } : {}),
697
- ...(capabilities?.resources?.listChanged ? { resourcesListChanged: true } : {}),
698
- };
699
- }
700
-
701
- private currentListenFilter(name: string, connection: ServerConnection): SubscriptionFilter {
702
- const now = Date.now();
703
- const recent = connection.recentResourceUris;
704
- if (recent) {
705
- for (const [uri, touchedAt] of recent) {
706
- if (now - touchedAt > RECENT_RESOURCE_TTL_MS) recent.delete(uri);
707
- }
708
- }
709
- const openResourceUris = [...new Set(
710
- [...this.resourceUpdatedListeners.values()]
711
- .filter(registration => registration.serverName === name)
712
- .map(registration => registration.uri),
713
- )].slice(-MAX_RESOURCE_SUBSCRIPTIONS);
714
- const openSet = new Set(openResourceUris);
715
- const recentSlots = MAX_RESOURCE_SUBSCRIPTIONS - openResourceUris.length;
716
- const recentResourceUris = recentSlots > 0
717
- ? [...(recent?.keys() ?? [])].filter(uri => !openSet.has(uri)).slice(-recentSlots)
718
- : [];
719
- const resourceSubscriptions = [...openResourceUris, ...recentResourceUris];
720
- return {
721
- ...this.catalogListenFilter(connection),
722
- ...(resourceSubscriptions.length > 0 ? { resourceSubscriptions } : {}),
723
- };
724
- }
725
-
726
- private watchListenSubscription(
727
- name: string,
728
- connection: ServerConnection,
729
- subscription: McpSubscription | undefined,
730
- ): void {
731
- if (!subscription) return;
732
- void subscription.closed.then(cause => {
733
- if (
734
- this.stopped ||
735
- this.connections.get(name) !== connection ||
736
- connection.status !== "connected" ||
737
- connection.listenSubscription !== subscription
738
- ) return;
739
- if (cause === "remote") {
740
- const staleUris = connection.listenFilter?.resourceSubscriptions ?? [];
741
- if (staleUris.length > 0) connection.resourceReadRefreshUris = new Set(staleUris);
742
- connection.listenCatalogStale = true;
743
- connection.listenRetryAfter = Date.now();
744
- this.setListenState(name, connection, "dropped");
745
- } else if (cause === "graceful" || connection.listenState !== "re-establishing") {
746
- connection.listenStopped = true;
747
- this.setListenState(name, connection, "not-listening");
748
- }
749
- });
750
- }
751
-
752
- /** Quietly repairs a modern catalog listen at an existing activity boundary. */
753
- async ensureListen(name: string, expectedConnection: ServerConnection): Promise<void> {
754
- if (
755
- this.stopped ||
756
- this.connections.get(name) !== expectedConnection ||
757
- expectedConnection.status !== "connected" ||
758
- expectedConnection.listenStopped ||
759
- expectedConnection.client.getProtocolEra?.() !== "modern"
760
- ) return;
761
-
762
- const filter = this.currentListenFilter(name, expectedConnection);
763
- if (Object.keys(filter).length === 0) {
764
- this.setListenState(name, expectedConnection, "not-listening");
765
- return;
766
- }
767
- if (expectedConnection.listenPromise) {
768
- await expectedConnection.listenPromise;
769
- return this.ensureListen(name, expectedConnection);
770
- }
771
- if ((expectedConnection.listenRetryAfter ?? 0) > Date.now()) return;
772
-
773
- const sameFilter = isDeepStrictEqual(expectedConnection.listenFilter, filter);
774
- if (expectedConnection.listenState === "active" && sameFilter) {
775
- if (!expectedConnection.listenCatalogStale) return;
776
- const attempt = (async () => {
777
- this.setListenState(name, expectedConnection, "re-establishing");
778
- const confirmed = await this.reconcileCatalogAfterListen(name, expectedConnection, this.buildRequestOptions(expectedConnection.definition));
779
- if (!confirmed) expectedConnection.listenRetryAfter = Date.now() + LISTEN_RETRY_DELAY_MS;
780
- this.setListenState(name, expectedConnection, "active");
781
- })().finally(() => {
782
- if (expectedConnection.listenPromise === attempt) delete expectedConnection.listenPromise;
783
- });
784
- expectedConnection.listenPromise = attempt;
785
- return attempt;
786
- }
787
-
788
- const attempt = (async () => {
789
- const recoverDroppedListen = expectedConnection.listenState === "dropped";
790
- this.setListenState(name, expectedConnection, "re-establishing");
791
- const previous = expectedConnection.listenSubscription;
792
- if (previous) await previous.close().catch(() => {});
793
- if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected") return;
794
- try {
795
- const requestOptions = this.buildRequestOptions(expectedConnection.definition);
796
- const subscription = await expectedConnection.client.listen(
797
- filter,
798
- {
799
- ...requestOptions,
800
- timeout: Math.min(requestOptions?.timeout ?? KEEP_ALIVE_REFRESH_TIMEOUT_MS, KEEP_ALIVE_REFRESH_TIMEOUT_MS),
801
- },
802
- );
803
- if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected") {
804
- await subscription.close().catch(() => {});
805
- return;
806
- }
807
- expectedConnection.listenSubscription = subscription;
808
- expectedConnection.listenFilter = filter;
809
- delete expectedConnection.listenStopped;
810
- delete expectedConnection.listenRetryAfter;
811
- this.watchListenSubscription(name, expectedConnection, subscription);
812
- const confirmed = recoverDroppedListen
813
- ? await this.reconcileCatalogAfterListen(name, expectedConnection, requestOptions)
814
- : true;
815
- if (!confirmed) expectedConnection.listenRetryAfter = Date.now() + LISTEN_RETRY_DELAY_MS;
816
- this.setListenState(name, expectedConnection, "active");
817
- } catch (error) {
818
- if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected") return;
819
- if (expectedConnection.listenSubscription) await expectedConnection.listenSubscription.close().catch(() => {});
820
- expectedConnection.listenRetryAfter = Date.now() + LISTEN_RETRY_DELAY_MS;
821
- this.setListenState(name, expectedConnection, "dropped");
822
- logger.debug(`MCP: catalog listen repair failed for ${name}: ${error instanceof Error ? error.message : String(error)}`);
823
- }
824
- })().finally(() => {
825
- if (expectedConnection.listenPromise === attempt) delete expectedConnection.listenPromise;
826
- });
827
- expectedConnection.listenPromise = attempt;
828
- return attempt;
829
- }
830
-
831
- private async reconcileCatalogAfterListen(
832
- name: string,
833
- expectedConnection: ServerConnection,
834
- requestOptions?: CacheableRequestOptions,
835
- ): Promise<boolean> {
836
- const timeout = Math.min(requestOptions?.timeout ?? KEEP_ALIVE_REFRESH_TIMEOUT_MS, KEEP_ALIVE_REFRESH_TIMEOUT_MS);
837
- const refreshSignal = combineAbortSignals(requestOptions?.signal, AbortSignal.timeout(timeout));
838
- const refreshOptions: CacheableRequestOptions = {
839
- ...requestOptions,
840
- timeout,
841
- cacheMode: "refresh",
842
- ...(refreshSignal ? { signal: refreshSignal } : {}),
843
- };
844
- const [toolResult, resources, promptResult] = await Promise.allSettled([
845
- this.fetchAllTools(expectedConnection.client, refreshOptions),
846
- this.fetchAllResources(expectedConnection.client, refreshOptions, true),
847
- this.fetchAllPrompts(expectedConnection.client, refreshOptions),
848
- ]);
849
- if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected") return false;
850
-
851
- const nextTools = toolResult.status === "fulfilled" ? toolResult.value : undefined;
852
- const nextResources = resources.status === "fulfilled" ? resources.value : undefined;
853
- const nextPrompts = promptResult.status === "fulfilled" && !promptResult.value.failed ? promptResult.value : undefined;
854
- const confirmed = nextTools !== undefined && nextResources !== undefined && nextPrompts !== undefined;
855
- const changed = (nextTools !== undefined && (
856
- !isDeepStrictEqual(expectedConnection.tools, nextTools.tools) ||
857
- !isDeepStrictEqual(expectedConnection.toolListHints, nextTools.hints)
858
- )) ||
859
- (nextResources !== undefined && (
860
- !isDeepStrictEqual(expectedConnection.resources, nextResources.resources) ||
861
- expectedConnection.resourceDiscoveryFailed !== nextResources.failed
862
- )) ||
863
- (nextPrompts !== undefined && (
864
- !isDeepStrictEqual(expectedConnection.prompts, nextPrompts.prompts) ||
865
- expectedConnection.promptDiscoveryFailed !== false
866
- ));
867
- if (!changed) {
868
- this.retryPendingMetadataPublication(name, expectedConnection);
869
- if (confirmed) delete expectedConnection.listenCatalogStale;
870
- else expectedConnection.listenCatalogStale = true;
871
- return confirmed;
872
- }
873
-
874
- if (nextTools !== undefined) {
875
- expectedConnection.tools = nextTools.tools;
876
- expectedConnection.toolListHints = nextTools.hints;
877
- expectedConnection.toolsRevision = (expectedConnection.toolsRevision ?? 0) + 1;
878
- }
879
- if (nextResources !== undefined) {
880
- expectedConnection.resources = nextResources.resources;
881
- expectedConnection.resourceDiscoveryFailed = nextResources.failed;
882
- }
883
- if (nextPrompts !== undefined) {
884
- expectedConnection.prompts = nextPrompts.prompts;
885
- expectedConnection.promptDiscoveryFailed = false;
886
- }
887
- if (confirmed) delete expectedConnection.listenCatalogStale;
888
- else expectedConnection.listenCatalogStale = true;
889
- this.metadataListChangedListener?.(name, "listen-recovered");
890
- this.pendingMetadataPublications.delete(name);
891
- return confirmed;
892
- }
893
-
894
- async prepareResourceUse(name: string, uri: string, expectedConnection: ServerConnection): Promise<boolean> {
895
- if (this.connections.get(name) !== expectedConnection || expectedConnection.status !== "connected") return false;
896
- const refreshRead = expectedConnection.listenState === "dropped" ||
897
- expectedConnection.listenState === "re-establishing" ||
898
- expectedConnection.resourceReadRefreshUris?.has(uri) === true;
899
- const recent = expectedConnection.recentResourceUris ?? new Map<string, number>();
900
- recent.delete(uri);
901
- recent.set(uri, Date.now());
902
- while (recent.size > MAX_RESOURCE_SUBSCRIPTIONS) {
903
- const oldest = recent.keys().next().value as string | undefined;
904
- if (oldest === undefined) break;
905
- recent.delete(oldest);
906
- }
907
- expectedConnection.recentResourceUris = recent;
908
- await this.ensureListen(name, expectedConnection);
909
- expectedConnection.resourceReadRefreshUris?.delete(uri);
910
- return refreshRead;
911
- }
912
-
913
- registerResourceUpdatedListener(
914
- token: string,
915
- serverName: string,
916
- uri: string,
917
- listener: ResourceUpdatedListener,
918
- ): void {
919
- this.removeResourceUpdatedListener(token);
920
- this.resourceUpdatedListeners.set(token, { serverName, uri, listener });
921
- const connection = this.connections.get(serverName);
922
- if (!connection || connection.status !== "connected") return;
923
- void this.prepareResourceUse(serverName, uri, connection);
924
- }
925
-
926
- removeResourceUpdatedListener(token: string): void {
927
- this.resourceUpdatedListeners.delete(token);
928
- }
929
-
930
- private async doReconnect(
931
- name: string,
932
- definition: ServerDefinition,
933
- staleConnection: ServerConnection,
934
- signal?: AbortSignal,
935
- oauthAuthority?: OAuthAuthority,
936
- attemptOwner?: AbortController,
937
- ): Promise<ServerConnection> {
938
- throwIfAborted(signal);
939
- const current = this.connections.get(name);
940
-
941
- // Never tear down a connection we didn't prove stale: if the map no
942
- // longer holds the connection we were asked to replace, someone else
943
- // already reconnected (or connected) first.
944
- if (current !== staleConnection) {
945
- return current ?? this.connect(name, definition, signal);
946
- }
947
-
948
- // Build the replacement privately. The current route remains usable until
949
- // the candidate has completed its handshake and metadata discovery. A
950
- // failed candidate therefore cannot remove or close the last good route.
951
- const generation = this.closeGenerations.get(name) ?? 0;
952
- const credentialsInvalidated = staleConnection.status === "needs-auth"
953
- && staleConnection.credentialsInvalidated === true;
954
- const candidateAttempt = this.createConnection(
955
- name,
956
- definition,
957
- signal,
958
- signal,
959
- credentialsInvalidated,
960
- oauthAuthority,
961
- attemptOwner,
962
- );
963
- const fresh = definition.url
964
- ? await candidateAttempt.catch(async error => { throw await this.enrichHttpConnectionError(definition, error); })
965
- : await candidateAttempt;
966
-
967
- // An explicit close or a concurrent replacement supersedes this candidate.
968
- // Dispose only the candidate we own; never close whichever route is now
969
- // registered under the shared server name.
970
- if (signal?.aborted
971
- || this.reconnectAttempts.get(name) !== attemptOwner
972
- || (this.closeGenerations.get(name) ?? 0) !== generation) {
973
- await this.disposeConnection(fresh);
974
- throwIfAborted(signal);
975
- throw new Error(`MCP connection for ${name} was closed while reconnecting`);
976
- }
977
- const routeAtPublish = this.connections.get(name);
978
- if (routeAtPublish !== staleConnection) {
979
- await this.disposeConnection(fresh);
980
- return routeAtPublish ?? this.connect(name, definition, signal);
981
- }
982
-
983
- fresh.inFlight = Math.max(fresh.inFlight, staleConnection.inFlight);
984
- this.connections.set(name, fresh);
985
- this.watchListenSubscription(name, fresh, fresh.listenSubscription);
986
- if ([...this.resourceUpdatedListeners.values()].some(registration => registration.serverName === name)) {
987
- void this.ensureListen(name, fresh);
988
- }
989
-
990
- // Publish first so calls route to the fresh image while the exact displaced
991
- // child is terminated and reaped. Late close callbacks are identity-guarded.
992
- staleConnection.status = "closed";
993
- try {
994
- await this.disposeConnection(staleConnection);
995
- } catch (error) {
996
- const failures = error instanceof AggregateError ? error.errors : [error];
997
- const details = failures
998
- .map(failure => failure instanceof Error ? failure.message : String(failure))
999
- .join("; ");
1000
- logger.debug(`MCP: stale connection cleanup failed for ${name}: ${details}`);
1001
- }
1002
-
1003
- // Publication is not permission to return a route that close() disposed
1004
- // while stale cleanup was pending.
1005
- if ((this.closeGenerations.get(name) ?? 0) !== generation
1006
- || this.connections.get(name) !== fresh
1007
- || fresh.status === "closed") {
1008
- throw new Error(`MCP connection for ${name} was closed while reconnecting`);
1009
- }
1010
- return fresh;
1011
- }
1012
-
1013
- private async createConnection(
1014
- name: string,
1015
- definition: ServerDefinition,
1016
- signal?: AbortSignal,
1017
- requestSignal?: AbortSignal,
1018
- credentialsInvalidated = false,
1019
- oauthAuthority?: OAuthAuthority,
1020
- attemptOwner?: AbortController,
1021
- ): Promise<ServerConnection> {
1022
- throwIfAborted(signal);
1023
-
1024
- const tracingEnabled = isMcpTraceEnabled(definition, this.traceSettings);
1025
- const traceWriter = tracingEnabled
1026
- ? (this.traceWriter ??= createMcpTraceWriter(this.defaultCwd, this.traceSettings ?? {}))
1027
- : undefined;
1028
- const traceObserver: McpTraceObserver | undefined = traceWriter
1029
- ? { record: event => traceWriter.write(event) }
1030
- : undefined;
1031
-
1032
- let client: Client;
1033
- let transport: Transport;
1034
- let clientConnected = false;
1035
- let invalidated = credentialsInvalidated;
1036
- let transportAlreadyTraced = false;
1037
- let stderrTail: Buffer<ArrayBufferLike> = Buffer.alloc(0);
1038
- const configuredTransports = [definition.command, definition.url, definition.socket]
1039
- .filter(value => typeof value === "string" && value.length > 0);
1040
- if (configuredTransports.length !== 1) {
1041
- throw new Error(`Server ${name} must configure exactly one of command, url, or socket`);
1042
- }
1043
-
1044
- const requestOptions = this.buildRequestOptions(definition, requestSignal);
1045
-
1046
- if (definition.command) {
1047
- client = this.createClient(name, definition);
1048
- let command = resolveConfigPath(definition.command) ?? definition.command;
1049
- const literalArgs = isBuiltInAgentPlugin(definition, "args");
1050
- const literalCwd = isBuiltInAgentPlugin(definition, "cwd");
1051
- let args = literalArgs
1052
- ? [...(definition.args ?? [])]
1053
- : (definition.args ?? []).map((argument) => expandHomePath(interpolateEnvVars(argument)) ?? argument);
1054
- const cwd = (literalCwd ? expandHomePath(definition.cwd) : resolveConfigPath(definition.cwd)) ?? this.defaultCwd;
1055
- if (definition.pluginDataDir) mkdirSync(definition.pluginDataDir, { recursive: true });
1056
- if (cwd !== undefined) {
1057
- const cwdStats = statSync(cwd, { throwIfNoEntry: false });
1058
- if (!cwdStats) throw new Error(`MCP server "${name}" configured cwd does not exist: "${cwd}"`);
1059
- if (!cwdStats.isDirectory()) throw new Error(`MCP server "${name}" configured cwd is not a directory: "${cwd}"`);
1060
- }
1061
-
1062
- if (command === "npx" || command === "npm") {
1063
- const resolved = await resolveNpxBinary(command, args, signal);
1064
- if (resolved) {
1065
- command = resolved.isJs ? "node" : resolved.binPath;
1066
- args = resolved.isJs ? [resolved.binPath, ...resolved.extraArgs] : resolved.extraArgs;
1067
- logger.debug(`${name} resolved to ${resolved.binPath} (skipping npm parent)`);
1068
- }
1069
- }
1070
- throwIfAborted(signal);
1071
-
1072
- const stdioTransport = new StdioClientTransport({
1073
- command,
1074
- args,
1075
- env: resolveEnv(
1076
- definition.env,
1077
- name,
1078
- isBuiltInAgentPlugin(definition, "env") || definition.literalEnv === true,
1079
- definition.inheritEnv !== false,
1080
- ),
1081
- ...(cwd !== undefined ? { cwd } : {}),
1082
- stderr: definition.debug ? "inherit" : "pipe",
1083
- });
1084
- // Keep non-debug child diagnostics available for connection failures without
1085
- // retaining an unbounded stream or changing the existing debug behavior.
1086
- if (stdioTransport.stderr) {
1087
- stdioTransport.stderr.on("data", (chunk: Buffer | string) => {
1088
- stderrTail = appendStderrTail(stderrTail, chunk);
1089
- });
1090
- }
1091
- transport = stdioTransport;
1092
- } else if (definition.url) {
1093
- const httpConnection = await this.connectHttpClient(
1094
- definition,
1095
- name,
1096
- requestOptions,
1097
- signal,
1098
- traceObserver,
1099
- invalidated,
1100
- oauthAuthority,
1101
- attemptOwner,
1102
- );
1103
- client = httpConnection.client;
1104
- transport = httpConnection.transport;
1105
- invalidated = httpConnection.credentialsInvalidated;
1106
- if (httpConnection.status === "needs-auth") {
1107
- return {
1108
- client,
1109
- transport,
1110
- definition,
1111
- tools: [],
1112
- resources: [],
1113
- prompts: [],
1114
- lastUsedAt: Date.now(),
1115
- inFlight: 0,
1116
- status: "needs-auth",
1117
- listenState: "disconnected",
1118
- credentialsInvalidated: invalidated,
1119
- };
1120
- }
1121
- clientConnected = true;
1122
- transportAlreadyTraced = traceObserver !== undefined;
1123
- } else {
1124
- client = this.createClient(name, definition);
1125
- transport = new UnixSocketClientTransport(resolveConfigPath(definition.socket!)!);
1126
- }
1127
-
1128
- if (traceObserver && !transportAlreadyTraced) {
1129
- const traceTransportKindValue = traceTransportKind(definition, transport);
1130
- transport = wrapTransportWithMcpTrace(transport, name, traceTransportKindValue, traceObserver);
1131
- }
1132
-
1133
- try {
1134
- throwIfAborted(signal);
1135
- if (!clientConnected) {
1136
- await this.connectClientWithAbort(client, transport, requestOptions, signal);
1137
- }
1138
- this.attachAdapterNotificationHandlers(name, client);
1139
-
1140
- const instructions = client.getInstructions?.();
1141
- const protocolEra = client.getProtocolEra?.();
1142
- const autoOpenedSubscription = client.autoOpenedSubscription;
1143
- const connection: ServerConnection = {
1144
- client,
1145
- transport,
1146
- definition,
1147
- tools: [],
1148
- toolsRevision: 0,
1149
- resources: [],
1150
- prompts: [],
1151
- ...(instructions !== undefined ? { instructions } : {}),
1152
- lastUsedAt: Date.now(),
1153
- inFlight: 0,
1154
- status: "connected",
1155
- listenState: protocolEra === "modern"
1156
- ? autoOpenedSubscription
1157
- ? "active"
1158
- : "not-listening"
1159
- : "legacy",
1160
- ...(autoOpenedSubscription ? {
1161
- listenSubscription: autoOpenedSubscription,
1162
- } : {}),
1163
- };
1164
- if (autoOpenedSubscription) connection.listenFilter = this.catalogListenFilter(connection);
1165
-
1166
- // Reflect the SDK's own close signal in connection status, guarded by
1167
- // identity so a stale connection's late close can never clobber a fresh
1168
- // connection. The SDK client owns the transport callbacks.
1169
- client.onclose = () => {
1170
- if (connection.status === "closed") return;
1171
- connection.status = "closed";
1172
- if (this.connections.get(name) !== connection) return;
1173
- this.metadataListChangedListener?.(name, "remote-close");
1174
- };
1175
-
1176
- // Discover tools, resources, and prompts. Resource and prompt listing is
1177
- // optional: only servers advertising the capability are queried.
1178
- const [toolResult, resources, promptResult] = await Promise.all([
1179
- this.fetchAllTools(client, requestOptions),
1180
- this.fetchAllResources(client, requestOptions),
1181
- this.fetchAllPrompts(client, requestOptions),
1182
- ]);
1183
- if (connection.status !== "connected") {
1184
- throw new Error(`MCP connection for ${name} closed during metadata discovery`);
1185
- }
1186
- connection.tools = toolResult.tools;
1187
- connection.toolListHints = toolResult.hints;
1188
- connection.resources = resources.resources;
1189
- connection.resourceDiscoveryFailed = resources.failed;
1190
- connection.prompts = promptResult.prompts;
1191
- connection.promptDiscoveryFailed = promptResult.failed;
1192
-
1193
- if (definition.tasks !== false) {
1194
- try {
1195
- const attachment = await attachTaskSession({
1196
- client,
1197
- serverName: name,
1198
- definition,
1199
- transport,
1200
- requestTimeoutMs: this.getResolvedRequestTimeoutMs(definition),
1201
- clientInfo: { name: `pi-mcp-${name}`, version: "1.0.0" },
1202
- clientCapabilities: this.buildClientCapabilities(),
1203
- ...(this.elicitationConfig
1204
- ? {
1205
- onElicitation: (request: Parameters<typeof handleElicitationRequest>[1], signal?: AbortSignal) =>
1206
- handleElicitationRequest({
1207
- ...this.elicitationConfig!,
1208
- serverName: name,
1209
- onUrlAccepted: elicitationId => this.rememberUrlElicitation(name, elicitationId),
1210
- }, request, signal),
1211
- }
1212
- : {}),
1213
- ...(this.samplingConfig
1214
- ? {
1215
- onSampling: (request: Parameters<typeof handleSamplingRequest>[1], signal?: AbortSignal) =>
1216
- handleSamplingRequest({
1217
- ...this.samplingConfig!,
1218
- serverName: name,
1219
- // Cancelling the task should also stop the local sampling run.
1220
- getSignal: () => combineAbortSignals(this.samplingConfig!.getSignal(), signal),
1221
- }, request),
1222
- }
1223
- : {}),
1224
- });
1225
- if (attachment && connection.status === "connected") {
1226
- connection.taskSession = attachment.session;
1227
- connection.taskChannel = attachment.channel;
1228
- } else if (attachment) {
1229
- attachment.channel.rejectAll("MCP connection closed");
1230
- await attachment.session.close().catch(() => {});
1231
- }
1232
- } catch (error) {
1233
- logger.debug(`Task session attach failed for ${name}: ${String(error)}`);
1234
- }
1235
- }
1236
-
1237
- return connection;
1238
- } catch (error) {
1239
- // If connectClientWithAbort closed the transport, await that exact close.
1240
- // Otherwise the SDK client owns its transport and performs cleanup once.
1241
- const abortCleanup = abortCleanupPromises.get(transport);
1242
- const abortCleanupFailed = error instanceof AggregateError && error.message === "MCP connection abort cleanup failed";
1243
- const cleanupResults = abortCleanupFailed
1244
- ? []
1245
- : await Promise.allSettled([
1246
- abortCleanup ?? Promise.resolve().then(() => client.close()),
1247
- ]);
1248
- const cleanupFailures = cleanupResults.flatMap(result => result.status === "rejected" ? [result.reason] : []);
1249
- let reportedError: unknown = error;
1250
- if (cleanupFailures.length > 0) {
1251
- reportedError = new AggregateError([error, ...cleanupFailures], "MCP connection setup failed");
1252
- }
1253
-
1254
- // A cleanup failure remains a setup failure rather than being hidden
1255
- // behind needs-auth.
1256
- if (isUnauthorizedHttpError(error) && supportsOAuth(definition) && cleanupFailures.length === 0) {
1257
- if (!invalidated) {
1258
- invalidateAuthEntryCache(name);
1259
- invalidated = true;
1260
- }
1261
- return {
1262
- client,
1263
- transport,
1264
- definition,
1265
- tools: [],
1266
- resources: [],
1267
- prompts: [],
1268
- lastUsedAt: Date.now(),
1269
- inFlight: 0,
1270
- status: "needs-auth",
1271
- listenState: "disconnected",
1272
- credentialsInvalidated: invalidated,
1273
- };
1274
- }
1275
-
1276
- if (stderrTail.length > 0) {
1277
- const stderrText = stderrTail.toString("utf8").trim();
1278
- const lines = stderrText.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
1279
- if (lines.length > 0) {
1280
- const baseMessage = reportedError instanceof Error ? reportedError.message : String(reportedError);
1281
- const detail = lines.slice(-MAX_CAPTURED_STDERR_LINES).join(" — ");
1282
- throw new Error(`${baseMessage} (${detail})`, { cause: reportedError });
1283
- }
1284
- }
1285
- throw reportedError;
1286
- }
1287
- }
1288
-
1289
- private async enrichHttpConnectionError(definition: ServerDefinition, error: unknown): Promise<Error> {
1290
- const originalMessage = error instanceof Error ? error.message : String(error);
1291
- if (process.platform === "darwin") {
1292
- const codes = localNetworkFailureCodes(error);
1293
- if (codes.length > 0 && isLiteralLocalAddress(resolveServerUrl(definition)!)) {
1294
- return new Error(`${originalMessage} — ${codes.join(", ")} — macOS Local Network Privacy may be blocking access. Check System Settings > Privacy & Security > Local Network for the app hosting Pi; enable access if listed and restart it. Try launching Pi from Terminal.app or SSH. Routing or firewall problems can also cause this error.`, { cause: error });
1295
- }
1296
- }
1297
- if (isTransientHttpConnectError(error)) {
1298
- return new Error(`${originalMessage} — endpoint is temporarily unavailable (HTTP 503)`, { cause: error });
1299
- }
1300
- try {
1301
- const probe = await probeMcpEndpoint(resolveServerUrl(definition)!);
1302
- return new Error(`${originalMessage} — probe: ${probe.classification}`, { cause: error });
1303
- } catch {
1304
- return error instanceof Error ? error : new Error(originalMessage);
1305
- }
1306
- }
1307
-
1308
- private async connectClientWithAbort(
1309
- client: Client,
1310
- transport: Transport,
1311
- requestOptions?: RequestOptions,
1312
- signal?: AbortSignal,
1313
- ): Promise<void> {
1314
- throwIfAborted(signal);
1315
- let abortCleanup: Promise<void> | undefined;
1316
- const closeTransport = () => {
1317
- abortCleanup = Promise.resolve().then(() => transport.close());
1318
- abortCleanupPromises.set(transport, abortCleanup);
1319
- };
1320
- signal?.addEventListener("abort", closeTransport, { once: true });
1321
- try {
1322
- await abortable(client.connect(transport, requestOptions), signal);
1323
- await abortCleanup;
1324
- } catch (error) {
1325
- if (abortCleanup) {
1326
- try {
1327
- await abortCleanup;
1328
- } catch (cleanupError) {
1329
- throw new AggregateError([error, cleanupError], "MCP connection abort cleanup failed");
1330
- }
1331
- }
1332
- throw error;
1333
- } finally {
1334
- signal?.removeEventListener("abort", closeTransport);
1335
- }
1336
- }
1337
-
1338
- private buildClientCapabilities() {
1339
- return {
1340
- extensions: {
1341
- "io.modelcontextprotocol/ui": {
1342
- mimeTypes: [RESOURCE_MIME_TYPE],
1343
- },
1344
- },
1345
- ...(this.samplingConfig ? { sampling: {} } : {}),
1346
- ...(this.elicitationConfig
1347
- ? {
1348
- elicitation: {
1349
- form: {},
1350
- ...(this.elicitationConfig.allowUrl ? { url: {} } : {}),
1351
- },
1352
- }
1353
- : {}),
1354
- };
1355
- }
1356
-
1357
- private createClient(serverName: string, definition: ServerDefinition): Client {
1358
- const capabilities = this.buildClientCapabilities();
1359
- const versionNegotiation = resolveVersionNegotiation(definition);
1360
- let client: Client;
1361
- client = new Client(
1362
- { name: `pi-mcp-${serverName}`, version: "1.0.0" },
1363
- {
1364
- jsonSchemaValidator: createJsonSchemaValidator(),
1365
- ...(versionNegotiation ? { versionNegotiation } : {}),
1366
- ...(Object.keys(capabilities).length > 0 ? { capabilities } : {}),
1367
- listChanged: {
1368
- tools: {
1369
- onChanged: (error: Error | null, tools: McpTool[] | null) => {
1370
- this.handleToolsListChanged(serverName, client, error, tools);
1371
- },
1372
- },
1373
- resources: {
1374
- onChanged: (error: Error | null, resources: McpResource[] | null) => {
1375
- this.handleResourcesListChanged(serverName, client, error, resources);
1376
- },
1377
- },
1378
- prompts: {
1379
- onChanged: (error: Error | null, prompts: McpPrompt[] | null) => {
1380
- this.handlePromptsListChanged(serverName, client, error, prompts);
1381
- },
1382
- },
1383
- },
1384
- },
1385
- );
1386
- if (this.samplingConfig) {
1387
- registerSamplingHandler(client, { ...this.samplingConfig, serverName });
1388
- }
1389
- if (this.elicitationConfig) {
1390
- registerElicitationHandler(client, {
1391
- ...this.elicitationConfig,
1392
- serverName,
1393
- onUrlAccepted: elicitationId => this.rememberUrlElicitation(serverName, elicitationId),
1394
- });
1395
- if (this.elicitationConfig.allowUrl) {
1396
- client.setNotificationHandler("notifications/elicitation/complete", notification => {
1397
- if (this.runtimeSignal?.aborted) return;
1398
- const accepted = this.acceptedUrlElicitations.get(serverName);
1399
- if (!accepted?.delete(notification.params.elicitationId)) return;
1400
- this.elicitationConfig?.ui.notify(
1401
- `MCP browser interaction for ${serverName} completed. You can retry the tool now.`,
1402
- "info",
1403
- );
1404
- });
1405
- }
1406
- }
1407
- return client;
1408
- }
1409
-
1410
- private handleToolsListChanged(
1411
- serverName: string,
1412
- client: Client,
1413
- error: Error | null,
1414
- tools: McpTool[] | null,
1415
- ): void {
1416
- if (error) {
1417
- logger.debug(`MCP: tools/list_changed refresh failed for ${serverName}: ${error.message}`);
1418
- return;
1419
- }
1420
- if (!tools) return;
1421
- const connection = this.connections.get(serverName);
1422
- if (!connection || connection.client !== client || connection.status !== "connected") return;
1423
- connection.tools = tools;
1424
- connection.toolsRevision = (connection.toolsRevision ?? 0) + 1;
1425
- this.metadataListChangedListener?.(serverName, "tools-list-changed");
1426
- this.pendingMetadataPublications.delete(serverName);
1427
- }
1428
-
1429
- private handlePromptsListChanged(
1430
- serverName: string,
1431
- client: Client,
1432
- error: Error | null,
1433
- prompts: McpPrompt[] | null,
1434
- ): void {
1435
- if (error) {
1436
- logger.debug(`MCP: prompts/list_changed refresh failed for ${serverName}: ${error.message}`);
1437
- return;
1438
- }
1439
- if (!prompts) return;
1440
- const connection = this.connections.get(serverName);
1441
- if (!connection || connection.client !== client || connection.status !== "connected") return;
1442
- connection.prompts = prompts;
1443
- connection.promptDiscoveryFailed = false;
1444
- this.metadataListChangedListener?.(serverName, "prompts-list-changed");
1445
- this.pendingMetadataPublications.delete(serverName);
1446
- }
1447
-
1448
- private handleResourcesListChanged(
1449
- serverName: string,
1450
- client: Client,
1451
- error: Error | null,
1452
- resources: McpResource[] | null,
1453
- ): void {
1454
- if (error) {
1455
- logger.debug(`MCP: resources/list_changed refresh failed for ${serverName}: ${error.message}`);
1456
- return;
1457
- }
1458
- if (!resources) return;
1459
- const connection = this.connections.get(serverName);
1460
- if (!connection || connection.client !== client || connection.status !== "connected") return;
1461
- connection.resources = resources;
1462
- connection.resourceDiscoveryFailed = false;
1463
- this.metadataListChangedListener?.(serverName, "resources-list-changed");
1464
- this.pendingMetadataPublications.delete(serverName);
1465
- }
1466
-
1467
- async handleUrlElicitationRequired(
1468
- serverName: string,
1469
- error: UrlElicitationRequiredError,
1470
- ): Promise<"accept" | "decline" | "cancel"> {
1471
- if (this.runtimeSignal?.aborted || !this.elicitationConfig?.allowUrl) return "cancel";
1472
- for (const params of error.elicitations) {
1473
- const result = await handleUrlElicitation({
1474
- ...this.elicitationConfig,
1475
- serverName,
1476
- onUrlAccepted: elicitationId => this.rememberUrlElicitation(serverName, elicitationId),
1477
- }, params);
1478
- if (result.action !== "accept") return result.action;
1479
- }
1480
- return "accept";
1481
- }
1482
-
1483
- private rememberUrlElicitation(serverName: string, elicitationId: string): void {
1484
- if (this.runtimeSignal?.aborted) return;
1485
- let accepted = this.acceptedUrlElicitations.get(serverName);
1486
- if (!accepted) {
1487
- accepted = new Set();
1488
- this.acceptedUrlElicitations.set(serverName, accepted);
1489
- }
1490
- accepted.add(elicitationId);
1491
- }
1492
-
1493
- private async connectHttpClient(
1494
- definition: ServerDefinition,
1495
- serverName: string,
1496
- requestOptions: RequestOptions | undefined,
1497
- signal?: AbortSignal,
1498
- traceObserver?: McpTraceObserver,
1499
- credentialsInvalidated = false,
1500
- oauthAuthority?: OAuthAuthority,
1501
- attemptOwner?: AbortController,
1502
- ): Promise<{ client: Client; transport: Transport; status: "connected" | "needs-auth"; credentialsInvalidated: boolean }> {
1503
- throwIfAborted(signal);
1504
- const serverUrl = resolveServerUrl(definition)!;
1505
- const url = new URL(serverUrl);
1506
-
1507
- // Resolve secret commands only for this connection attempt, without
1508
- // mutating the persisted configuration.
1509
- const literalHeaders = isBuiltInAgentPlugin(definition, "headers");
1510
- const hasCommandHeader = !literalHeaders && Object.values(definition.headers ?? {})
1511
- .some(value => value.startsWith("!") && !value.startsWith("!!"));
1512
- const oauthEnabled = supportsOAuth(definition);
1513
- let headers: Record<string, string>;
1514
- if (literalHeaders) {
1515
- headers = { ...definition.headers };
1516
- } else if (oauthEnabled) {
1517
- headers = Object.fromEntries(resolveOAuthHeaders(definition.headers));
1518
- } else {
1519
- headers = resolveCommandSecretsRecord(
1520
- definition.headers,
1521
- key => `MCP server "${serverName}" HTTP header "${key}"`,
1522
- ) ?? {};
1523
- }
1524
-
1525
- // Resolve bearer auth before creating requestInit so every attempted
1526
- // transport receives the same headers.
1527
- const commandBearer = definition.bearerToken?.startsWith("!") && !definition.bearerToken.startsWith("!!")
1528
- ? definition.bearerToken
1529
- : undefined;
1530
- // Command-backed bearers resolve eagerly, then refresh through a TTL cache.
1531
- let bearerCommandResolver: BearerCommandResolver | undefined;
1532
- if (definition.auth === "bearer") {
1533
- if (commandBearer) {
1534
- bearerCommandResolver = new BearerCommandResolver(
1535
- commandBearer,
1536
- `MCP server "${serverName}" HTTP bearer token`,
1537
- );
1538
- // Eager resolve so a broken command surfaces at connect time, not at
1539
- // the first tool call.
1540
- await bearerCommandResolver.resolve(signal);
1541
- } else {
1542
- const token = resolveBearerToken(definition)
1543
- ?? (definition.bearerToken === undefined && definition.bearerTokenEnv === undefined && definition.bearerTokenStore === true
1544
- ? getBearerTokenForUrl(serverName, serverUrl)
1545
- : undefined);
1546
- if (token) headers["Authorization"] = `Bearer ${token}`;
1547
- }
1548
- }
1549
-
1550
- if (hasCommandHeader || commandBearer) {
1551
- try {
1552
- new Headers(headers);
1553
- } catch {
1554
- throw new Error(`Failed to resolve MCP server "${serverName}" HTTP command secret: command returned an invalid header value`);
1555
- }
1556
- }
1557
-
1558
- // Do not give origin-bound headers to SDK requestInit: it reuses those
1559
- // defaults for discovered OAuth endpoints, including other origins.
1560
- const requestInit = !oauthEnabled && Object.keys(headers).length > 0 ? { headers } : undefined;
1561
- const serviceHeaders = oauthEnabled ? new Headers(headers) : new Headers();
1562
- let caFetch = createCaFetch(definition);
1563
- try {
1564
- const createAuthProvider = (): McpOAuthProvider => {
1565
- const currentConnectAttempt = this.connectAttempts.get(serverName);
1566
- const currentReconnectAttempt = this.reconnectAttempts.get(serverName);
1567
- if ((currentConnectAttempt && currentConnectAttempt !== attemptOwner)
1568
- || (currentReconnectAttempt && currentReconnectAttempt !== attemptOwner)) {
1569
- throw new Error(`MCP connection for ${serverName} was replaced while connecting`);
1570
- }
1571
- if (!oauthAuthority) throw new Error(`Missing OAuth authority for ${serverName}`);
1572
- const provider = new McpOAuthProvider(
1573
- serverName,
1574
- serverUrl,
1575
- extractOAuthConfig(definition),
1576
- { onRedirect: async () => {} },
1577
- this.authStorageOptions,
1578
- this.oauthRuntime?.signal,
1579
- undefined,
1580
- oauthAuthority,
1581
- );
1582
- provider.setAuthFetch(createOAuthFetch(serverUrl, () => serviceHeaders,
1583
- combineAbortSignals(this.oauthRuntime?.signal, signal), {
1584
- ...(caFetch ? { delegate: caFetch.fetch } : {}),
1585
- }));
1586
- return provider;
1587
- };
1588
-
1589
- // Explicit OAuth checks secure storage immediately. Implicit OAuth keeps
1590
- // anonymous servers provider-free unless URL-bound credentials are already
1591
- // stored, so an unavailable credential store does not break anonymous use.
1592
- let implicitStoredAuth: ReturnType<typeof inspectAuthForUrl> | undefined;
1593
- if (definition.auth === undefined && supportsOAuth(definition)) {
1594
- try {
1595
- implicitStoredAuth = inspectAuthForUrl(serverName, serverUrl, this.authStorageOptions);
1596
- } catch {
1597
- // Implicit preflight is opportunistic; malformed records must not block
1598
- // an otherwise anonymous-capable server from connecting.
1599
- }
1600
- }
1601
- const hasImplicitStoredTokens = implicitStoredAuth?.status === "present"
1602
- && implicitStoredAuth.entry.tokens !== undefined;
1603
- if (hasImplicitStoredTokens) invalidateAuthEntryCache(serverName);
1604
- let authState: HttpAuthProviderState = supportsOAuth(definition)
1605
- ? definition.auth === undefined
1606
- ? hasImplicitStoredTokens
1607
- ? { status: "implicit-stored", provider: createAuthProvider() }
1608
- : { status: "implicit-deferred" }
1609
- : { status: "explicit", provider: createAuthProvider() }
1610
- : { status: "disabled" };
1611
-
1612
- const commandFetch = definition.requestHeadersCommand
1613
- ? createRequestHeadersCommandFetch(definition.requestHeadersCommand, caFetch?.fetch)
1614
- : caFetch?.fetch;
1615
- // requestHeadersCommand stays last in the header chain.
1616
- const bearerFetch = bearerCommandResolver
1617
- ? createBearerCommandFetch(bearerCommandResolver, commandFetch)
1618
- : commandFetch;
1619
- const requestFetch = oauthEnabled
1620
- ? createOAuthFetch(serverUrl, () => serviceHeaders, this.oauthRuntime?.signal, {
1621
- // MCP streams outlive individual auth requests; retain SDK request deadlines.
1622
- timeout: false,
1623
- ...(bearerFetch ? { delegate: bearerFetch } : {}),
1624
- })
1625
- : bearerFetch;
1626
- const attempt = async (
1627
- kind: "streamable-http" | "sse",
1628
- ): Promise<
1629
- | { status: "connected"; client: Client; transport: Transport }
1630
- | { status: "failed"; client: Client; transport: Transport; error: unknown }
1631
- > => {
1632
- const authProvider = "provider" in authState ? authState.provider : undefined;
1633
- let sseFetchFailure: unknown;
1634
- const transportFetch: FetchLike | undefined = kind === "sse" && process.platform === "darwin" && isLiteralLocalAddress(serverUrl)
1635
- ? async (input, init) => {
1636
- try {
1637
- return await (requestFetch ?? globalThis.fetch)(input, init);
1638
- } catch (error) {
1639
- // EventSource discards the fetch cause before the SDK creates SseError.
1640
- if (localNetworkFailureCodes(error).length > 0) sseFetchFailure = error;
1641
- throw error;
1642
- }
1643
- }
1644
- : requestFetch;
1645
- const transportOptions = {
1646
- ...(requestInit !== undefined ? { requestInit } : {}),
1647
- ...(transportFetch !== undefined ? { fetch: transportFetch } : {}),
1648
- ...(authProvider !== undefined ? { authProvider } : {}),
1649
- ...(authProvider !== undefined
1650
- && definition.oauth !== false
1651
- && definition.oauth?.skipIssuerMetadataValidation === true
1652
- ? { skipIssuerMetadataValidation: true }
1653
- : {}),
1654
- };
1655
- const baseTransport: Transport = kind === "streamable-http"
1656
- ? new StreamableHTTPClientTransport(url, transportOptions)
1657
- : new SSEClientTransport(url, transportOptions);
1658
- const transport = traceObserver
1659
- ? wrapTransportWithMcpTrace(baseTransport, serverName, kind, traceObserver)
1660
- : baseTransport;
1661
- const client = this.createClient(serverName, definition);
1662
-
1663
- try {
1664
- await this.connectClientWithAbort(client, transport, requestOptions, signal);
1665
- return { status: "connected", client, transport };
1666
- } catch (error) {
1667
- if (error instanceof SseError && sseFetchFailure !== undefined) {
1668
- error = new AggregateError([error, sseFetchFailure], error.message);
1669
- }
1670
- const abortCleanupFailed = error instanceof AggregateError
1671
- && error.message === "MCP connection abort cleanup failed";
1672
- if (!abortCleanupFailed) {
1673
- try {
1674
- await (abortCleanupPromises.get(transport) ?? client.close());
1675
- } catch (cleanupError) {
1676
- throw new AggregateError([error, cleanupError], "MCP HTTP connection cleanup failed");
1677
- }
1678
- }
1679
- return { status: "failed", client, transport, error };
1680
- }
1681
- };
1682
-
1683
- // Connect the real client once. Retry Streamable HTTP only for an implicit
1684
- // OAuth challenge; use SSE only for definitive endpoint incompatibility.
1685
- // Agent Plugins set httpTransport, and their declared transport is used without fallback.
1686
- let kind: "streamable-http" | "sse" = definition.httpTransport ?? "streamable-http";
1687
- let invalidated = credentialsInvalidated;
1688
- for (;;) {
1689
- const result = await attempt(kind);
1690
- if (result.status === "connected") {
1691
- const ownedCa = caFetch;
1692
- if (ownedCa) {
1693
- const close = result.transport.close.bind(result.transport);
1694
- const onclose = result.transport.onclose;
1695
- result.transport.onclose = () => {
1696
- void ownedCa.close().catch(error => {
1697
- logger.debug(`MCP: CA dispatcher cleanup failed for ${serverName}: ${String(error)}`);
1698
- });
1699
- onclose?.();
1700
- };
1701
- result.transport.close = async () => {
1702
- try { await close(); } finally { await ownedCa.close(); }
1703
- };
1704
- caFetch = undefined;
1705
- }
1706
- return { ...result, credentialsInvalidated: invalidated };
1707
- }
1708
- if (result.error instanceof AggregateError
1709
- && result.error.message === "MCP connection abort cleanup failed") {
1710
- throw result.error;
1711
- }
1712
- if (signal?.aborted) throwIfAborted(signal);
1713
-
1714
- if (authState.status === "implicit-deferred" && isUnauthorizedHttpError(result.error)) {
1715
- authState = { status: "implicit-challenged", provider: createAuthProvider() };
1716
- continue;
1717
- }
1718
- if (isUnauthorizedHttpError(result.error)) {
1719
- if (supportsOAuth(definition)) {
1720
- if (!invalidated) {
1721
- invalidateAuthEntryCache(serverName);
1722
- invalidated = true;
1723
- }
1724
- return {
1725
- client: result.client,
1726
- transport: result.transport,
1727
- status: "needs-auth",
1728
- credentialsInvalidated: invalidated,
1729
- };
1730
- }
1731
- throw result.error;
1732
- }
1733
-
1734
- if (definition.httpTransport === undefined && kind === "streamable-http" && shouldFallbackToSse(result.error, definition)) {
1735
- kind = "sse";
1736
- continue;
1737
- }
1738
- throw result.error;
1739
- }
1740
- } finally {
1741
- await caFetch?.close();
1742
- }
1743
- }
1744
-
1745
- private async fetchAllTools(client: Client, requestOptions?: CacheableRequestOptions): Promise<ToolListResult> {
1746
- const allTools: McpTool[] = [];
1747
- let cursor: string | undefined;
1748
- let hints: ToolListCacheHints | undefined;
1749
- let firstPage = true;
1750
-
1751
- do {
1752
- const result = await client.listTools(cursor ? { cursor } : undefined, requestOptions);
1753
- if (firstPage) {
1754
- const ttlMs = typeof result.ttlMs === "number" && Number.isSafeInteger(result.ttlMs) && result.ttlMs >= 0
1755
- ? result.ttlMs
1756
- : undefined;
1757
- const cacheScope = result.cacheScope === "public" || result.cacheScope === "private"
1758
- ? result.cacheScope
1759
- : undefined;
1760
- if (ttlMs !== undefined || cacheScope !== undefined) {
1761
- hints = {
1762
- ...(ttlMs !== undefined ? { ttlMs } : {}),
1763
- ...(cacheScope !== undefined ? { cacheScope } : {}),
1764
- };
1765
- }
1766
- firstPage = false;
1767
- }
1768
- allTools.push(...(result.tools ?? []));
1769
- cursor = result.nextCursor;
1770
- } while (cursor);
1771
-
1772
- return { tools: allTools, ...(hints !== undefined ? { hints } : {}) };
1773
- }
1774
-
1775
- private async fetchAllPrompts(
1776
- client: Client,
1777
- requestOptions?: RequestOptions,
1778
- ): Promise<{ prompts: McpPrompt[]; failed: boolean }> {
1779
- const capabilities = client.getServerCapabilities?.();
1780
- if (!capabilities?.prompts) return { prompts: [], failed: false };
1781
-
1782
- try {
1783
- const prompts: McpPrompt[] = [];
1784
- let cursor: string | undefined;
1785
- do {
1786
- const result = await client.listPrompts(cursor ? { cursor } : undefined, requestOptions);
1787
- prompts.push(...(result.prompts ?? []));
1788
- cursor = result.nextCursor;
1789
- } while (cursor);
1790
- return { prompts, failed: false };
1791
- } catch (error) {
1792
- if (requestOptions?.signal?.aborted) throwIfAborted(requestOptions.signal);
1793
- if (isUnauthorizedHttpError(error)) throw error;
1794
- const message = error instanceof Error ? error.message : String(error);
1795
- logger.debug(`MCP: prompts/list failed: ${message}`);
1796
- return { prompts: [], failed: true };
1797
- }
1798
- }
1799
-
1800
- private async fetchAllResources(client: Client, requestOptions?: RequestOptions, strict = false): Promise<ResourceListResult> {
1801
- const capabilities = client.getServerCapabilities?.();
1802
- if (!capabilities?.resources) return { resources: [], failed: false };
1803
-
1804
- try {
1805
- const allResources: McpResource[] = [];
1806
- let cursor: string | undefined;
1807
-
1808
- do {
1809
- const result = await client.listResources(cursor ? { cursor } : undefined, requestOptions);
1810
- allResources.push(...(result.resources ?? []));
1811
- cursor = result.nextCursor;
1812
- } while (cursor);
1813
-
1814
- return { resources: allResources, failed: false };
1815
- } catch (error) {
1816
- if (requestOptions?.signal?.aborted) {
1817
- throwIfAborted(requestOptions.signal);
1818
- }
1819
- if (isUnauthorizedHttpError(error)) throw error;
1820
- if (strict) throw error;
1821
- // The server advertises resources but the listing failed
1822
- return { resources: [], failed: true };
1823
- }
1824
- }
1825
-
1826
- private attachAdapterNotificationHandlers(serverName: string, client: Client): void {
1827
- client.setNotificationHandler("notifications/resources/updated", notification => {
1828
- const uri = notification.params.uri;
1829
- const connection = this.connections.get(serverName);
1830
- if (!connection || connection.client !== client || connection.status !== "connected") return;
1831
- for (const registration of this.resourceUpdatedListeners.values()) {
1832
- if (registration.serverName === serverName && registration.uri === uri) {
1833
- try {
1834
- registration.listener(serverName, uri);
1835
- } catch {
1836
- // One UI listener must not block resource invalidation for others.
1837
- }
1838
- }
1839
- }
1840
- });
1841
- client.setNotificationHandler(
1842
- SERVER_STREAM_RESULT_PATCH_METHOD,
1843
- { params: serverStreamResultPatchNotificationSchema.shape.params },
1844
- params => {
1845
- const listener = this.uiStreamListeners.get(params.streamToken);
1846
- if (!listener) return;
1847
- listener(serverName, params);
1848
- },
1849
- );
1850
- }
1851
-
1852
- registerUiStreamListener(streamToken: string, listener: UiStreamListener): void {
1853
- this.uiStreamListeners.set(streamToken, listener);
1854
- }
1855
-
1856
- removeUiStreamListener(streamToken: string): void {
1857
- this.uiStreamListeners.delete(streamToken);
1858
- }
1859
-
1860
- async getPrompt(
1861
- name: string,
1862
- promptName: string,
1863
- args?: Record<string, string>,
1864
- signal?: AbortSignal,
1865
- ): Promise<GetPromptResult> {
1866
- const connection = this.connections.get(name);
1867
- if (!connection || connection.status !== "connected") {
1868
- throw new Error(`Server "${name}" is not connected`);
1869
- }
1870
- try {
1871
- this.touch(name);
1872
- this.incrementInFlight(name);
1873
- await this.ensureListen(name, connection);
1874
- return await connection.client.getPrompt(
1875
- { name: promptName, ...(args ? { arguments: args } : {}) },
1876
- this.getRequestOptions(name, signal),
1877
- );
1878
- } finally {
1879
- this.decrementInFlight(name);
1880
- this.touch(name);
1881
- }
1882
- }
1883
-
1884
- async readResource(name: string, uri: string, signal?: AbortSignal): Promise<ReadResourceResult> {
1885
- if (isServerDisabled(this.connections.get(name)?.definition)) {
1886
- throw new Error(`MCP server "${name}" is disabled`);
1887
- }
1888
- const connection = this.connections.get(name);
1889
- if (!connection || connection.status !== "connected") {
1890
- throw new Error(`Server "${name}" is not connected`);
1891
- }
1892
-
1893
- try {
1894
- this.touch(name);
1895
- this.incrementInFlight(name);
1896
- const refreshRead = await this.prepareResourceUse(name, uri, connection);
1897
- const requestOptions = this.getRequestOptions(name, signal);
1898
- return await connection.client.readResource(
1899
- { uri },
1900
- refreshRead ? { ...requestOptions, cacheMode: "refresh" } : requestOptions,
1901
- );
1902
- } finally {
1903
- this.decrementInFlight(name);
1904
- this.touch(name);
1905
- }
1906
- }
1907
-
1908
- async close(name: string): Promise<void> {
1909
- this.closeGenerations.set(name, (this.closeGenerations.get(name) ?? 0) + 1);
1910
- this.connectAttempts.get(name)?.abort(new Error(`MCP connection ${name} was closed`));
1911
- this.reconnectAttempts.get(name)?.abort(new Error(`MCP connection ${name} was closed`));
1912
- this.pendingMetadataPublications.delete(name);
1913
-
1914
- const pendingReconnect = this.reconnectPromises.get(name);
1915
- const connection = this.connections.get(name);
1916
- if (!connection) {
1917
- const pendingClose = this.closePromises.get(name);
1918
- if (pendingClose) {
1919
- await pendingClose;
1920
- return;
1921
- }
1922
- const pendingConnect = this.connectPromises.get(name);
1923
- for (const pending of [pendingConnect, pendingReconnect]) {
1924
- if (!pending) continue;
1925
- try {
1926
- await pending;
1927
- } catch (error) {
1928
- if (this.containsCleanupFailure(error)) throw error;
1929
- }
1930
- }
1931
- return;
1932
- }
1933
-
1934
- // Delete before awaiting SDK cleanup so a replacement cannot be removed by
1935
- // an old close operation finishing later.
1936
- connection.status = "closed";
1937
- this.connections.delete(name);
1938
- this.acceptedUrlElicitations.delete(name);
1939
- const closing = this.disposeConnection(connection).finally(() => {
1940
- if (this.closePromises.get(name) === closing) this.closePromises.delete(name);
1941
- });
1942
- this.closePromises.set(name, closing);
1943
- await closing;
1944
- if (pendingReconnect) {
1945
- try {
1946
- await pendingReconnect;
1947
- } catch (error) {
1948
- if (this.containsCleanupFailure(error)) throw error;
1949
- }
1950
- }
1951
- }
1952
-
1953
- private async disposeConnection(connection: ServerConnection): Promise<void> {
1954
- const results = await Promise.allSettled([
1955
- // Release ext-tasks state first so its SDK adapter detaches before close.
1956
- Promise.resolve().then(async () => {
1957
- connection.taskChannel?.rejectAll("MCP connection closed");
1958
- await connection.taskSession?.close();
1959
- }).catch(() => {}),
1960
- // Only client.close() is needed; the client owns the transport and will close it internally.
1961
- Promise.resolve().then(() => connection.client.close()),
1962
- this.traceWriter?.flush() ?? Promise.resolve(),
1963
- ]);
1964
- const failures = results.flatMap(result => result.status === "rejected" ? [result.reason] : []);
1965
- if (failures.length > 0) throw new AggregateError(failures, "MCP connection cleanup failed");
1966
- }
1967
-
1968
- async closeAll(): Promise<void> {
1969
- this.stopped = true;
1970
- const names = new Set([
1971
- ...this.connections.keys(),
1972
- ...this.connectPromises.keys(),
1973
- ...this.reconnectPromises.keys(),
1974
- ]);
1975
- for (const name of names) {
1976
- this.closeGenerations.set(name, (this.closeGenerations.get(name) ?? 0) + 1);
1977
- this.connectAttempts.get(name)?.abort(new Error(`MCP connection ${name} was closed`));
1978
- this.reconnectAttempts.get(name)?.abort(new Error(`MCP connection ${name} was closed`));
1979
- }
1980
-
1981
- const pendingConnects = [...this.connectPromises.values(), ...this.reconnectPromises.values()];
1982
- const currentNames = [...this.connections.keys()];
1983
- const pendingResults = await Promise.allSettled(pendingConnects);
1984
- const results = await Promise.allSettled(currentNames.map(name => this.close(name)));
1985
-
1986
- // A connect that resolved during the first close snapshot is still fenced;
1987
- // close any handle that was already inserted before its attempt settled.
1988
- const lateNames = [...this.connections.keys()];
1989
- const lateResults = await Promise.allSettled(lateNames.map(name => this.close(name)));
1990
- const failures = [...pendingResults, ...results, ...lateResults]
1991
- .flatMap(result => result.status === "rejected" ? [result.reason] : [])
1992
- .filter(error => this.containsCleanupFailure(error));
1993
- this.uiStreamListeners.clear();
1994
- this.resourceUpdatedListeners.clear();
1995
- this.acceptedUrlElicitations.clear();
1996
- this.pendingMetadataPublications.clear();
1997
- this.samplingConfig = undefined;
1998
- this.elicitationConfig = undefined;
1999
- await this.traceWriter?.flush();
2000
- if (failures.length > 0) throw new AggregateError(failures, "MCP manager cleanup failed");
2001
- }
2002
-
2003
- private containsCleanupFailure(error: unknown): boolean {
2004
- const pending: unknown[] = [error];
2005
- const seen = new Set<unknown>();
2006
- while (pending.length > 0) {
2007
- const current = pending.pop();
2008
- if (!(current instanceof Error) || seen.has(current)) continue;
2009
- seen.add(current);
2010
- if (current instanceof AggregateError) {
2011
- if (/cleanup failed|setup failed/.test(current.message)) return true;
2012
- pending.push(...current.errors);
2013
- }
2014
- if (current.cause !== undefined) pending.push(current.cause);
2015
- }
2016
- return false;
2017
- }
2018
-
2019
- isConnecting(name: string): boolean {
2020
- return this.connectPromises.has(name);
2021
- }
2022
-
2023
- getConnection(name: string): ServerConnection | undefined {
2024
- return this.connections.get(name);
2025
- }
2026
-
2027
- getAllConnections(): Map<string, ServerConnection> {
2028
- return new Map(this.connections);
2029
- }
2030
-
2031
- touch(name: string): void {
2032
- const connection = this.connections.get(name);
2033
- if (connection) {
2034
- connection.lastUsedAt = Date.now();
2035
- }
2036
- }
2037
-
2038
- incrementInFlight(name: string): void {
2039
- const connection = this.connections.get(name);
2040
- if (connection) {
2041
- connection.inFlight = (connection.inFlight ?? 0) + 1;
2042
- }
2043
- }
2044
-
2045
- decrementInFlight(name: string): void {
2046
- const connection = this.connections.get(name);
2047
- if (connection && connection.inFlight) {
2048
- connection.inFlight--;
2049
- }
2050
- }
2051
-
2052
- isIdle(name: string, timeoutMs: number): boolean {
2053
- const connection = this.connections.get(name);
2054
- if (!connection || connection.status !== "connected") return false;
2055
- if (connection.inFlight > 0) return false;
2056
- return (Date.now() - connection.lastUsedAt) > timeoutMs;
2057
- }
2058
- }
2059
-
2060
- /**
2061
- * Resolve environment variables with interpolation.
2062
- */
2063
- function resolveEnv(
2064
- env: Record<string, string> | undefined,
2065
- serverName: string,
2066
- literalEnv = false,
2067
- inheritEnv = true,
2068
- ): Record<string, string> {
2069
- const resolved: Record<string, string> = {};
2070
- if (inheritEnv) {
2071
- for (const [key, value] of Object.entries(process.env)) {
2072
- if (value !== undefined) resolved[key] = value;
2073
- }
2074
- }
2075
- if (literalEnv) return env ? { ...resolved, ...env } : resolved;
2076
-
2077
- const overrides = resolveCommandSecretsRecord(
2078
- env,
2079
- key => `MCP server "${serverName}" stdio env "${key}"`,
2080
- );
2081
- return overrides ? { ...resolved, ...overrides } : resolved;
2082
- }
2083
-
2084
- function normalizeRequestTimeoutMs(timeoutMs: number | undefined): number | undefined {
2085
- return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0
2086
- ? timeoutMs
2087
- : undefined;
2088
- }