@chroxy/server 0.10.0 → 0.11.10

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 (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -1,30 +1,40 @@
1
1
  /**
2
- * MCP child-process lifecycle for the claude-byok provider (#4077).
2
+ * MCP client lifecycle for the claude-byok provider (#4077, #6821).
3
3
  *
4
- * One MCPClient owns one MCP server child. Handles spawn, JSON-RPC handshake
5
- * (initialize → initialized → tools/list), crash detection with exponential
6
- * backoff between restart attempts (1s/2s/4s, #4453), and SIGTERM/SIGKILL
7
- * grace on destroy.
4
+ * Two transports live here behind one interface (state / tools / start() /
5
+ * callTool() / destroy() + the same state/ready/dead events):
8
6
  *
9
- * Per #4077 scope:
10
- * - Lazy spawn: caller decides when to call start().
11
- * - Crash detection on child exit / spawn error → schedule restart per the
12
- * RESTART_BACKOFF_MS schedule (1s/2s/4s).
13
- * - After MAX_RESTART_ATTEMPTS failures, state=dead and tools=[].
14
- * - Session destroy sends SIGTERM, escalates to SIGKILL at KILL_GRACE_MS.
7
+ * - MCPClient — stdio: owns one MCP server CHILD PROCESS. Handles
8
+ * spawn, JSON-RPC handshake (initialize → initialized → tools/list), crash
9
+ * detection with exponential backoff between restart attempts (1s/2s/4s,
10
+ * #4453), and SIGTERM/SIGKILL grace on destroy.
11
+ * - MCPRemoteClient — network (#6821): speaks the MCP Streamable HTTP
12
+ * transport (POST JSON-RPC to a url, honour the Mcp-Session-Id header,
13
+ * read an SSE-upgraded response when the server streams one) with a
14
+ * legacy HTTP+SSE fallback for `type: 'sse'` servers. No child process,
15
+ * so the process-restart model does not apply — a network client makes a
16
+ * single connect attempt and surfaces a clear status on failure (notably
17
+ * `oauth-required` on a 401, deferred to #6822).
18
+ *
19
+ * `createMcpClient(config, opts)` picks the transport from the config shape
20
+ * (a `url` selects the remote client) so the fleet stays transport-agnostic.
15
21
  *
16
22
  * Out of scope (next stages):
17
23
  * - Materializing into Anthropic SDK tools[] (#4078).
18
24
  */
19
25
 
20
26
  import { spawn } from 'node:child_process'
27
+ import { lookup } from 'node:dns/promises'
21
28
  import { EventEmitter } from 'node:events'
22
29
  import { readFileSync } from 'node:fs'
23
30
  import { fileURLToPath } from 'node:url'
24
31
  import { dirname, join } from 'node:path'
25
32
  import { createLogger } from './logger.js'
26
- import { CHROXY_SECRET_DENYLIST } from './utils/spawn-env.js'
33
+ import { isBlockedMetadataHost } from './byok-mcp-config.js'
34
+ import { CHROXY_SECRET_DENYLIST, stripInheritedChroxySecrets, stripParentClaudeSessionEnv } from './utils/spawn-env.js'
27
35
  import { prepareSpawn } from './utils/win-spawn.js'
36
+ import * as realOAuthFlow from './byok-mcp-oauth.js'
37
+ import * as realOAuthStore from './byok-mcp-oauth-store.js'
28
38
 
29
39
  // #4453: exponential restart backoff. The first restart still fires at ~1s
30
40
  // after the death (no regression on the existing acceptance test); the
@@ -97,8 +107,8 @@ export class MCPClient extends EventEmitter {
97
107
  this._config = config
98
108
  this._log = opts.log || createLogger('byok-mcp')
99
109
  // #4457: optional async gate consulted before EACH start() (not each
100
- // restart — a trust decision applies to the whole (name, command, args[0])
101
- // tuple, which doesn't change between restart attempts). Returns true →
110
+ // restart — a trust decision applies to the whole spawn config (#7001),
111
+ // which doesn't change between restart attempts). Returns true →
102
112
  // proceed; false → state=DEAD permanently, no child is ever spawned.
103
113
  this._trustGate = opts.trustGate || null
104
114
  // #4454: per-instance handshake timeout. Precedence (high → low):
@@ -115,6 +125,17 @@ export class MCPClient extends EventEmitter {
115
125
  DEFAULT_HANDSHAKE_TIMEOUT_MS
116
126
  this._state = MCP_STATES.IDLE
117
127
  this._tools = []
128
+ // #6823: MCP prompts + resources, populated after tools/list during the
129
+ // handshake but ONLY when the server advertises the matching capability on
130
+ // initialize (`capabilities.prompts` / `capabilities.resources`). Servers
131
+ // that don't implement them never get a `prompts/list` / `resources/list`
132
+ // request, so a tools-only server degrades cleanly with no method-not-found
133
+ // spam. Cleared on child exit alongside `_tools`.
134
+ this._prompts = []
135
+ this._resources = []
136
+ // The `capabilities` object the server returned on initialize. Read to
137
+ // gate the prompts/resources list calls; null until a successful handshake.
138
+ this._serverCapabilities = null
118
139
  this._child = null
119
140
  this._stdoutBuf = ''
120
141
  this._nextId = 1
@@ -126,6 +147,8 @@ export class MCPClient extends EventEmitter {
126
147
 
127
148
  get state() { return this._state }
128
149
  get tools() { return this._tools }
150
+ get prompts() { return this._prompts }
151
+ get resources() { return this._resources }
129
152
 
130
153
  async start() {
131
154
  if (this._destroyed) throw new Error('MCPClient destroyed')
@@ -142,6 +165,12 @@ export class MCPClient extends EventEmitter {
142
165
  this._log.warn(`MCP server ${this.name}: trust gate threw: ${err?.message || err}`)
143
166
  allowed = false
144
167
  }
168
+ // #7906: destroy() can land while the trust gate above was pending. No
169
+ // child exists yet, so a concurrent destroy() already resolved cleanly
170
+ // (see destroy()'s `!child` branch below) and set state=DESTROYED —
171
+ // bail here instead of spawning an untracked child once this suspended
172
+ // start() resumes.
173
+ if (this._destroyed) return
145
174
  if (!allowed) {
146
175
  this._setState(MCP_STATES.DEAD)
147
176
  this.emit('dead')
@@ -149,14 +178,20 @@ export class MCPClient extends EventEmitter {
149
178
  }
150
179
  }
151
180
  this._spawnAndHandshake()
152
- // Resolve when state stabilises — first READY (handshake success) or
153
- // DEAD (max restart attempts exhausted). RESTARTING intermediate states
154
- // are transparent to the caller; what they want is "is this thing
155
- // usable or not", and that's the steady-state answer.
181
+ // Resolve when state stabilises — first READY (handshake success), DEAD
182
+ // (max restart attempts exhausted), or DESTROYED (#7906: destroy() can
183
+ // land while _spawnAndHandshake()'s handshake is in flight — see the
184
+ // _destroyed re-check at the end of _handshake(). That path never
185
+ // reaches READY/DEAD, so without DESTROYED here this promise would hang
186
+ // forever — _onExit() forces DESTROYED once the already-signalled
187
+ // child actually exits, but nothing upstream of it is READY/DEAD).
188
+ // RESTARTING intermediate states are transparent to the caller; what
189
+ // they want is "is this thing usable or not (or gone)", and that's the
190
+ // steady-state answer.
156
191
  if (this._state !== MCP_STATES.READY && this._state !== MCP_STATES.DEAD) {
157
192
  await new Promise((resolve) => {
158
193
  const onState = ({ next }) => {
159
- if (next === MCP_STATES.READY || next === MCP_STATES.DEAD) {
194
+ if (next === MCP_STATES.READY || next === MCP_STATES.DEAD || next === MCP_STATES.DESTROYED) {
160
195
  this.off('state', onState)
161
196
  resolve()
162
197
  }
@@ -173,6 +208,12 @@ export class MCPClient extends EventEmitter {
173
208
  * never reach an MCP server subprocess, which could read it and seize the
174
209
  * daemon. Extracted so the strip is unit-testable without a real spawn.
175
210
  *
211
+ * Also strips CHROXY_PORT/CHROXY_HOOK_SECRET (#7360): an MCP server has no
212
+ * legitimate use for the daemon's permission-hook secret — it is not a
213
+ * hook-consuming child — so any value present here is necessarily
214
+ * AMBIENTLY inherited (e.g. this daemon was itself launched from inside
215
+ * another chroxy session) rather than something this client set itself.
216
+ *
176
217
  * @returns {Record<string, string>}
177
218
  */
178
219
  _buildChildEnv() {
@@ -180,6 +221,8 @@ export class MCPClient extends EventEmitter {
180
221
  for (const key of CHROXY_SECRET_DENYLIST) {
181
222
  delete env[key]
182
223
  }
224
+ stripInheritedChroxySecrets(env)
225
+ stripParentClaudeSessionEnv(env) // #8262
183
226
  return env
184
227
  }
185
228
 
@@ -207,6 +250,20 @@ export class MCPClient extends EventEmitter {
207
250
  child.on('error', (err) => {
208
251
  this._log.warn(`MCP server ${this.name}: child error: ${err?.message || err}`)
209
252
  })
253
+ // #7906: a write can race the child's actual death — SIGTERM is sent,
254
+ // but stdin.writable can still read true for a brief window before the
255
+ // OS pipe is fully torn down (destroy() racing _notify()'s handshake
256
+ // write is one real path here: initialize resolves late, _notify()
257
+ // fires immediately after, right as the killed child is exiting). A
258
+ // stream write failure (EPIPE) is reported asynchronously as an
259
+ // 'error' event, not a catchable exception at the write() call site —
260
+ // with no listener, Node treats it as unhandled and CRASHES THE WHOLE
261
+ // PROCESS. _request()'s write passes a callback (which absorbs a
262
+ // reported error) but _notify()'s does not, so this listener is the
263
+ // one guard that covers every stdin write regardless of call site.
264
+ child.stdin.on('error', (err) => {
265
+ this._log.debug(`MCP server ${this.name}: stdin write error: ${err?.message || err}`)
266
+ })
210
267
  child.stderr.on('data', (chunk) => {
211
268
  this._log.debug(`MCP server ${this.name} stderr: ${chunk.toString().trimEnd()}`)
212
269
  })
@@ -238,15 +295,88 @@ export class MCPClient extends EventEmitter {
238
295
  if (typeof serverVersion === 'string' && serverVersion !== MCP_PROTOCOL_VERSION) {
239
296
  this._log.warn(`MCP server ${this.name}: protocolVersion mismatch — requested=${MCP_PROTOCOL_VERSION} server=${serverVersion} (negotiating to server value)`)
240
297
  }
298
+ // #6823: remember the server's advertised capabilities so the
299
+ // prompts/resources list calls below are only made when the server
300
+ // actually implements them.
301
+ this._serverCapabilities =
302
+ initResult.capabilities && typeof initResult.capabilities === 'object'
303
+ ? initResult.capabilities
304
+ : {}
241
305
  this._notify('notifications/initialized')
242
306
  const toolsResult = await this._request('tools/list', {}, this._handshakeTimeoutMs)
243
307
  const tools = Array.isArray(toolsResult?.tools) ? toolsResult.tools : []
244
308
  this._tools = Object.freeze(tools.map((t) => Object.freeze({ ...t })))
309
+ // #6823: capability-gated prompts/list + resources/list. A failure here is
310
+ // NON-fatal — the server is otherwise usable for tools, so we log at debug
311
+ // and leave the list empty rather than failing the handshake into a restart
312
+ // loop (see _loadListing).
313
+ if (this._serverCapabilities.prompts) {
314
+ this._prompts = await this._loadListing('prompts/list', 'prompts')
315
+ }
316
+ if (this._serverCapabilities.resources) {
317
+ this._resources = await this._loadListing('resources/list', 'resources')
318
+ }
245
319
  this._restartAttempts = 0
320
+ // #7906: destroy() can land at any point during the handshake awaits
321
+ // above (initialize / tools/list / prompts/list / resources/list) —
322
+ // the child's stdout data can already be buffered/received before
323
+ // destroy()'s SIGTERM actually terminates the process, so the pending
324
+ // _request() promises above can still resolve successfully after
325
+ // _destroyed flips true. _onExit() will eventually force state back to
326
+ // DESTROYED once the (already-signalled) child actually exits, but
327
+ // without this check the handshake would resurrect a destroyed client
328
+ // as READY — and emit 'ready' with populated tools — in the meantime.
329
+ if (this._destroyed) return
246
330
  this._setState(MCP_STATES.READY)
247
331
  this.emit('ready', this._tools)
248
332
  }
249
333
 
334
+ /**
335
+ * #6823: fetch a capability-gated list (prompts/list or resources/list),
336
+ * returning a frozen array. Errors (timeout, method-not-found from a server
337
+ * that advertised the capability but doesn't honour the request, malformed
338
+ * result) degrade to an empty list with a debug log — never a throw, so the
339
+ * handshake still reaches READY on the strength of tools alone.
340
+ */
341
+ async _loadListing(method, field) {
342
+ try {
343
+ const result = await this._request(method, {}, this._handshakeTimeoutMs)
344
+ const list = Array.isArray(result?.[field]) ? result[field] : []
345
+ return Object.freeze(list.map((item) => Object.freeze({ ...item })))
346
+ } catch (err) {
347
+ this._log.debug(`MCP server ${this.name}: ${method} failed: ${err?.message || err}`)
348
+ return []
349
+ }
350
+ }
351
+
352
+ /**
353
+ * #6823: fetch one prompt's messages (MCP `prompts/get`). `args` is the
354
+ * caller-supplied argument map; omitted from the request when empty so
355
+ * no-argument prompts stay first-class. Throws when the server is not READY
356
+ * or the JSON-RPC call errors (a missing required argument surfaces here).
357
+ */
358
+ async getPrompt(name, args, timeoutMs = DEFAULT_TOOL_CALL_TIMEOUT_MS) {
359
+ if (this._state !== MCP_STATES.READY) {
360
+ throw new Error(`MCP server ${this.name} not ready (state=${this._state})`)
361
+ }
362
+ const params = { name }
363
+ if (args && typeof args === 'object' && Object.keys(args).length > 0) {
364
+ params.arguments = args
365
+ }
366
+ return this._request('prompts/get', params, timeoutMs)
367
+ }
368
+
369
+ /**
370
+ * #6823: read one resource's contents (MCP `resources/read`). Throws when the
371
+ * server is not READY or the JSON-RPC call errors.
372
+ */
373
+ async readResource(uri, timeoutMs = DEFAULT_TOOL_CALL_TIMEOUT_MS) {
374
+ if (this._state !== MCP_STATES.READY) {
375
+ throw new Error(`MCP server ${this.name} not ready (state=${this._state})`)
376
+ }
377
+ return this._request('resources/read', { uri }, timeoutMs)
378
+ }
379
+
250
380
  async callTool(toolName, args, timeoutMs = DEFAULT_TOOL_CALL_TIMEOUT_MS) {
251
381
  if (this._state !== MCP_STATES.READY) {
252
382
  throw new Error(`MCP server ${this.name} not ready (state=${this._state})`)
@@ -290,7 +420,7 @@ export class MCPClient extends EventEmitter {
290
420
  let msg
291
421
  try {
292
422
  msg = JSON.parse(line)
293
- } catch (err) {
423
+ } catch (_err) {
294
424
  this._log.warn(`MCP server ${this.name}: non-JSON line: ${line.slice(0, 80)}`)
295
425
  continue
296
426
  }
@@ -334,6 +464,11 @@ export class MCPClient extends EventEmitter {
334
464
  if (!wasStartingOrReady) return
335
465
 
336
466
  this._tools = []
467
+ // #6823: a dead server contributes zero prompts/resources too, mirroring
468
+ // the tools reset so a crashed-then-restart-exhausted server cleanly
469
+ // disappears from the next turn's slash-command + resource surfaces.
470
+ this._prompts = []
471
+ this._resources = []
337
472
  this._restartAttempts += 1
338
473
  // #4453: gate on `>` (not `>=`) so the FULL RESTART_BACKOFF_MS schedule
339
474
  // is consumed before declaring DEAD. Pre-#4453 the gate fired on `>=`
@@ -402,3 +537,1001 @@ export class MCPClient extends EventEmitter {
402
537
  this.emit('state', { prev, next })
403
538
  }
404
539
  }
540
+
541
+ // ---------------------------------------------------------------------------
542
+ // Remote transport (#6821): MCP Streamable HTTP + legacy HTTP+SSE.
543
+ // ---------------------------------------------------------------------------
544
+
545
+ /**
546
+ * Iterate a fetch response body as chunks. Node's `fetch` returns a web
547
+ * ReadableStream (undici); prefer async iteration when available, else fall
548
+ * back to an explicit reader so the SSE loop works across node versions.
549
+ */
550
+ async function* iterateStream(stream) {
551
+ if (!stream) return
552
+ if (typeof stream[Symbol.asyncIterator] === 'function') {
553
+ yield* stream
554
+ return
555
+ }
556
+ const reader = stream.getReader()
557
+ try {
558
+ for (;;) {
559
+ const { value, done } = await reader.read()
560
+ if (done) return
561
+ if (value) yield value
562
+ }
563
+ } finally {
564
+ try { reader.releaseLock() } catch { /* stream already closed */ }
565
+ }
566
+ }
567
+
568
+ /**
569
+ * Parse one SSE event block into `{ event, data }`. Per the SSE grammar a
570
+ * `data:` field drops a single leading space and multiple `data:` lines join
571
+ * with newlines; `id:`/`retry:`/comment (`:`) lines are ignored — we only
572
+ * need the event name and its JSON-RPC data payload.
573
+ */
574
+ function parseSseEvent(rawEvent) {
575
+ let event = 'message'
576
+ const dataLines = []
577
+ for (const line of rawEvent.split('\n')) {
578
+ if (line.length === 0 || line.startsWith(':')) continue
579
+ if (line.startsWith('event:')) event = line.slice(6).replace(/^ /, '').trim()
580
+ else if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, ''))
581
+ }
582
+ return { event, data: dataLines.length > 0 ? dataLines.join('\n') : null }
583
+ }
584
+
585
+ /** Parse a POST body (single object or JSON-RPC batch array) for the response matching `id`. */
586
+ function extractJsonRpcResponse(text, id) {
587
+ let parsed
588
+ try { parsed = JSON.parse(text) } catch { return null }
589
+ const list = Array.isArray(parsed) ? parsed : [parsed]
590
+ return list.find((m) => m && m.id === id) || null
591
+ }
592
+
593
+ export class MCPRemoteClient extends EventEmitter {
594
+ constructor(config, opts = {}) {
595
+ super()
596
+ this.name = config.name
597
+ this._config = config
598
+ this._log = opts.log || createLogger('byok-mcp')
599
+ // Injectable HTTP client (defaults to the global fetch), mirroring the
600
+ // fetchImpl seam in get-public-ip / discord-webhook-client so tests can
601
+ // drive the transport against an in-process http server. fetch is a node
602
+ // primitive — no new npm dependency, consistent with the hand-rolled
603
+ // stdio client above.
604
+ this._fetchImpl = opts.fetchImpl || globalThis.fetch
605
+ // #4457 parity: optional async trust gate consulted before the first
606
+ // connect. true → proceed; false / throw → permanent DEAD, no request
607
+ // ever leaves the process.
608
+ this._trustGate = opts.trustGate || null
609
+ // #4454 parity: per-request handshake timeout. Same precedence + defensive
610
+ // guard as the stdio client (opts > config > module default).
611
+ this._handshakeTimeoutMs =
612
+ (Number.isFinite(opts.handshakeTimeoutMs) && opts.handshakeTimeoutMs > 0 && opts.handshakeTimeoutMs) ||
613
+ (Number.isFinite(config?.handshakeTimeoutMs) && config.handshakeTimeoutMs > 0 && config.handshakeTimeoutMs) ||
614
+ DEFAULT_HANDSHAKE_TIMEOUT_MS
615
+ this._url = config.url
616
+ // 'sse' → legacy HTTP+SSE two-endpoint transport; anything else → modern
617
+ // Streamable HTTP (single endpoint, POST + optional SSE-upgraded response).
618
+ this._transportType = config.type === 'sse' ? 'sse' : 'http'
619
+ this._headers = config.headers || {}
620
+ this._state = MCP_STATES.IDLE
621
+ this._tools = []
622
+ // #6823: MCP prompts + resources — same capability-gated lifecycle as the
623
+ // stdio client. Populated after tools/list, only when the server advertises
624
+ // the capability on initialize; cleared on death.
625
+ this._prompts = []
626
+ this._resources = []
627
+ this._serverCapabilities = null
628
+ this._nextId = 1
629
+ this._sessionId = null
630
+ this._negotiatedProtocolVersion = null
631
+ // 'oauth-required' after a 401/407 that the OAuth flow (#6822) could not
632
+ // silently satisfy — the client surfaces `authorizationUrl` for the user to
633
+ // open. null otherwise. Never carries any header/token value.
634
+ this._statusReason = null
635
+ // #6822 OAuth 2.1 + PKCE for a remote server that answers 401. Injectable
636
+ // seams (default the real modules) keep the flow testable against an
637
+ // in-process mock AS/RS with no real network + no real keychain.
638
+ this._oauthEnabled = opts.oauthEnabled !== false
639
+ this._oauthFlow = opts.oauthFlow || realOAuthFlow
640
+ this._oauthStore = opts.oauthStore || realOAuthStore
641
+ // The redirect_uri the daemon registers + surfaces. Defaults to the
642
+ // configured daemon callback (loopback/tunnel); tests pass a fixed value.
643
+ this._oauthRedirectUri = opts.oauthRedirectUri || null
644
+ // Bearer access token (from a stored record or a completed authorization).
645
+ // Merged into every request's headers via `_authHeader()` — OAuth wins over
646
+ // any static Authorization header the config carried.
647
+ this._accessToken = null
648
+ // The browser authorization URL surfaced to clients while `oauth-required`.
649
+ this._authorizationUrl = null
650
+ // Server-side PKCE/state/token-endpoint bag from beginAuthorization, consumed
651
+ // by completeAuthorization. Holds secret material — never logged/surfaced.
652
+ this._authPending = null
653
+ // Guards a single proactive/reactive refresh attempt per start() so a broken
654
+ // refresh token can't spin the connect loop.
655
+ this._refreshAttempted = false
656
+ this._destroyed = false
657
+ // In-flight AbortControllers, aborted on destroy() so a hung request or a
658
+ // persistent SSE stream cannot keep the process alive after teardown.
659
+ this._controllers = new Set()
660
+ // Legacy-SSE only: resolved POST endpoint + pending-request registry
661
+ // (streamable HTTP awaits each POST inline, so it leaves these empty).
662
+ this._endpointUrl = null
663
+ this._pending = new Map()
664
+ this._endpointTimer = null
665
+ this._endpointResolve = null
666
+ this._endpointReject = null
667
+ }
668
+
669
+ get state() { return this._state }
670
+ get tools() { return this._tools }
671
+ get prompts() { return this._prompts }
672
+ get resources() { return this._resources }
673
+ get statusReason() { return this._statusReason }
674
+ /** #6822: the browser authorization URL to open while `oauth-required`, else null. */
675
+ get authorizationUrl() { return this._authorizationUrl }
676
+ /** #6822: true when this server is waiting for the user to complete OAuth. */
677
+ get needsAuthorization() { return this._statusReason === 'oauth-required' }
678
+
679
+ async start() {
680
+ if (this._destroyed) throw new Error('MCPRemoteClient destroyed')
681
+ if (this._state === MCP_STATES.READY || this._state === MCP_STATES.DEAD) return
682
+ // #6834 sharp edge, folded in pre-merge: unconditionally refuse
683
+ // cloud-metadata / link-local targets at REQUEST time too (parse already
684
+ // rejects them; this guards configs constructed programmatically). Checked
685
+ // before the trust gate so the user is never prompted to trust a URL we
686
+ // will refuse regardless.
687
+ const refusal = await this._refuseMetadataTarget()
688
+ // #7906: destroy() can land while the metadata-refusal check above (a
689
+ // real DNS lookup for non-literal hostnames) was pending. Nothing is
690
+ // open yet, so a concurrent destroy() already resolved cleanly and set
691
+ // state=DESTROYED — bail before touching state again or consulting the
692
+ // trust gate.
693
+ if (this._destroyed) { this._setState(MCP_STATES.DESTROYED); return }
694
+ if (refusal) {
695
+ this._log.warn(`MCP server ${this.name}: ${refusal}`)
696
+ this._toDead()
697
+ return
698
+ }
699
+ // #4457 parity: trust gate fires BEFORE any network request. Deny/throw →
700
+ // permanent DEAD, fail-closed.
701
+ if (this._trustGate) {
702
+ let allowed
703
+ try {
704
+ allowed = await this._trustGate()
705
+ } catch (err) {
706
+ this._log.warn(`MCP server ${this.name}: trust gate threw: ${err?.message || err}`)
707
+ allowed = false
708
+ }
709
+ // #7906: same re-check — destroy() can land while the trust gate
710
+ // itself was pending. No connection exists yet, so bail rather than
711
+ // resurrect a destroyed client (and never overwrite state=DESTROYED
712
+ // with DEAD via _toDead()).
713
+ if (this._destroyed) { this._setState(MCP_STATES.DESTROYED); return }
714
+ if (!allowed) {
715
+ this._toDead()
716
+ return
717
+ }
718
+ }
719
+ // #6822: prime a stored access token (refreshing it up front if expired) so a
720
+ // previously-authorized server reconnects with no user prompt.
721
+ await this._prepareStoredToken()
722
+ // #7906: destroy() can land while priming the stored token (a refresh
723
+ // call to the token endpoint) — bail before opening the real connection
724
+ // below.
725
+ if (this._destroyed) { this._setState(MCP_STATES.DESTROYED); return }
726
+ this._setState(MCP_STATES.STARTING)
727
+ try {
728
+ await this._attemptConnect()
729
+ if (this._destroyed) { this._setState(MCP_STATES.DESTROYED); return }
730
+ this._setState(MCP_STATES.READY)
731
+ this.emit('ready', this._tools)
732
+ } catch (err) {
733
+ if (this._destroyed) { this._setState(MCP_STATES.DESTROYED); return }
734
+ if (err && err._oauthRequired) {
735
+ await this._onOAuthRequired(err)
736
+ return
737
+ }
738
+ this._log.warn(`MCP server ${this.name}: connect failed: ${err?.message || err}`)
739
+ this._toDead()
740
+ }
741
+ }
742
+
743
+ /** Run the transport handshake once (fresh transport counters each attempt). */
744
+ async _attemptConnect() {
745
+ this._resetTransportState()
746
+ if (this._transportType === 'sse') await this._connectLegacySse()
747
+ else await this._handshakeStreamableHttp()
748
+ }
749
+
750
+ /** Reset per-connection transport state so a re-attempt starts clean (#6822). */
751
+ _resetTransportState() {
752
+ this._sessionId = null
753
+ this._negotiatedProtocolVersion = null
754
+ this._nextId = 1
755
+ this._endpointUrl = null
756
+ this._rejectAllPending(new Error('reconnecting'))
757
+ }
758
+
759
+ /**
760
+ * #6822: a connect answered 401/407. Try, in order:
761
+ * 1. a silent refresh (an existing-but-expired token whose refresh works) →
762
+ * reconnect authenticated;
763
+ * 2. begin a browser authorization — discover the AS, register a client, and
764
+ * surface the authorization URL (status `oauth-required`).
765
+ * Any failure falls through to a value-free `oauth-required` DEAD state.
766
+ */
767
+ async _onOAuthRequired(err) {
768
+ // (1) silent refresh of an existing token.
769
+ if (this._oauthEnabled && this._accessToken && !this._refreshAttempted) {
770
+ this._refreshAttempted = true
771
+ const refreshed = await this._tryRefresh()
772
+ if (refreshed && !this._destroyed) {
773
+ try {
774
+ await this._attemptConnect()
775
+ if (this._destroyed) { this._setState(MCP_STATES.DESTROYED); return }
776
+ this._setState(MCP_STATES.READY)
777
+ this.emit('ready', this._tools)
778
+ return
779
+ } catch (retryErr) {
780
+ if (this._destroyed) { this._setState(MCP_STATES.DESTROYED); return }
781
+ if (!(retryErr && retryErr._oauthRequired)) {
782
+ this._log.warn(`MCP server ${this.name}: reconnect after refresh failed: ${retryErr?.message || retryErr}`)
783
+ this._toDead()
784
+ return
785
+ }
786
+ // Refresh succeeded but the server still rejects — fall through to a
787
+ // fresh browser authorization below.
788
+ err = retryErr
789
+ }
790
+ }
791
+ }
792
+ // (2) begin browser authorization.
793
+ await this._beginBrowserAuthorization(err)
794
+ }
795
+
796
+ /**
797
+ * Attempt to refresh the stored token in place. Returns true on success (with
798
+ * `_accessToken` updated + the record persisted), false otherwise. The stored
799
+ * record is left intact on failure so a subsequent full re-auth can replace it.
800
+ */
801
+ async _tryRefresh() {
802
+ let record
803
+ try { record = this._oauthStore.getStoredToken(this._url) } catch { record = null }
804
+ if (!record || !record.refreshToken || !record.tokenEndpoint) return false
805
+ try {
806
+ const tokens = await this._oauthFlow.refreshAccessToken({
807
+ tokenEndpoint: record.tokenEndpoint,
808
+ clientId: record.clientId,
809
+ clientSecret: record.clientSecret,
810
+ refreshToken: record.refreshToken,
811
+ scope: record.scope,
812
+ resource: record.resource,
813
+ fetchImpl: this._fetchImpl,
814
+ })
815
+ const next = { ...record, ...tokens }
816
+ this._oauthStore.setStoredToken(this._url, next)
817
+ this._accessToken = next.accessToken
818
+ return true
819
+ } catch (refreshErr) {
820
+ this._log.debug(`MCP server ${this.name}: token refresh failed: ${refreshErr?.message || refreshErr}`)
821
+ return false
822
+ }
823
+ }
824
+
825
+ /**
826
+ * Discover + register + build the authorization URL, surfacing it as
827
+ * `oauth-required`. Registers a callback keyed by the flow's `state` so the
828
+ * daemon's loopback/tunnel callback can auto-complete; the paste-code path
829
+ * (completeAuthorization) is the universal fallback. Never throws.
830
+ */
831
+ async _beginBrowserAuthorization(err) {
832
+ const redirectUri = this._oauthRedirectUri || this._oauthFlow.mcpOAuthRedirectUri?.()
833
+ if (!this._oauthEnabled || !redirectUri) {
834
+ this._statusReason = 'oauth-required'
835
+ this._log.warn(`MCP server ${this.name}: requires OAuth but the flow is disabled or no redirect URI is configured`)
836
+ // #7906: this method can be reached with _destroyed already true —
837
+ // _onOAuthRequired()'s silent-refresh branch falls through to
838
+ // `await this._beginBrowserAuthorization(err)` unconditionally once
839
+ // its own `await this._tryRefresh()` settles, regardless of whether
840
+ // destroy() landed during that await. No connection exists yet here
841
+ // either, so bail rather than regress an already-destroyed client to
842
+ // DEAD via _toDead() (and fire a stray 'dead' event nothing should
843
+ // see) — same reasoning as the guard below this method's try/catch.
844
+ if (this._destroyed) { this._setState(MCP_STATES.DESTROYED); return }
845
+ this._toDead()
846
+ return
847
+ }
848
+ try {
849
+ const { authorizationUrl, pending } = await this._oauthFlow.beginAuthorization({
850
+ serverUrl: this._url,
851
+ wwwAuthenticate: err?._wwwAuthenticate || null,
852
+ redirectUri,
853
+ fetchImpl: this._fetchImpl,
854
+ log: this._log,
855
+ })
856
+ if (this._destroyed) { this._setState(MCP_STATES.DESTROYED); return }
857
+ this._authPending = pending
858
+ this._authorizationUrl = authorizationUrl
859
+ this._statusReason = 'oauth-required'
860
+ // Register the loopback/tunnel auto-complete handler. The paste-code path
861
+ // shares completeAuthorization, so both redemption routes are equivalent.
862
+ try {
863
+ this._oauthFlow.registerOAuthCallback?.(pending.state, (code) => this.completeAuthorization(code))
864
+ } catch { /* registry is best-effort — paste-code still works */ }
865
+ this._log.info(`MCP server ${this.name}: OAuth authorization required — surfaced an authorization URL`)
866
+ } catch (authErr) {
867
+ this._statusReason = 'oauth-required'
868
+ this._log.warn(`MCP server ${this.name}: could not begin OAuth authorization: ${authErr?.message || authErr}`)
869
+ }
870
+ // #7906: destroy() can land while beginAuthorization() above (real AS
871
+ // discovery + dynamic client registration network calls) was pending —
872
+ // including via the catch branch immediately above, when destroy()'s
873
+ // abort of an in-flight request (or an unrelated network failure) makes
874
+ // that call reject rather than resolve. No connection exists yet, so
875
+ // bail rather than regress an already-destroyed client to DEAD via
876
+ // _toDead() (which would also fire a stray 'dead' event nothing should
877
+ // see).
878
+ if (this._destroyed) { this._setState(MCP_STATES.DESTROYED); return }
879
+ // Not ready — DEAD until a code is submitted (contributes zero tools). The
880
+ // oauth-required fields survive _toDead so the fleet can surface them.
881
+ this._toDead()
882
+ }
883
+
884
+ /**
885
+ * #6822: complete an authorization by redeeming `code` against the pending
886
+ * PKCE/state bag, persisting the tokens, and reconnecting authenticated. Shared
887
+ * by the loopback callback and the paste-code wire path. Throws (value-free) on
888
+ * redemption failure; resolves once the reconnect settles.
889
+ *
890
+ * @param {string} code
891
+ * @returns {Promise<{ ok: true }>}
892
+ */
893
+ async completeAuthorization(code) {
894
+ if (this._destroyed) throw new Error('MCPRemoteClient destroyed')
895
+ if (!this._authPending) throw new Error(`MCP server ${this.name}: no pending authorization`)
896
+ if (typeof code !== 'string' || !code.trim()) throw new Error('an authorization code is required')
897
+ const pending = this._authPending
898
+ const record = await this._oauthFlow.completeAuthorization({
899
+ pending,
900
+ code: code.trim(),
901
+ fetchImpl: this._fetchImpl,
902
+ })
903
+ this._oauthStore.setStoredToken(this._url, record)
904
+ this._accessToken = record.accessToken
905
+ // #7906: destroy() can land while redeeming the code above (a real
906
+ // network round-trip). The token just persisted above is fully formed
907
+ // and safe to keep for a future reconnect, but a destroyed client must
908
+ // never be resurrected: the raw `_state = IDLE` write below bypasses
909
+ // _setState entirely (no terminal-state protection), and the
910
+ // reconnecting `start()` call would otherwise throw ("MCPRemoteClient
911
+ // destroyed") only AFTER state was already clobbered to IDLE.
912
+ if (this._destroyed) { this._setState(MCP_STATES.DESTROYED); return { ok: true } }
913
+ // Clear the pending-auth surface and reconnect.
914
+ try { this._oauthFlow.unregisterOAuthCallback?.(pending.state) } catch { /* best-effort */ }
915
+ this._authPending = null
916
+ this._authorizationUrl = null
917
+ this._statusReason = null
918
+ this._refreshAttempted = false
919
+ this._state = MCP_STATES.IDLE
920
+ await this.start()
921
+ return { ok: true }
922
+ }
923
+
924
+ /**
925
+ * Load a stored token for this server, refreshing it up front when expired.
926
+ * Sets `_accessToken` when a usable token is available. Read/refresh failures
927
+ * degrade to unauthenticated (the connect then 401s and re-authorizes).
928
+ */
929
+ async _prepareStoredToken() {
930
+ this._refreshAttempted = false
931
+ if (!this._oauthEnabled) return
932
+ let record
933
+ try { record = this._oauthStore.getStoredToken(this._url) } catch { record = null }
934
+ if (!record) return
935
+ if (this._oauthStore.isTokenExpired(record)) {
936
+ this._refreshAttempted = true
937
+ const refreshed = await this._tryRefresh()
938
+ if (!refreshed) this._accessToken = null
939
+ return
940
+ }
941
+ this._accessToken = record.accessToken
942
+ }
943
+
944
+ /**
945
+ * Dispatch a single JSON-RPC request over whichever transport this client
946
+ * negotiated (legacy SSE endpoint vs Streamable HTTP POST). Shared by
947
+ * callTool / getPrompt / readResource so the transport branch lives in one
948
+ * place (#6823).
949
+ */
950
+ _rpc(method, params, timeoutMs) {
951
+ return this._transportType === 'sse'
952
+ ? this._rpcViaEndpoint(method, params, timeoutMs)
953
+ : this._rpcPost(method, params, timeoutMs)
954
+ }
955
+
956
+ async callTool(toolName, args, timeoutMs = DEFAULT_TOOL_CALL_TIMEOUT_MS) {
957
+ if (this._state !== MCP_STATES.READY) {
958
+ throw new Error(`MCP server ${this.name} not ready (state=${this._state})`)
959
+ }
960
+ return this._rpc('tools/call', { name: toolName, arguments: args || {} }, timeoutMs)
961
+ }
962
+
963
+ /** #6823: MCP `prompts/get` — parity with the stdio client's getPrompt. */
964
+ async getPrompt(name, args, timeoutMs = DEFAULT_TOOL_CALL_TIMEOUT_MS) {
965
+ if (this._state !== MCP_STATES.READY) {
966
+ throw new Error(`MCP server ${this.name} not ready (state=${this._state})`)
967
+ }
968
+ const params = { name }
969
+ if (args && typeof args === 'object' && Object.keys(args).length > 0) {
970
+ params.arguments = args
971
+ }
972
+ return this._rpc('prompts/get', params, timeoutMs)
973
+ }
974
+
975
+ /** #6823: MCP `resources/read` — parity with the stdio client's readResource. */
976
+ async readResource(uri, timeoutMs = DEFAULT_TOOL_CALL_TIMEOUT_MS) {
977
+ if (this._state !== MCP_STATES.READY) {
978
+ throw new Error(`MCP server ${this.name} not ready (state=${this._state})`)
979
+ }
980
+ return this._rpc('resources/read', { uri }, timeoutMs)
981
+ }
982
+
983
+ /**
984
+ * #6823: fetch a capability-gated list (prompts/list or resources/list) over
985
+ * the negotiated transport, degrading to an empty frozen array on any error —
986
+ * same non-fatal contract as the stdio client's _loadListing.
987
+ */
988
+ async _loadListing(method, field) {
989
+ try {
990
+ const result = await this._rpc(method, {}, this._handshakeTimeoutMs)
991
+ const list = Array.isArray(result?.[field]) ? result[field] : []
992
+ return Object.freeze(list.map((item) => Object.freeze({ ...item })))
993
+ } catch (err) {
994
+ this._log.debug(`MCP server ${this.name}: ${method} failed: ${err?.message || err}`)
995
+ return []
996
+ }
997
+ }
998
+
999
+ async destroy() {
1000
+ if (this._destroyed) return
1001
+ this._destroyed = true
1002
+ if (this._endpointTimer) { clearTimeout(this._endpointTimer); this._endpointTimer = null }
1003
+ // #6822: drop any pending-auth callback so a torn-down client can't be
1004
+ // completed via the loopback registry after destroy.
1005
+ if (this._authPending?.state) {
1006
+ try { this._oauthFlow.unregisterOAuthCallback?.(this._authPending.state) } catch { /* best-effort */ }
1007
+ }
1008
+ this._rejectAllPending(new Error('MCP remote client destroyed'))
1009
+ for (const c of this._controllers) { try { c.abort() } catch { /* already settled */ } }
1010
+ this._controllers.clear()
1011
+ // Best-effort Streamable HTTP session teardown (spec: DELETE with the
1012
+ // session header). Bounded by KILL_GRACE_MS and fully error-swallowed —
1013
+ // it must never make destroy() hang or throw.
1014
+ if (this._transportType === 'http' && this._sessionId && typeof this._fetchImpl === 'function') {
1015
+ const controller = new AbortController()
1016
+ const timer = setTimeout(() => { try { controller.abort() } catch {} }, KILL_GRACE_MS)
1017
+ try {
1018
+ const res = await this._fetchImpl(this._url, {
1019
+ method: 'DELETE',
1020
+ headers: this._buildHeaders(),
1021
+ redirect: 'manual', // #6834: never follow a redirect off-origin
1022
+ signal: controller.signal,
1023
+ })
1024
+ await this._discardBody(res)
1025
+ } catch { /* teardown is best-effort */ } finally {
1026
+ clearTimeout(timer)
1027
+ }
1028
+ }
1029
+ this._setState(MCP_STATES.DESTROYED)
1030
+ }
1031
+
1032
+ // --- Streamable HTTP -----------------------------------------------------
1033
+
1034
+ async _handshakeStreamableHttp() {
1035
+ const initResult = await this._rpcPost('initialize', {
1036
+ protocolVersion: MCP_PROTOCOL_VERSION,
1037
+ capabilities: {},
1038
+ clientInfo: { name: 'chroxy-byok', version: MCP_CLIENT_VERSION },
1039
+ }, this._handshakeTimeoutMs, { captureSession: true })
1040
+ this._applyInitResult(initResult)
1041
+ await this._notifyPost('notifications/initialized')
1042
+ const toolsResult = await this._rpcPost('tools/list', {}, this._handshakeTimeoutMs)
1043
+ this._setTools(toolsResult)
1044
+ await this._loadPromptsAndResources()
1045
+ }
1046
+
1047
+ /** POST one JSON-RPC request; resolve its result from a JSON or SSE-upgraded response. */
1048
+ async _rpcPost(method, params, timeoutMs, { captureSession = false } = {}) {
1049
+ const id = this._nextId++
1050
+ const payload = JSON.stringify({ jsonrpc: '2.0', id, method, params })
1051
+ const controller = new AbortController()
1052
+ this._controllers.add(controller)
1053
+ let timedOut = false
1054
+ const timer = setTimeout(() => { timedOut = true; try { controller.abort() } catch {} }, timeoutMs)
1055
+ try {
1056
+ let res
1057
+ try {
1058
+ res = await this._fetchImpl(this._url, {
1059
+ method: 'POST',
1060
+ headers: this._buildHeaders({ json: true, acceptStream: true }),
1061
+ body: payload,
1062
+ // #6834: never auto-follow — a redirect must not carry our
1063
+ // credentialed headers to a different origin. 3xx → _checkStatus throws.
1064
+ redirect: 'manual',
1065
+ signal: controller.signal,
1066
+ })
1067
+ } catch (err) {
1068
+ if (timedOut) throw new Error(`MCP ${method} timeout`)
1069
+ throw err
1070
+ }
1071
+ await this._checkStatus(res, method)
1072
+ if (captureSession) {
1073
+ const sid = res.headers.get('mcp-session-id')
1074
+ if (sid) this._sessionId = sid
1075
+ }
1076
+ const contentType = (res.headers.get('content-type') || '').toLowerCase()
1077
+ let message
1078
+ if (contentType.includes('text/event-stream')) {
1079
+ message = await this._readSseUntilId(res.body, id)
1080
+ } else {
1081
+ let text
1082
+ try { text = await res.text() } catch (err) {
1083
+ if (timedOut) throw new Error(`MCP ${method} timeout`)
1084
+ throw err
1085
+ }
1086
+ message = extractJsonRpcResponse(text, id)
1087
+ }
1088
+ if (message == null) {
1089
+ if (timedOut) throw new Error(`MCP ${method} timeout`)
1090
+ throw new Error(`MCP ${method}: no matching JSON-RPC response`)
1091
+ }
1092
+ if (message.error) throw new Error(message.error?.message || `MCP ${method} RPC error`)
1093
+ return message.result
1094
+ } finally {
1095
+ clearTimeout(timer)
1096
+ this._controllers.delete(controller)
1097
+ }
1098
+ }
1099
+
1100
+ /** POST a JSON-RPC notification (no id, no response expected). Best-effort but honours a 401. */
1101
+ async _notifyPost(method, params) {
1102
+ const controller = new AbortController()
1103
+ this._controllers.add(controller)
1104
+ const timer = setTimeout(() => { try { controller.abort() } catch {} }, this._handshakeTimeoutMs)
1105
+ try {
1106
+ let res
1107
+ try {
1108
+ res = await this._fetchImpl(this._url, {
1109
+ method: 'POST',
1110
+ headers: this._buildHeaders({ json: true, acceptStream: true }),
1111
+ body: JSON.stringify({ jsonrpc: '2.0', method, params }),
1112
+ redirect: 'manual', // #6834: never follow a redirect off-origin
1113
+ signal: controller.signal,
1114
+ })
1115
+ } catch {
1116
+ return // initialize already succeeded; a lost `initialized` is non-fatal
1117
+ }
1118
+ if (res.status === 401 || res.status === 407) {
1119
+ throw this._oauthError(res, res.status)
1120
+ }
1121
+ await this._discardBody(res)
1122
+ } finally {
1123
+ clearTimeout(timer)
1124
+ this._controllers.delete(controller)
1125
+ }
1126
+ }
1127
+
1128
+ /** Read an SSE stream until the JSON-RPC response with `id` arrives (or the stream ends). */
1129
+ async _readSseUntilId(body, id) {
1130
+ if (!body) return null
1131
+ const decoder = new TextDecoder()
1132
+ let buf = ''
1133
+ for await (const chunk of iterateStream(body)) {
1134
+ buf += decoder.decode(chunk, { stream: true })
1135
+ buf = buf.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
1136
+ let idx
1137
+ while ((idx = buf.indexOf('\n\n')) !== -1) {
1138
+ const { data } = parseSseEvent(buf.slice(0, idx))
1139
+ buf = buf.slice(idx + 2)
1140
+ if (data == null) continue
1141
+ let msg
1142
+ try { msg = JSON.parse(data) } catch { continue }
1143
+ if (msg && msg.id === id) return msg
1144
+ // Server-initiated notifications/requests before the response: ignore.
1145
+ }
1146
+ }
1147
+ return null
1148
+ }
1149
+
1150
+ // --- Legacy HTTP+SSE (type: 'sse') ---------------------------------------
1151
+
1152
+ async _connectLegacySse() {
1153
+ const controller = new AbortController()
1154
+ this._controllers.add(controller)
1155
+ let res
1156
+ try {
1157
+ res = await this._fetchImpl(this._url, {
1158
+ method: 'GET',
1159
+ // #6822: include the OAuth bearer token (if any) on the SSE GET too, via
1160
+ // _applyOAuthHeader so a config-supplied `authorization` doesn't collide
1161
+ // with a fresh `Authorization` (two auth headers).
1162
+ headers: this._applyOAuthHeader({ ...this._headers, Accept: 'text/event-stream' }),
1163
+ redirect: 'manual', // #6834: never follow a redirect off-origin
1164
+ signal: controller.signal,
1165
+ })
1166
+ } catch (err) {
1167
+ this._controllers.delete(controller)
1168
+ throw err
1169
+ }
1170
+ if (res.status === 401 || res.status === 407) {
1171
+ throw this._oauthError(res, res.status)
1172
+ }
1173
+ if (res.status >= 300 && res.status < 400) {
1174
+ throw new Error(`MCP server ${this.name} HTTP ${res.status} redirect opening SSE stream — refused (redirects are not followed)`)
1175
+ }
1176
+ if (res.status < 200 || res.status >= 300) {
1177
+ throw new Error(`MCP server ${this.name} HTTP ${res.status} opening SSE stream`)
1178
+ }
1179
+ const endpointReady = new Promise((resolve, reject) => {
1180
+ this._endpointResolve = resolve
1181
+ this._endpointReject = reject
1182
+ this._endpointTimer = setTimeout(
1183
+ () => reject(new Error(`MCP server ${this.name}: timeout waiting for SSE endpoint`)),
1184
+ this._handshakeTimeoutMs,
1185
+ )
1186
+ })
1187
+ // Background dispatch loop: resolves the endpoint, then routes responses.
1188
+ this._runSseDispatchLoop(res.body)
1189
+ await endpointReady
1190
+ await this._legacyHandshake()
1191
+ }
1192
+
1193
+ async _legacyHandshake() {
1194
+ const initResult = await this._rpcViaEndpoint('initialize', {
1195
+ protocolVersion: MCP_PROTOCOL_VERSION,
1196
+ capabilities: {},
1197
+ clientInfo: { name: 'chroxy-byok', version: MCP_CLIENT_VERSION },
1198
+ }, this._handshakeTimeoutMs)
1199
+ this._applyInitResult(initResult)
1200
+ await this._notifyViaEndpoint('notifications/initialized')
1201
+ const toolsResult = await this._rpcViaEndpoint('tools/list', {}, this._handshakeTimeoutMs)
1202
+ this._setTools(toolsResult)
1203
+ await this._loadPromptsAndResources()
1204
+ }
1205
+
1206
+ async _runSseDispatchLoop(body) {
1207
+ const decoder = new TextDecoder()
1208
+ let buf = ''
1209
+ try {
1210
+ for await (const chunk of iterateStream(body)) {
1211
+ buf += decoder.decode(chunk, { stream: true })
1212
+ buf = buf.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
1213
+ let idx
1214
+ while ((idx = buf.indexOf('\n\n')) !== -1) {
1215
+ this._handleLegacyEvent(buf.slice(0, idx))
1216
+ buf = buf.slice(idx + 2)
1217
+ }
1218
+ }
1219
+ } catch (err) {
1220
+ if (!this._destroyed) this._log.debug(`MCP server ${this.name}: SSE stream error: ${err?.message || err}`)
1221
+ } finally {
1222
+ if (!this._destroyed) this._rejectAllPending(new Error('SSE stream closed'))
1223
+ }
1224
+ }
1225
+
1226
+ _handleLegacyEvent(rawEvent) {
1227
+ const { event, data } = parseSseEvent(rawEvent)
1228
+ if (event === 'endpoint') {
1229
+ if (!this._endpointResolve) return
1230
+ let endpoint = null
1231
+ try { endpoint = new URL(data, this._url) } catch { endpoint = null }
1232
+ if (this._endpointTimer) { clearTimeout(this._endpointTimer); this._endpointTimer = null }
1233
+ // #6834 sharp edge: the endpoint event is SERVER-SUPPLIED — an absolute
1234
+ // url here could pivot our credentialed POSTs (headers carry auth)
1235
+ // anywhere. Enforce SAME-ORIGIN (scheme+host+port, via URL.origin)
1236
+ // against the configured url; a cross-origin endpoint warns + rejects,
1237
+ // which fails the connect → DEAD. Origins are creds/query-free, so
1238
+ // logging them leaks nothing.
1239
+ let configuredOrigin = null
1240
+ try { configuredOrigin = new URL(this._url).origin } catch { /* refused below */ }
1241
+ if (endpoint && configuredOrigin && endpoint.origin === configuredOrigin) {
1242
+ this._endpointUrl = endpoint.toString()
1243
+ this._endpointResolve()
1244
+ } else if (endpoint && configuredOrigin) {
1245
+ this._log.warn(`MCP server ${this.name}: SSE endpoint origin ${endpoint.origin} != configured origin ${configuredOrigin} — refusing cross-origin endpoint`)
1246
+ this._endpointReject?.(new Error(`MCP server ${this.name}: cross-origin SSE endpoint refused`))
1247
+ } else {
1248
+ this._endpointReject?.(new Error(`MCP server ${this.name}: invalid SSE endpoint event`))
1249
+ }
1250
+ this._endpointResolve = null
1251
+ this._endpointReject = null
1252
+ return
1253
+ }
1254
+ if (data == null) return
1255
+ let msg
1256
+ try { msg = JSON.parse(data) } catch { return }
1257
+ if (msg && msg.id != null && this._pending.has(msg.id)) {
1258
+ const settle = this._pending.get(msg.id)
1259
+ settle(msg)
1260
+ }
1261
+ }
1262
+
1263
+ /** POST a JSON-RPC request to the legacy endpoint; await the response off the persistent SSE stream. */
1264
+ async _rpcViaEndpoint(method, params, timeoutMs) {
1265
+ if (!this._endpointUrl) throw new Error(`MCP server ${this.name}: no SSE endpoint`)
1266
+ const id = this._nextId++
1267
+ const responsePromise = new Promise((resolve) => {
1268
+ const timer = setTimeout(() => {
1269
+ this._pending.delete(id)
1270
+ resolve({ id, error: { message: `MCP ${method} timeout` } })
1271
+ }, timeoutMs)
1272
+ this._pending.set(id, (msg) => { clearTimeout(timer); this._pending.delete(id); resolve(msg) })
1273
+ })
1274
+ const controller = new AbortController()
1275
+ this._controllers.add(controller)
1276
+ const postTimer = setTimeout(() => { try { controller.abort() } catch {} }, timeoutMs)
1277
+ try {
1278
+ const res = await this._fetchImpl(this._endpointUrl, {
1279
+ method: 'POST',
1280
+ headers: this._buildHeaders({ json: true }),
1281
+ body: JSON.stringify({ jsonrpc: '2.0', id, method, params }),
1282
+ redirect: 'manual', // #6834: never follow a redirect off-origin
1283
+ signal: controller.signal,
1284
+ })
1285
+ await this._checkStatus(res, method)
1286
+ await this._discardBody(res)
1287
+ } catch (err) {
1288
+ this._pending.delete(id)
1289
+ throw err
1290
+ } finally {
1291
+ clearTimeout(postTimer)
1292
+ this._controllers.delete(controller)
1293
+ }
1294
+ const msg = await responsePromise
1295
+ if (msg.error) throw new Error(msg.error?.message || `MCP ${method} RPC error`)
1296
+ return msg.result
1297
+ }
1298
+
1299
+ async _notifyViaEndpoint(method, params) {
1300
+ if (!this._endpointUrl) return
1301
+ const controller = new AbortController()
1302
+ this._controllers.add(controller)
1303
+ const timer = setTimeout(() => { try { controller.abort() } catch {} }, this._handshakeTimeoutMs)
1304
+ try {
1305
+ let res
1306
+ try {
1307
+ res = await this._fetchImpl(this._endpointUrl, {
1308
+ method: 'POST',
1309
+ headers: this._buildHeaders({ json: true }),
1310
+ body: JSON.stringify({ jsonrpc: '2.0', method, params }),
1311
+ redirect: 'manual', // #6834: never follow a redirect off-origin
1312
+ signal: controller.signal,
1313
+ })
1314
+ } catch {
1315
+ return // network-level failure is best-effort — initialize already succeeded
1316
+ }
1317
+ // Same status semantics as every other call site (_checkStatus): 401/407
1318
+ // → oauth-required (propagates → DEAD), redirect/other non-2xx → error →
1319
+ // DEAD. Pre-fix this swallowed ALL statuses, letting the handshake
1320
+ // proceed past `initialized` while the server was rejecting our requests.
1321
+ await this._checkStatus(res, method)
1322
+ await this._discardBody(res)
1323
+ } finally {
1324
+ clearTimeout(timer)
1325
+ this._controllers.delete(controller)
1326
+ }
1327
+ }
1328
+
1329
+ // --- shared helpers ------------------------------------------------------
1330
+
1331
+ /**
1332
+ * Return a refusal reason when the configured url targets the cloud
1333
+ * metadata service / link-local range (#6834 sharp edge), else null.
1334
+ * Literal hosts are checked directly (the URL parser already canonicalized
1335
+ * hex/decimal tricks); DNS names get a best-effort lookup so a name
1336
+ * resolving into the blocked range is refused too. Lookup ERRORS pass
1337
+ * through — fetch will surface them as ordinary connect failures. Full
1338
+ * resolution pinning / DNS-rebinding defence stays in #6834.
1339
+ */
1340
+ async _refuseMetadataTarget() {
1341
+ let hostname
1342
+ try {
1343
+ hostname = new URL(this._url).hostname
1344
+ } catch {
1345
+ return null // fetch will surface the malformed url as a connect failure
1346
+ }
1347
+ if (isBlockedMetadataHost(hostname)) {
1348
+ return 'refusing cloud-metadata / link-local endpoint (never a legitimate MCP server)'
1349
+ }
1350
+ const bare = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname
1351
+ const isLiteral = /^[\d.]+$/.test(bare) || bare.includes(':')
1352
+ if (!isLiteral) {
1353
+ try {
1354
+ const addrs = await lookup(bare, { all: true })
1355
+ if (addrs.some(({ address }) => isBlockedMetadataHost(address))) {
1356
+ return 'refusing DNS name resolving to a cloud-metadata / link-local address'
1357
+ }
1358
+ } catch { /* resolution failures surface via fetch */ }
1359
+ }
1360
+ return null
1361
+ }
1362
+
1363
+ _applyInitResult(initResult) {
1364
+ if (!initResult || typeof initResult !== 'object') {
1365
+ throw new Error('initialize returned non-object result')
1366
+ }
1367
+ // #6823: capture advertised capabilities to gate prompts/resources fetches.
1368
+ this._serverCapabilities =
1369
+ initResult.capabilities && typeof initResult.capabilities === 'object'
1370
+ ? initResult.capabilities
1371
+ : {}
1372
+ const serverVersion = initResult.protocolVersion
1373
+ if (typeof serverVersion === 'string') {
1374
+ this._negotiatedProtocolVersion = serverVersion
1375
+ if (serverVersion !== MCP_PROTOCOL_VERSION) {
1376
+ this._log.warn(`MCP server ${this.name}: protocolVersion mismatch — requested=${MCP_PROTOCOL_VERSION} server=${serverVersion} (negotiating to server value)`)
1377
+ }
1378
+ }
1379
+ }
1380
+
1381
+ _setTools(toolsResult) {
1382
+ const tools = Array.isArray(toolsResult?.tools) ? toolsResult.tools : []
1383
+ this._tools = Object.freeze(tools.map((t) => Object.freeze({ ...t })))
1384
+ }
1385
+
1386
+ /**
1387
+ * #6823: capability-gated prompts/list + resources/list, run after tools/list
1388
+ * in both remote handshakes. Uses the shared `_serverCapabilities` gate and
1389
+ * the non-fatal `_loadListing` so a prompt/resource fetch failure never fails
1390
+ * the connect.
1391
+ */
1392
+ async _loadPromptsAndResources() {
1393
+ const caps = this._serverCapabilities || {}
1394
+ if (caps.prompts) this._prompts = await this._loadListing('prompts/list', 'prompts')
1395
+ if (caps.resources) this._resources = await this._loadListing('resources/list', 'resources')
1396
+ }
1397
+
1398
+ _buildHeaders({ json = false, acceptStream = false } = {}) {
1399
+ const headers = { ...this._headers }
1400
+ if (acceptStream) headers.Accept = 'application/json, text/event-stream'
1401
+ if (json) headers['Content-Type'] = 'application/json'
1402
+ // #6821 Streamable HTTP: echo the session id + negotiated protocol version
1403
+ // on every post-initialize request per the 2025-03-26 / 2025-06-18 spec.
1404
+ if (this._sessionId) headers['Mcp-Session-Id'] = this._sessionId
1405
+ if (this._negotiatedProtocolVersion) headers['MCP-Protocol-Version'] = this._negotiatedProtocolVersion
1406
+ return this._applyOAuthHeader(headers)
1407
+ }
1408
+
1409
+ /**
1410
+ * #6822: when an OAuth access token exists, replace ANY authorization header
1411
+ * the config carried (case-insensitively — a config `authorization` collides
1412
+ * with a fresh `Authorization`, sending TWO auth headers) with the OAuth
1413
+ * bearer, which is the fresher credential. Mutates + returns `headers`. When
1414
+ * there is no token, the config's own header (whatever its case) passes
1415
+ * through untouched.
1416
+ */
1417
+ _applyOAuthHeader(headers) {
1418
+ if (!this._accessToken) return headers
1419
+ for (const key of Object.keys(headers)) {
1420
+ if (key.toLowerCase() === 'authorization') delete headers[key]
1421
+ }
1422
+ headers.Authorization = `Bearer ${this._accessToken}`
1423
+ return headers
1424
+ }
1425
+
1426
+ /**
1427
+ * #6822: build the 401/407 error, capturing the `WWW-Authenticate` header so the
1428
+ * OAuth flow can discover the resource metadata. The header names only public
1429
+ * discovery URLs (never a token), so retaining it is safe.
1430
+ */
1431
+ _oauthError(res, status) {
1432
+ const err = new Error(`MCP server ${this.name} requires OAuth (HTTP ${status})`)
1433
+ err._oauthRequired = true
1434
+ try { err._wwwAuthenticate = res?.headers?.get?.('www-authenticate') || null } catch { err._wwwAuthenticate = null }
1435
+ return err
1436
+ }
1437
+
1438
+ async _checkStatus(res, method) {
1439
+ const status = res.status
1440
+ if (status >= 200 && status < 300) return
1441
+ // Non-2xx: no throw path below ever reads the body, so cancel/drain it
1442
+ // first — an unread Streamable-HTTP response body keeps its stream/socket
1443
+ // dangling (a leaked handle, the #6835 hang class), and for the legacy SSE
1444
+ // call sites the caller's own `_discardBody(res)` never runs once we throw.
1445
+ // _discardBody wraps its own work in try/catch, so this drain can never
1446
+ // throw-and-mask the status error we raise below.
1447
+ await this._discardBody(res)
1448
+ if (status === 401 || status === 407) {
1449
+ throw this._oauthError(res, status)
1450
+ }
1451
+ // #6834: with redirect:'manual' a 3xx surfaces here as-is. Refuse it
1452
+ // explicitly — following would replay our credentialed headers against
1453
+ // whatever origin the Location header names.
1454
+ if (status >= 300 && status < 400) {
1455
+ throw new Error(`MCP server ${this.name} HTTP ${status} redirect on ${method} — refused (redirects are not followed)`)
1456
+ }
1457
+ if (status === 404) {
1458
+ // #6835: a 404 means our Streamable HTTP session id is no longer valid —
1459
+ // the server GC'd the session (a real long-lived-session scenario). Drop
1460
+ // the stale id and, if this happened mid-session (live READY client with a
1461
+ // held session), tear the client down to DEAD. See _expireSession.
1462
+ this._expireSession(method)
1463
+ }
1464
+ throw new Error(`MCP server ${this.name} HTTP ${status} on ${method}`)
1465
+ }
1466
+
1467
+ /**
1468
+ * #6835: handle a 404 (Streamable HTTP session expiry). Always drops the stale
1469
+ * session id. When it fired on a LIVE session (state READY with a session id we
1470
+ * were echoing), the server has GC'd our session server-side — leaving the
1471
+ * client READY would keep the fleet advertising tools that now silently 404 on
1472
+ * every call (the zombie). The remote transport has no lazy re-handshake
1473
+ * (single-connect model, #6821), so tear the client down to DEAD: the fleet
1474
+ * drops its tools, matching the stdio restart-exhaustion contract; recovery is
1475
+ * a session restart or a server re-enable (which rebuilds a fresh client).
1476
+ *
1477
+ * A stateless server (never issued a session id) keeps the prior per-call
1478
+ * behaviour — a lone 404 there stays READY and the next call retries, mirroring
1479
+ * the transient-network-blip handling.
1480
+ */
1481
+ _expireSession(method) {
1482
+ const wasLive = this._state === MCP_STATES.READY && this._sessionId != null
1483
+ this._sessionId = null
1484
+ if (!wasLive) return
1485
+ this._log.warn(`MCP server ${this.name}: Streamable HTTP session expired (HTTP 404 on ${method}) — marking the server dead`)
1486
+ // Abort any other in-flight requests against the now-dead session so no
1487
+ // reader/stream lingers past the transition (the request that observed the
1488
+ // 404 has already resolved; aborting its controller is a no-op). Clear the
1489
+ // set after aborting — mirroring destroy() — so the DEAD transition retains
1490
+ // no now-aborted controllers and a later destroy() repeats no abort work.
1491
+ for (const c of this._controllers) { try { c.abort() } catch { /* already settled */ } }
1492
+ this._controllers.clear()
1493
+ this._toDead()
1494
+ }
1495
+
1496
+ async _discardBody(res) {
1497
+ try {
1498
+ if (res?.body && typeof res.body.cancel === 'function') await res.body.cancel()
1499
+ else if (res && typeof res.arrayBuffer === 'function') await res.arrayBuffer()
1500
+ } catch { /* nothing to drain */ }
1501
+ }
1502
+
1503
+ _rejectAllPending(err) {
1504
+ for (const settle of this._pending.values()) {
1505
+ try { settle({ id: null, error: { message: err.message } }) } catch { /* already settled */ }
1506
+ }
1507
+ this._pending.clear()
1508
+ }
1509
+
1510
+ _toDead() {
1511
+ this._tools = []
1512
+ // #6823: parity with the stdio client — a dead remote server contributes
1513
+ // zero prompts/resources.
1514
+ this._prompts = []
1515
+ this._resources = []
1516
+ this._rejectAllPending(new Error('MCP remote client dead'))
1517
+ this._setState(MCP_STATES.DEAD)
1518
+ this.emit('dead')
1519
+ }
1520
+
1521
+ _setState(next) {
1522
+ if (this._state === next) return
1523
+ const prev = this._state
1524
+ this._state = next
1525
+ this.emit('state', { prev, next })
1526
+ }
1527
+ }
1528
+
1529
+ /**
1530
+ * Pick the transport for a parsed MCP server config (#6821). A `url` selects
1531
+ * the remote (Streamable HTTP / SSE) client; otherwise the stdio child-process
1532
+ * client. Keeps byok-mcp-fleet.js transport-agnostic — it just calls this.
1533
+ */
1534
+ export function createMcpClient(config, opts = {}) {
1535
+ const isRemote = typeof config?.url === 'string' && config.url.length > 0
1536
+ return isRemote ? new MCPRemoteClient(config, opts) : new MCPClient(config, opts)
1537
+ }