@chroxy/server 0.10.0 → 0.11.0

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 (160) hide show
  1. package/CONFIG.md +411 -14
  2. package/hooks/permission-hook.sh +253 -3
  3. package/package.json +8 -15
  4. package/sidecar/node_modules/.package-lock.json +29 -0
  5. package/sidecar/node_modules/ws/LICENSE +20 -0
  6. package/sidecar/node_modules/ws/README.md +548 -0
  7. package/sidecar/node_modules/ws/browser.js +8 -0
  8. package/sidecar/node_modules/ws/index.js +22 -0
  9. package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
  10. package/sidecar/node_modules/ws/lib/constants.js +19 -0
  11. package/sidecar/node_modules/ws/lib/event-target.js +292 -0
  12. package/sidecar/node_modules/ws/lib/extension.js +203 -0
  13. package/sidecar/node_modules/ws/lib/limiter.js +55 -0
  14. package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
  15. package/sidecar/node_modules/ws/lib/receiver.js +706 -0
  16. package/sidecar/node_modules/ws/lib/sender.js +602 -0
  17. package/sidecar/node_modules/ws/lib/stream.js +161 -0
  18. package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
  19. package/sidecar/node_modules/ws/lib/validation.js +152 -0
  20. package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
  21. package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
  22. package/sidecar/node_modules/ws/package.json +70 -0
  23. package/sidecar/node_modules/ws/wrapper.mjs +21 -0
  24. package/src/base-session.js +151 -6
  25. package/src/billing-budget.js +5 -1
  26. package/src/binary-provenance-trust.js +95 -0
  27. package/src/built-in-tools/file-ops.js +5 -4
  28. package/src/byok-mcp-client.js +1061 -13
  29. package/src/byok-mcp-config.js +1201 -4
  30. package/src/byok-mcp-fleet.js +374 -29
  31. package/src/byok-mcp-oauth-store.js +327 -0
  32. package/src/byok-mcp-oauth.js +635 -0
  33. package/src/byok-mcp-trust.js +254 -37
  34. package/src/byok-session.js +789 -13
  35. package/src/byok-tool-executor.js +20 -13
  36. package/src/checkpoint-manager.js +33 -6
  37. package/src/chroxy-host-metadata.js +122 -0
  38. package/src/claude-stream-parser.js +56 -0
  39. package/src/claude-tui/pty-driver.js +54 -14
  40. package/src/claude-tui-session.js +106 -7
  41. package/src/cli/config-cmd.js +2 -2
  42. package/src/cli/deploy-cmd.js +1 -1
  43. package/src/cli/init-cmd.js +1 -1
  44. package/src/cli/providers-cmd.js +3 -3
  45. package/src/cli/schedule-cmd.js +775 -0
  46. package/src/cli/server-cmd.js +16 -1
  47. package/src/cli/service-cmd.js +39 -19
  48. package/src/cli/shared.js +7 -4
  49. package/src/cli/tokens-cmd.js +213 -0
  50. package/src/cli/tunnel-cmd.js +1 -1
  51. package/src/cli-session.js +66 -10
  52. package/src/cli.js +4 -0
  53. package/src/codex-app-server-session.js +671 -39
  54. package/src/codex-session.js +121 -18
  55. package/src/config.js +453 -27
  56. package/src/control-room/integrations.js +16 -10
  57. package/src/control-room/skills-inventory.js +6 -1
  58. package/src/control-room/survey.js +32 -0
  59. package/src/credential-store.js +256 -10
  60. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  61. package/src/diagnostics.js +3 -0
  62. package/src/docker-sdk-session.js +16 -1
  63. package/src/docker-session.js +9 -0
  64. package/src/doctor.js +19 -8
  65. package/src/environments/backends/docker.js +8 -0
  66. package/src/environments/backends/k8s.js +9 -0
  67. package/src/event-ingest.js +19 -1
  68. package/src/event-normalizer.js +354 -19
  69. package/src/external-session-registry.js +0 -0
  70. package/src/gemini-session.js +19 -2
  71. package/src/github-webhook.js +188 -4
  72. package/src/handler-utils.js +42 -8
  73. package/src/handlers/checkpoint-handlers.js +126 -19
  74. package/src/handlers/control-room-handlers.js +48 -18
  75. package/src/handlers/conversation-handlers.js +127 -2
  76. package/src/handlers/credential-handlers.js +43 -2
  77. package/src/handlers/file-handlers.js +47 -3
  78. package/src/handlers/github-webhook-handlers.js +204 -0
  79. package/src/handlers/input-handlers.js +4 -0
  80. package/src/handlers/orchestration-handlers.js +238 -0
  81. package/src/handlers/scheduler-handlers.js +510 -0
  82. package/src/handlers/session-handlers.js +10 -2
  83. package/src/handlers/settings-handlers.js +510 -11
  84. package/src/handlers/token-handlers.js +11 -2
  85. package/src/http-routes.js +159 -0
  86. package/src/jsonl-reader.js +60 -6
  87. package/src/jsonl-subprocess-session.js +35 -6
  88. package/src/keychain.js +159 -12
  89. package/src/logger.js +182 -19
  90. package/src/notification-prefs.js +88 -6
  91. package/src/notifications/discord-webhook-sink.js +30 -1
  92. package/src/orchestration/build-manager.js +56 -0
  93. package/src/orchestration/decision-contract.js +245 -0
  94. package/src/orchestration/git-ops.js +347 -0
  95. package/src/orchestration/orchestration-manager.js +1295 -0
  96. package/src/orchestration/permission-gate.js +109 -0
  97. package/src/orchestration/role-prompts.js +136 -0
  98. package/src/orchestration/run-budget.js +81 -0
  99. package/src/orchestration/run-ledger.js +487 -0
  100. package/src/orchestration/run-model.js +205 -0
  101. package/src/orchestration/run-record.js +336 -0
  102. package/src/orchestration/run-report.js +194 -0
  103. package/src/orchestration/to-wire.js +201 -0
  104. package/src/orchestration/turn-driver.js +398 -0
  105. package/src/pairing.js +146 -1
  106. package/src/permission-audit.js +79 -3
  107. package/src/permission-floor.js +455 -0
  108. package/src/permission-manager.js +492 -40
  109. package/src/permission-resolver.js +55 -7
  110. package/src/permission-rule-store.js +411 -0
  111. package/src/platform.js +367 -23
  112. package/src/providers.js +21 -2
  113. package/src/schedule-parser.js +311 -0
  114. package/src/scheduled-task-store.js +653 -0
  115. package/src/scheduler.js +1029 -0
  116. package/src/sdk-session.js +338 -5
  117. package/src/server-cli/server-orchestrator.js +23 -0
  118. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  119. package/src/server-cli.js +238 -26
  120. package/src/server-identity.js +28 -4
  121. package/src/service.js +291 -33
  122. package/src/session-manager.js +417 -25
  123. package/src/session-message-history.js +27 -21
  124. package/src/session-title.js +168 -0
  125. package/src/session-token-store.js +60 -35
  126. package/src/skills-usage.js +20 -2
  127. package/src/statusline.js +584 -0
  128. package/src/subagent-counter.js +9 -1
  129. package/src/supervisor.js +77 -27
  130. package/src/token-manager.js +39 -9
  131. package/src/transcript-tasks.js +41 -6
  132. package/src/tunnel/cloudflare.js +115 -8
  133. package/src/tunnel/index.js +4 -1
  134. package/src/tunnel-check.js +1 -1
  135. package/src/turn-tracker.js +0 -0
  136. package/src/usage-normalize.js +118 -0
  137. package/src/user-shell-session.js +98 -32
  138. package/src/utils/componentwise-resolver.js +205 -0
  139. package/src/utils/composite-key.js +45 -0
  140. package/src/utils/iso-datetime.js +51 -0
  141. package/src/utils/preflight.js +140 -28
  142. package/src/utils/spawn-env.js +8 -2
  143. package/src/utils/verify-binary.js +276 -0
  144. package/src/utils/verify-provenance.js +241 -0
  145. package/src/utils/wire-counters.js +48 -0
  146. package/src/worktree-gc.js +4 -1
  147. package/src/ws-file-ops/browser.js +42 -11
  148. package/src/ws-file-ops/common.js +68 -1
  149. package/src/ws-file-ops/git.js +221 -3
  150. package/src/ws-file-ops/index.js +5 -0
  151. package/src/ws-file-ops/memory.js +358 -0
  152. package/src/ws-file-ops/reader.js +124 -0
  153. package/src/ws-forwarding.js +44 -16
  154. package/src/ws-handler-context.js +19 -0
  155. package/src/ws-history.js +84 -11
  156. package/src/ws-message-handlers.js +6 -0
  157. package/src/ws-outbound-schemas.js +207 -0
  158. package/src/ws-permissions.js +285 -4
  159. package/src/ws-schemas.js +1 -0
  160. package/src/ws-server.js +301 -17
@@ -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'
33
+ import { isBlockedMetadataHost } from './byok-mcp-config.js'
26
34
  import { CHROXY_SECRET_DENYLIST } 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')
@@ -238,15 +261,78 @@ export class MCPClient extends EventEmitter {
238
261
  if (typeof serverVersion === 'string' && serverVersion !== MCP_PROTOCOL_VERSION) {
239
262
  this._log.warn(`MCP server ${this.name}: protocolVersion mismatch — requested=${MCP_PROTOCOL_VERSION} server=${serverVersion} (negotiating to server value)`)
240
263
  }
264
+ // #6823: remember the server's advertised capabilities so the
265
+ // prompts/resources list calls below are only made when the server
266
+ // actually implements them.
267
+ this._serverCapabilities =
268
+ initResult.capabilities && typeof initResult.capabilities === 'object'
269
+ ? initResult.capabilities
270
+ : {}
241
271
  this._notify('notifications/initialized')
242
272
  const toolsResult = await this._request('tools/list', {}, this._handshakeTimeoutMs)
243
273
  const tools = Array.isArray(toolsResult?.tools) ? toolsResult.tools : []
244
274
  this._tools = Object.freeze(tools.map((t) => Object.freeze({ ...t })))
275
+ // #6823: capability-gated prompts/list + resources/list. A failure here is
276
+ // NON-fatal — the server is otherwise usable for tools, so we log at debug
277
+ // and leave the list empty rather than failing the handshake into a restart
278
+ // loop (see _loadListing).
279
+ if (this._serverCapabilities.prompts) {
280
+ this._prompts = await this._loadListing('prompts/list', 'prompts')
281
+ }
282
+ if (this._serverCapabilities.resources) {
283
+ this._resources = await this._loadListing('resources/list', 'resources')
284
+ }
245
285
  this._restartAttempts = 0
246
286
  this._setState(MCP_STATES.READY)
247
287
  this.emit('ready', this._tools)
248
288
  }
249
289
 
290
+ /**
291
+ * #6823: fetch a capability-gated list (prompts/list or resources/list),
292
+ * returning a frozen array. Errors (timeout, method-not-found from a server
293
+ * that advertised the capability but doesn't honour the request, malformed
294
+ * result) degrade to an empty list with a debug log — never a throw, so the
295
+ * handshake still reaches READY on the strength of tools alone.
296
+ */
297
+ async _loadListing(method, field) {
298
+ try {
299
+ const result = await this._request(method, {}, this._handshakeTimeoutMs)
300
+ const list = Array.isArray(result?.[field]) ? result[field] : []
301
+ return Object.freeze(list.map((item) => Object.freeze({ ...item })))
302
+ } catch (err) {
303
+ this._log.debug(`MCP server ${this.name}: ${method} failed: ${err?.message || err}`)
304
+ return []
305
+ }
306
+ }
307
+
308
+ /**
309
+ * #6823: fetch one prompt's messages (MCP `prompts/get`). `args` is the
310
+ * caller-supplied argument map; omitted from the request when empty so
311
+ * no-argument prompts stay first-class. Throws when the server is not READY
312
+ * or the JSON-RPC call errors (a missing required argument surfaces here).
313
+ */
314
+ async getPrompt(name, args, timeoutMs = DEFAULT_TOOL_CALL_TIMEOUT_MS) {
315
+ if (this._state !== MCP_STATES.READY) {
316
+ throw new Error(`MCP server ${this.name} not ready (state=${this._state})`)
317
+ }
318
+ const params = { name }
319
+ if (args && typeof args === 'object' && Object.keys(args).length > 0) {
320
+ params.arguments = args
321
+ }
322
+ return this._request('prompts/get', params, timeoutMs)
323
+ }
324
+
325
+ /**
326
+ * #6823: read one resource's contents (MCP `resources/read`). Throws when the
327
+ * server is not READY or the JSON-RPC call errors.
328
+ */
329
+ async readResource(uri, timeoutMs = DEFAULT_TOOL_CALL_TIMEOUT_MS) {
330
+ if (this._state !== MCP_STATES.READY) {
331
+ throw new Error(`MCP server ${this.name} not ready (state=${this._state})`)
332
+ }
333
+ return this._request('resources/read', { uri }, timeoutMs)
334
+ }
335
+
250
336
  async callTool(toolName, args, timeoutMs = DEFAULT_TOOL_CALL_TIMEOUT_MS) {
251
337
  if (this._state !== MCP_STATES.READY) {
252
338
  throw new Error(`MCP server ${this.name} not ready (state=${this._state})`)
@@ -334,6 +420,11 @@ export class MCPClient extends EventEmitter {
334
420
  if (!wasStartingOrReady) return
335
421
 
336
422
  this._tools = []
423
+ // #6823: a dead server contributes zero prompts/resources too, mirroring
424
+ // the tools reset so a crashed-then-restart-exhausted server cleanly
425
+ // disappears from the next turn's slash-command + resource surfaces.
426
+ this._prompts = []
427
+ this._resources = []
337
428
  this._restartAttempts += 1
338
429
  // #4453: gate on `>` (not `>=`) so the FULL RESTART_BACKOFF_MS schedule
339
430
  // is consumed before declaring DEAD. Pre-#4453 the gate fired on `>=`
@@ -402,3 +493,960 @@ export class MCPClient extends EventEmitter {
402
493
  this.emit('state', { prev, next })
403
494
  }
404
495
  }
496
+
497
+ // ---------------------------------------------------------------------------
498
+ // Remote transport (#6821): MCP Streamable HTTP + legacy HTTP+SSE.
499
+ // ---------------------------------------------------------------------------
500
+
501
+ /**
502
+ * Iterate a fetch response body as chunks. Node's `fetch` returns a web
503
+ * ReadableStream (undici); prefer async iteration when available, else fall
504
+ * back to an explicit reader so the SSE loop works across node versions.
505
+ */
506
+ async function* iterateStream(stream) {
507
+ if (!stream) return
508
+ if (typeof stream[Symbol.asyncIterator] === 'function') {
509
+ yield* stream
510
+ return
511
+ }
512
+ const reader = stream.getReader()
513
+ try {
514
+ for (;;) {
515
+ const { value, done } = await reader.read()
516
+ if (done) return
517
+ if (value) yield value
518
+ }
519
+ } finally {
520
+ try { reader.releaseLock() } catch { /* stream already closed */ }
521
+ }
522
+ }
523
+
524
+ /**
525
+ * Parse one SSE event block into `{ event, data }`. Per the SSE grammar a
526
+ * `data:` field drops a single leading space and multiple `data:` lines join
527
+ * with newlines; `id:`/`retry:`/comment (`:`) lines are ignored — we only
528
+ * need the event name and its JSON-RPC data payload.
529
+ */
530
+ function parseSseEvent(rawEvent) {
531
+ let event = 'message'
532
+ const dataLines = []
533
+ for (const line of rawEvent.split('\n')) {
534
+ if (line.length === 0 || line.startsWith(':')) continue
535
+ if (line.startsWith('event:')) event = line.slice(6).replace(/^ /, '').trim()
536
+ else if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, ''))
537
+ }
538
+ return { event, data: dataLines.length > 0 ? dataLines.join('\n') : null }
539
+ }
540
+
541
+ /** Parse a POST body (single object or JSON-RPC batch array) for the response matching `id`. */
542
+ function extractJsonRpcResponse(text, id) {
543
+ let parsed
544
+ try { parsed = JSON.parse(text) } catch { return null }
545
+ const list = Array.isArray(parsed) ? parsed : [parsed]
546
+ return list.find((m) => m && m.id === id) || null
547
+ }
548
+
549
+ export class MCPRemoteClient extends EventEmitter {
550
+ constructor(config, opts = {}) {
551
+ super()
552
+ this.name = config.name
553
+ this._config = config
554
+ this._log = opts.log || createLogger('byok-mcp')
555
+ // Injectable HTTP client (defaults to the global fetch), mirroring the
556
+ // fetchImpl seam in get-public-ip / discord-webhook-client so tests can
557
+ // drive the transport against an in-process http server. fetch is a node
558
+ // primitive — no new npm dependency, consistent with the hand-rolled
559
+ // stdio client above.
560
+ this._fetchImpl = opts.fetchImpl || globalThis.fetch
561
+ // #4457 parity: optional async trust gate consulted before the first
562
+ // connect. true → proceed; false / throw → permanent DEAD, no request
563
+ // ever leaves the process.
564
+ this._trustGate = opts.trustGate || null
565
+ // #4454 parity: per-request handshake timeout. Same precedence + defensive
566
+ // guard as the stdio client (opts > config > module default).
567
+ this._handshakeTimeoutMs =
568
+ (Number.isFinite(opts.handshakeTimeoutMs) && opts.handshakeTimeoutMs > 0 && opts.handshakeTimeoutMs) ||
569
+ (Number.isFinite(config?.handshakeTimeoutMs) && config.handshakeTimeoutMs > 0 && config.handshakeTimeoutMs) ||
570
+ DEFAULT_HANDSHAKE_TIMEOUT_MS
571
+ this._url = config.url
572
+ // 'sse' → legacy HTTP+SSE two-endpoint transport; anything else → modern
573
+ // Streamable HTTP (single endpoint, POST + optional SSE-upgraded response).
574
+ this._transportType = config.type === 'sse' ? 'sse' : 'http'
575
+ this._headers = config.headers || {}
576
+ this._state = MCP_STATES.IDLE
577
+ this._tools = []
578
+ // #6823: MCP prompts + resources — same capability-gated lifecycle as the
579
+ // stdio client. Populated after tools/list, only when the server advertises
580
+ // the capability on initialize; cleared on death.
581
+ this._prompts = []
582
+ this._resources = []
583
+ this._serverCapabilities = null
584
+ this._nextId = 1
585
+ this._sessionId = null
586
+ this._negotiatedProtocolVersion = null
587
+ // 'oauth-required' after a 401/407 that the OAuth flow (#6822) could not
588
+ // silently satisfy — the client surfaces `authorizationUrl` for the user to
589
+ // open. null otherwise. Never carries any header/token value.
590
+ this._statusReason = null
591
+ // #6822 OAuth 2.1 + PKCE for a remote server that answers 401. Injectable
592
+ // seams (default the real modules) keep the flow testable against an
593
+ // in-process mock AS/RS with no real network + no real keychain.
594
+ this._oauthEnabled = opts.oauthEnabled !== false
595
+ this._oauthFlow = opts.oauthFlow || realOAuthFlow
596
+ this._oauthStore = opts.oauthStore || realOAuthStore
597
+ // The redirect_uri the daemon registers + surfaces. Defaults to the
598
+ // configured daemon callback (loopback/tunnel); tests pass a fixed value.
599
+ this._oauthRedirectUri = opts.oauthRedirectUri || null
600
+ // Bearer access token (from a stored record or a completed authorization).
601
+ // Merged into every request's headers via `_authHeader()` — OAuth wins over
602
+ // any static Authorization header the config carried.
603
+ this._accessToken = null
604
+ // The browser authorization URL surfaced to clients while `oauth-required`.
605
+ this._authorizationUrl = null
606
+ // Server-side PKCE/state/token-endpoint bag from beginAuthorization, consumed
607
+ // by completeAuthorization. Holds secret material — never logged/surfaced.
608
+ this._authPending = null
609
+ // Guards a single proactive/reactive refresh attempt per start() so a broken
610
+ // refresh token can't spin the connect loop.
611
+ this._refreshAttempted = false
612
+ this._destroyed = false
613
+ // In-flight AbortControllers, aborted on destroy() so a hung request or a
614
+ // persistent SSE stream cannot keep the process alive after teardown.
615
+ this._controllers = new Set()
616
+ // Legacy-SSE only: resolved POST endpoint + pending-request registry
617
+ // (streamable HTTP awaits each POST inline, so it leaves these empty).
618
+ this._endpointUrl = null
619
+ this._pending = new Map()
620
+ this._endpointTimer = null
621
+ this._endpointResolve = null
622
+ this._endpointReject = null
623
+ }
624
+
625
+ get state() { return this._state }
626
+ get tools() { return this._tools }
627
+ get prompts() { return this._prompts }
628
+ get resources() { return this._resources }
629
+ get statusReason() { return this._statusReason }
630
+ /** #6822: the browser authorization URL to open while `oauth-required`, else null. */
631
+ get authorizationUrl() { return this._authorizationUrl }
632
+ /** #6822: true when this server is waiting for the user to complete OAuth. */
633
+ get needsAuthorization() { return this._statusReason === 'oauth-required' }
634
+
635
+ async start() {
636
+ if (this._destroyed) throw new Error('MCPRemoteClient destroyed')
637
+ if (this._state === MCP_STATES.READY || this._state === MCP_STATES.DEAD) return
638
+ // #6834 sharp edge, folded in pre-merge: unconditionally refuse
639
+ // cloud-metadata / link-local targets at REQUEST time too (parse already
640
+ // rejects them; this guards configs constructed programmatically). Checked
641
+ // before the trust gate so the user is never prompted to trust a URL we
642
+ // will refuse regardless.
643
+ const refusal = await this._refuseMetadataTarget()
644
+ if (refusal) {
645
+ this._log.warn(`MCP server ${this.name}: ${refusal}`)
646
+ this._toDead()
647
+ return
648
+ }
649
+ // #4457 parity: trust gate fires BEFORE any network request. Deny/throw →
650
+ // permanent DEAD, fail-closed.
651
+ if (this._trustGate) {
652
+ let allowed
653
+ try {
654
+ allowed = await this._trustGate()
655
+ } catch (err) {
656
+ this._log.warn(`MCP server ${this.name}: trust gate threw: ${err?.message || err}`)
657
+ allowed = false
658
+ }
659
+ if (!allowed) {
660
+ this._toDead()
661
+ return
662
+ }
663
+ }
664
+ // #6822: prime a stored access token (refreshing it up front if expired) so a
665
+ // previously-authorized server reconnects with no user prompt.
666
+ await this._prepareStoredToken()
667
+ this._setState(MCP_STATES.STARTING)
668
+ try {
669
+ await this._attemptConnect()
670
+ if (this._destroyed) { this._setState(MCP_STATES.DESTROYED); return }
671
+ this._setState(MCP_STATES.READY)
672
+ this.emit('ready', this._tools)
673
+ } catch (err) {
674
+ if (this._destroyed) { this._setState(MCP_STATES.DESTROYED); return }
675
+ if (err && err._oauthRequired) {
676
+ await this._onOAuthRequired(err)
677
+ return
678
+ }
679
+ this._log.warn(`MCP server ${this.name}: connect failed: ${err?.message || err}`)
680
+ this._toDead()
681
+ }
682
+ }
683
+
684
+ /** Run the transport handshake once (fresh transport counters each attempt). */
685
+ async _attemptConnect() {
686
+ this._resetTransportState()
687
+ if (this._transportType === 'sse') await this._connectLegacySse()
688
+ else await this._handshakeStreamableHttp()
689
+ }
690
+
691
+ /** Reset per-connection transport state so a re-attempt starts clean (#6822). */
692
+ _resetTransportState() {
693
+ this._sessionId = null
694
+ this._negotiatedProtocolVersion = null
695
+ this._nextId = 1
696
+ this._endpointUrl = null
697
+ this._rejectAllPending(new Error('reconnecting'))
698
+ }
699
+
700
+ /**
701
+ * #6822: a connect answered 401/407. Try, in order:
702
+ * 1. a silent refresh (an existing-but-expired token whose refresh works) →
703
+ * reconnect authenticated;
704
+ * 2. begin a browser authorization — discover the AS, register a client, and
705
+ * surface the authorization URL (status `oauth-required`).
706
+ * Any failure falls through to a value-free `oauth-required` DEAD state.
707
+ */
708
+ async _onOAuthRequired(err) {
709
+ // (1) silent refresh of an existing token.
710
+ if (this._oauthEnabled && this._accessToken && !this._refreshAttempted) {
711
+ this._refreshAttempted = true
712
+ const refreshed = await this._tryRefresh()
713
+ if (refreshed && !this._destroyed) {
714
+ try {
715
+ await this._attemptConnect()
716
+ if (this._destroyed) { this._setState(MCP_STATES.DESTROYED); return }
717
+ this._setState(MCP_STATES.READY)
718
+ this.emit('ready', this._tools)
719
+ return
720
+ } catch (retryErr) {
721
+ if (this._destroyed) { this._setState(MCP_STATES.DESTROYED); return }
722
+ if (!(retryErr && retryErr._oauthRequired)) {
723
+ this._log.warn(`MCP server ${this.name}: reconnect after refresh failed: ${retryErr?.message || retryErr}`)
724
+ this._toDead()
725
+ return
726
+ }
727
+ // Refresh succeeded but the server still rejects — fall through to a
728
+ // fresh browser authorization below.
729
+ err = retryErr
730
+ }
731
+ }
732
+ }
733
+ // (2) begin browser authorization.
734
+ await this._beginBrowserAuthorization(err)
735
+ }
736
+
737
+ /**
738
+ * Attempt to refresh the stored token in place. Returns true on success (with
739
+ * `_accessToken` updated + the record persisted), false otherwise. The stored
740
+ * record is left intact on failure so a subsequent full re-auth can replace it.
741
+ */
742
+ async _tryRefresh() {
743
+ let record
744
+ try { record = this._oauthStore.getStoredToken(this._url) } catch { record = null }
745
+ if (!record || !record.refreshToken || !record.tokenEndpoint) return false
746
+ try {
747
+ const tokens = await this._oauthFlow.refreshAccessToken({
748
+ tokenEndpoint: record.tokenEndpoint,
749
+ clientId: record.clientId,
750
+ clientSecret: record.clientSecret,
751
+ refreshToken: record.refreshToken,
752
+ scope: record.scope,
753
+ resource: record.resource,
754
+ fetchImpl: this._fetchImpl,
755
+ })
756
+ const next = { ...record, ...tokens }
757
+ this._oauthStore.setStoredToken(this._url, next)
758
+ this._accessToken = next.accessToken
759
+ return true
760
+ } catch (refreshErr) {
761
+ this._log.debug(`MCP server ${this.name}: token refresh failed: ${refreshErr?.message || refreshErr}`)
762
+ return false
763
+ }
764
+ }
765
+
766
+ /**
767
+ * Discover + register + build the authorization URL, surfacing it as
768
+ * `oauth-required`. Registers a callback keyed by the flow's `state` so the
769
+ * daemon's loopback/tunnel callback can auto-complete; the paste-code path
770
+ * (completeAuthorization) is the universal fallback. Never throws.
771
+ */
772
+ async _beginBrowserAuthorization(err) {
773
+ const redirectUri = this._oauthRedirectUri || this._oauthFlow.mcpOAuthRedirectUri?.()
774
+ if (!this._oauthEnabled || !redirectUri) {
775
+ this._statusReason = 'oauth-required'
776
+ this._log.warn(`MCP server ${this.name}: requires OAuth but the flow is disabled or no redirect URI is configured`)
777
+ this._toDead()
778
+ return
779
+ }
780
+ try {
781
+ const { authorizationUrl, pending } = await this._oauthFlow.beginAuthorization({
782
+ serverUrl: this._url,
783
+ wwwAuthenticate: err?._wwwAuthenticate || null,
784
+ redirectUri,
785
+ fetchImpl: this._fetchImpl,
786
+ log: this._log,
787
+ })
788
+ if (this._destroyed) { this._setState(MCP_STATES.DESTROYED); return }
789
+ this._authPending = pending
790
+ this._authorizationUrl = authorizationUrl
791
+ this._statusReason = 'oauth-required'
792
+ // Register the loopback/tunnel auto-complete handler. The paste-code path
793
+ // shares completeAuthorization, so both redemption routes are equivalent.
794
+ try {
795
+ this._oauthFlow.registerOAuthCallback?.(pending.state, (code) => this.completeAuthorization(code))
796
+ } catch { /* registry is best-effort — paste-code still works */ }
797
+ this._log.info(`MCP server ${this.name}: OAuth authorization required — surfaced an authorization URL`)
798
+ } catch (authErr) {
799
+ this._statusReason = 'oauth-required'
800
+ this._log.warn(`MCP server ${this.name}: could not begin OAuth authorization: ${authErr?.message || authErr}`)
801
+ }
802
+ // Not ready — DEAD until a code is submitted (contributes zero tools). The
803
+ // oauth-required fields survive _toDead so the fleet can surface them.
804
+ this._toDead()
805
+ }
806
+
807
+ /**
808
+ * #6822: complete an authorization by redeeming `code` against the pending
809
+ * PKCE/state bag, persisting the tokens, and reconnecting authenticated. Shared
810
+ * by the loopback callback and the paste-code wire path. Throws (value-free) on
811
+ * redemption failure; resolves once the reconnect settles.
812
+ *
813
+ * @param {string} code
814
+ * @returns {Promise<{ ok: true }>}
815
+ */
816
+ async completeAuthorization(code) {
817
+ if (this._destroyed) throw new Error('MCPRemoteClient destroyed')
818
+ if (!this._authPending) throw new Error(`MCP server ${this.name}: no pending authorization`)
819
+ if (typeof code !== 'string' || !code.trim()) throw new Error('an authorization code is required')
820
+ const pending = this._authPending
821
+ const record = await this._oauthFlow.completeAuthorization({
822
+ pending,
823
+ code: code.trim(),
824
+ fetchImpl: this._fetchImpl,
825
+ })
826
+ this._oauthStore.setStoredToken(this._url, record)
827
+ this._accessToken = record.accessToken
828
+ // Clear the pending-auth surface and reconnect.
829
+ try { this._oauthFlow.unregisterOAuthCallback?.(pending.state) } catch { /* best-effort */ }
830
+ this._authPending = null
831
+ this._authorizationUrl = null
832
+ this._statusReason = null
833
+ this._refreshAttempted = false
834
+ this._state = MCP_STATES.IDLE
835
+ await this.start()
836
+ return { ok: true }
837
+ }
838
+
839
+ /**
840
+ * Load a stored token for this server, refreshing it up front when expired.
841
+ * Sets `_accessToken` when a usable token is available. Read/refresh failures
842
+ * degrade to unauthenticated (the connect then 401s and re-authorizes).
843
+ */
844
+ async _prepareStoredToken() {
845
+ this._refreshAttempted = false
846
+ if (!this._oauthEnabled) return
847
+ let record
848
+ try { record = this._oauthStore.getStoredToken(this._url) } catch { record = null }
849
+ if (!record) return
850
+ if (this._oauthStore.isTokenExpired(record)) {
851
+ this._refreshAttempted = true
852
+ const refreshed = await this._tryRefresh()
853
+ if (!refreshed) this._accessToken = null
854
+ return
855
+ }
856
+ this._accessToken = record.accessToken
857
+ }
858
+
859
+ /**
860
+ * Dispatch a single JSON-RPC request over whichever transport this client
861
+ * negotiated (legacy SSE endpoint vs Streamable HTTP POST). Shared by
862
+ * callTool / getPrompt / readResource so the transport branch lives in one
863
+ * place (#6823).
864
+ */
865
+ _rpc(method, params, timeoutMs) {
866
+ return this._transportType === 'sse'
867
+ ? this._rpcViaEndpoint(method, params, timeoutMs)
868
+ : this._rpcPost(method, params, timeoutMs)
869
+ }
870
+
871
+ async callTool(toolName, args, timeoutMs = DEFAULT_TOOL_CALL_TIMEOUT_MS) {
872
+ if (this._state !== MCP_STATES.READY) {
873
+ throw new Error(`MCP server ${this.name} not ready (state=${this._state})`)
874
+ }
875
+ return this._rpc('tools/call', { name: toolName, arguments: args || {} }, timeoutMs)
876
+ }
877
+
878
+ /** #6823: MCP `prompts/get` — parity with the stdio client's getPrompt. */
879
+ async getPrompt(name, args, timeoutMs = DEFAULT_TOOL_CALL_TIMEOUT_MS) {
880
+ if (this._state !== MCP_STATES.READY) {
881
+ throw new Error(`MCP server ${this.name} not ready (state=${this._state})`)
882
+ }
883
+ const params = { name }
884
+ if (args && typeof args === 'object' && Object.keys(args).length > 0) {
885
+ params.arguments = args
886
+ }
887
+ return this._rpc('prompts/get', params, timeoutMs)
888
+ }
889
+
890
+ /** #6823: MCP `resources/read` — parity with the stdio client's readResource. */
891
+ async readResource(uri, timeoutMs = DEFAULT_TOOL_CALL_TIMEOUT_MS) {
892
+ if (this._state !== MCP_STATES.READY) {
893
+ throw new Error(`MCP server ${this.name} not ready (state=${this._state})`)
894
+ }
895
+ return this._rpc('resources/read', { uri }, timeoutMs)
896
+ }
897
+
898
+ /**
899
+ * #6823: fetch a capability-gated list (prompts/list or resources/list) over
900
+ * the negotiated transport, degrading to an empty frozen array on any error —
901
+ * same non-fatal contract as the stdio client's _loadListing.
902
+ */
903
+ async _loadListing(method, field) {
904
+ try {
905
+ const result = await this._rpc(method, {}, this._handshakeTimeoutMs)
906
+ const list = Array.isArray(result?.[field]) ? result[field] : []
907
+ return Object.freeze(list.map((item) => Object.freeze({ ...item })))
908
+ } catch (err) {
909
+ this._log.debug(`MCP server ${this.name}: ${method} failed: ${err?.message || err}`)
910
+ return []
911
+ }
912
+ }
913
+
914
+ async destroy() {
915
+ if (this._destroyed) return
916
+ this._destroyed = true
917
+ if (this._endpointTimer) { clearTimeout(this._endpointTimer); this._endpointTimer = null }
918
+ // #6822: drop any pending-auth callback so a torn-down client can't be
919
+ // completed via the loopback registry after destroy.
920
+ if (this._authPending?.state) {
921
+ try { this._oauthFlow.unregisterOAuthCallback?.(this._authPending.state) } catch { /* best-effort */ }
922
+ }
923
+ this._rejectAllPending(new Error('MCP remote client destroyed'))
924
+ for (const c of this._controllers) { try { c.abort() } catch { /* already settled */ } }
925
+ this._controllers.clear()
926
+ // Best-effort Streamable HTTP session teardown (spec: DELETE with the
927
+ // session header). Bounded by KILL_GRACE_MS and fully error-swallowed —
928
+ // it must never make destroy() hang or throw.
929
+ if (this._transportType === 'http' && this._sessionId && typeof this._fetchImpl === 'function') {
930
+ const controller = new AbortController()
931
+ const timer = setTimeout(() => { try { controller.abort() } catch {} }, KILL_GRACE_MS)
932
+ try {
933
+ const res = await this._fetchImpl(this._url, {
934
+ method: 'DELETE',
935
+ headers: this._buildHeaders(),
936
+ redirect: 'manual', // #6834: never follow a redirect off-origin
937
+ signal: controller.signal,
938
+ })
939
+ await this._discardBody(res)
940
+ } catch { /* teardown is best-effort */ } finally {
941
+ clearTimeout(timer)
942
+ }
943
+ }
944
+ this._setState(MCP_STATES.DESTROYED)
945
+ }
946
+
947
+ // --- Streamable HTTP -----------------------------------------------------
948
+
949
+ async _handshakeStreamableHttp() {
950
+ const initResult = await this._rpcPost('initialize', {
951
+ protocolVersion: MCP_PROTOCOL_VERSION,
952
+ capabilities: {},
953
+ clientInfo: { name: 'chroxy-byok', version: MCP_CLIENT_VERSION },
954
+ }, this._handshakeTimeoutMs, { captureSession: true })
955
+ this._applyInitResult(initResult)
956
+ await this._notifyPost('notifications/initialized')
957
+ const toolsResult = await this._rpcPost('tools/list', {}, this._handshakeTimeoutMs)
958
+ this._setTools(toolsResult)
959
+ await this._loadPromptsAndResources()
960
+ }
961
+
962
+ /** POST one JSON-RPC request; resolve its result from a JSON or SSE-upgraded response. */
963
+ async _rpcPost(method, params, timeoutMs, { captureSession = false } = {}) {
964
+ const id = this._nextId++
965
+ const payload = JSON.stringify({ jsonrpc: '2.0', id, method, params })
966
+ const controller = new AbortController()
967
+ this._controllers.add(controller)
968
+ let timedOut = false
969
+ const timer = setTimeout(() => { timedOut = true; try { controller.abort() } catch {} }, timeoutMs)
970
+ try {
971
+ let res
972
+ try {
973
+ res = await this._fetchImpl(this._url, {
974
+ method: 'POST',
975
+ headers: this._buildHeaders({ json: true, acceptStream: true }),
976
+ body: payload,
977
+ // #6834: never auto-follow — a redirect must not carry our
978
+ // credentialed headers to a different origin. 3xx → _checkStatus throws.
979
+ redirect: 'manual',
980
+ signal: controller.signal,
981
+ })
982
+ } catch (err) {
983
+ if (timedOut) throw new Error(`MCP ${method} timeout`)
984
+ throw err
985
+ }
986
+ await this._checkStatus(res, method)
987
+ if (captureSession) {
988
+ const sid = res.headers.get('mcp-session-id')
989
+ if (sid) this._sessionId = sid
990
+ }
991
+ const contentType = (res.headers.get('content-type') || '').toLowerCase()
992
+ let message
993
+ if (contentType.includes('text/event-stream')) {
994
+ message = await this._readSseUntilId(res.body, id)
995
+ } else {
996
+ let text
997
+ try { text = await res.text() } catch (err) {
998
+ if (timedOut) throw new Error(`MCP ${method} timeout`)
999
+ throw err
1000
+ }
1001
+ message = extractJsonRpcResponse(text, id)
1002
+ }
1003
+ if (message == null) {
1004
+ if (timedOut) throw new Error(`MCP ${method} timeout`)
1005
+ throw new Error(`MCP ${method}: no matching JSON-RPC response`)
1006
+ }
1007
+ if (message.error) throw new Error(message.error?.message || `MCP ${method} RPC error`)
1008
+ return message.result
1009
+ } finally {
1010
+ clearTimeout(timer)
1011
+ this._controllers.delete(controller)
1012
+ }
1013
+ }
1014
+
1015
+ /** POST a JSON-RPC notification (no id, no response expected). Best-effort but honours a 401. */
1016
+ async _notifyPost(method, params) {
1017
+ const controller = new AbortController()
1018
+ this._controllers.add(controller)
1019
+ const timer = setTimeout(() => { try { controller.abort() } catch {} }, this._handshakeTimeoutMs)
1020
+ try {
1021
+ let res
1022
+ try {
1023
+ res = await this._fetchImpl(this._url, {
1024
+ method: 'POST',
1025
+ headers: this._buildHeaders({ json: true, acceptStream: true }),
1026
+ body: JSON.stringify({ jsonrpc: '2.0', method, params }),
1027
+ redirect: 'manual', // #6834: never follow a redirect off-origin
1028
+ signal: controller.signal,
1029
+ })
1030
+ } catch {
1031
+ return // initialize already succeeded; a lost `initialized` is non-fatal
1032
+ }
1033
+ if (res.status === 401 || res.status === 407) {
1034
+ throw this._oauthError(res, res.status)
1035
+ }
1036
+ await this._discardBody(res)
1037
+ } finally {
1038
+ clearTimeout(timer)
1039
+ this._controllers.delete(controller)
1040
+ }
1041
+ }
1042
+
1043
+ /** Read an SSE stream until the JSON-RPC response with `id` arrives (or the stream ends). */
1044
+ async _readSseUntilId(body, id) {
1045
+ if (!body) return null
1046
+ const decoder = new TextDecoder()
1047
+ let buf = ''
1048
+ for await (const chunk of iterateStream(body)) {
1049
+ buf += decoder.decode(chunk, { stream: true })
1050
+ buf = buf.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
1051
+ let idx
1052
+ while ((idx = buf.indexOf('\n\n')) !== -1) {
1053
+ const { data } = parseSseEvent(buf.slice(0, idx))
1054
+ buf = buf.slice(idx + 2)
1055
+ if (data == null) continue
1056
+ let msg
1057
+ try { msg = JSON.parse(data) } catch { continue }
1058
+ if (msg && msg.id === id) return msg
1059
+ // Server-initiated notifications/requests before the response: ignore.
1060
+ }
1061
+ }
1062
+ return null
1063
+ }
1064
+
1065
+ // --- Legacy HTTP+SSE (type: 'sse') ---------------------------------------
1066
+
1067
+ async _connectLegacySse() {
1068
+ const controller = new AbortController()
1069
+ this._controllers.add(controller)
1070
+ let res
1071
+ try {
1072
+ res = await this._fetchImpl(this._url, {
1073
+ method: 'GET',
1074
+ // #6822: include the OAuth bearer token (if any) on the SSE GET too, via
1075
+ // _applyOAuthHeader so a config-supplied `authorization` doesn't collide
1076
+ // with a fresh `Authorization` (two auth headers).
1077
+ headers: this._applyOAuthHeader({ ...this._headers, Accept: 'text/event-stream' }),
1078
+ redirect: 'manual', // #6834: never follow a redirect off-origin
1079
+ signal: controller.signal,
1080
+ })
1081
+ } catch (err) {
1082
+ this._controllers.delete(controller)
1083
+ throw err
1084
+ }
1085
+ if (res.status === 401 || res.status === 407) {
1086
+ throw this._oauthError(res, res.status)
1087
+ }
1088
+ if (res.status >= 300 && res.status < 400) {
1089
+ throw new Error(`MCP server ${this.name} HTTP ${res.status} redirect opening SSE stream — refused (redirects are not followed)`)
1090
+ }
1091
+ if (res.status < 200 || res.status >= 300) {
1092
+ throw new Error(`MCP server ${this.name} HTTP ${res.status} opening SSE stream`)
1093
+ }
1094
+ const endpointReady = new Promise((resolve, reject) => {
1095
+ this._endpointResolve = resolve
1096
+ this._endpointReject = reject
1097
+ this._endpointTimer = setTimeout(
1098
+ () => reject(new Error(`MCP server ${this.name}: timeout waiting for SSE endpoint`)),
1099
+ this._handshakeTimeoutMs,
1100
+ )
1101
+ })
1102
+ // Background dispatch loop: resolves the endpoint, then routes responses.
1103
+ this._runSseDispatchLoop(res.body)
1104
+ await endpointReady
1105
+ await this._legacyHandshake()
1106
+ }
1107
+
1108
+ async _legacyHandshake() {
1109
+ const initResult = await this._rpcViaEndpoint('initialize', {
1110
+ protocolVersion: MCP_PROTOCOL_VERSION,
1111
+ capabilities: {},
1112
+ clientInfo: { name: 'chroxy-byok', version: MCP_CLIENT_VERSION },
1113
+ }, this._handshakeTimeoutMs)
1114
+ this._applyInitResult(initResult)
1115
+ await this._notifyViaEndpoint('notifications/initialized')
1116
+ const toolsResult = await this._rpcViaEndpoint('tools/list', {}, this._handshakeTimeoutMs)
1117
+ this._setTools(toolsResult)
1118
+ await this._loadPromptsAndResources()
1119
+ }
1120
+
1121
+ async _runSseDispatchLoop(body) {
1122
+ const decoder = new TextDecoder()
1123
+ let buf = ''
1124
+ try {
1125
+ for await (const chunk of iterateStream(body)) {
1126
+ buf += decoder.decode(chunk, { stream: true })
1127
+ buf = buf.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
1128
+ let idx
1129
+ while ((idx = buf.indexOf('\n\n')) !== -1) {
1130
+ this._handleLegacyEvent(buf.slice(0, idx))
1131
+ buf = buf.slice(idx + 2)
1132
+ }
1133
+ }
1134
+ } catch (err) {
1135
+ if (!this._destroyed) this._log.debug(`MCP server ${this.name}: SSE stream error: ${err?.message || err}`)
1136
+ } finally {
1137
+ if (!this._destroyed) this._rejectAllPending(new Error('SSE stream closed'))
1138
+ }
1139
+ }
1140
+
1141
+ _handleLegacyEvent(rawEvent) {
1142
+ const { event, data } = parseSseEvent(rawEvent)
1143
+ if (event === 'endpoint') {
1144
+ if (!this._endpointResolve) return
1145
+ let endpoint = null
1146
+ try { endpoint = new URL(data, this._url) } catch { endpoint = null }
1147
+ if (this._endpointTimer) { clearTimeout(this._endpointTimer); this._endpointTimer = null }
1148
+ // #6834 sharp edge: the endpoint event is SERVER-SUPPLIED — an absolute
1149
+ // url here could pivot our credentialed POSTs (headers carry auth)
1150
+ // anywhere. Enforce SAME-ORIGIN (scheme+host+port, via URL.origin)
1151
+ // against the configured url; a cross-origin endpoint warns + rejects,
1152
+ // which fails the connect → DEAD. Origins are creds/query-free, so
1153
+ // logging them leaks nothing.
1154
+ let configuredOrigin = null
1155
+ try { configuredOrigin = new URL(this._url).origin } catch { /* refused below */ }
1156
+ if (endpoint && configuredOrigin && endpoint.origin === configuredOrigin) {
1157
+ this._endpointUrl = endpoint.toString()
1158
+ this._endpointResolve()
1159
+ } else if (endpoint && configuredOrigin) {
1160
+ this._log.warn(`MCP server ${this.name}: SSE endpoint origin ${endpoint.origin} != configured origin ${configuredOrigin} — refusing cross-origin endpoint`)
1161
+ this._endpointReject?.(new Error(`MCP server ${this.name}: cross-origin SSE endpoint refused`))
1162
+ } else {
1163
+ this._endpointReject?.(new Error(`MCP server ${this.name}: invalid SSE endpoint event`))
1164
+ }
1165
+ this._endpointResolve = null
1166
+ this._endpointReject = null
1167
+ return
1168
+ }
1169
+ if (data == null) return
1170
+ let msg
1171
+ try { msg = JSON.parse(data) } catch { return }
1172
+ if (msg && msg.id != null && this._pending.has(msg.id)) {
1173
+ const settle = this._pending.get(msg.id)
1174
+ settle(msg)
1175
+ }
1176
+ }
1177
+
1178
+ /** POST a JSON-RPC request to the legacy endpoint; await the response off the persistent SSE stream. */
1179
+ async _rpcViaEndpoint(method, params, timeoutMs) {
1180
+ if (!this._endpointUrl) throw new Error(`MCP server ${this.name}: no SSE endpoint`)
1181
+ const id = this._nextId++
1182
+ const responsePromise = new Promise((resolve) => {
1183
+ const timer = setTimeout(() => {
1184
+ this._pending.delete(id)
1185
+ resolve({ id, error: { message: `MCP ${method} timeout` } })
1186
+ }, timeoutMs)
1187
+ this._pending.set(id, (msg) => { clearTimeout(timer); this._pending.delete(id); resolve(msg) })
1188
+ })
1189
+ const controller = new AbortController()
1190
+ this._controllers.add(controller)
1191
+ const postTimer = setTimeout(() => { try { controller.abort() } catch {} }, timeoutMs)
1192
+ try {
1193
+ const res = await this._fetchImpl(this._endpointUrl, {
1194
+ method: 'POST',
1195
+ headers: this._buildHeaders({ json: true }),
1196
+ body: JSON.stringify({ jsonrpc: '2.0', id, method, params }),
1197
+ redirect: 'manual', // #6834: never follow a redirect off-origin
1198
+ signal: controller.signal,
1199
+ })
1200
+ await this._checkStatus(res, method)
1201
+ await this._discardBody(res)
1202
+ } catch (err) {
1203
+ this._pending.delete(id)
1204
+ throw err
1205
+ } finally {
1206
+ clearTimeout(postTimer)
1207
+ this._controllers.delete(controller)
1208
+ }
1209
+ const msg = await responsePromise
1210
+ if (msg.error) throw new Error(msg.error?.message || `MCP ${method} RPC error`)
1211
+ return msg.result
1212
+ }
1213
+
1214
+ async _notifyViaEndpoint(method, params) {
1215
+ if (!this._endpointUrl) return
1216
+ const controller = new AbortController()
1217
+ this._controllers.add(controller)
1218
+ const timer = setTimeout(() => { try { controller.abort() } catch {} }, this._handshakeTimeoutMs)
1219
+ try {
1220
+ let res
1221
+ try {
1222
+ res = await this._fetchImpl(this._endpointUrl, {
1223
+ method: 'POST',
1224
+ headers: this._buildHeaders({ json: true }),
1225
+ body: JSON.stringify({ jsonrpc: '2.0', method, params }),
1226
+ redirect: 'manual', // #6834: never follow a redirect off-origin
1227
+ signal: controller.signal,
1228
+ })
1229
+ } catch {
1230
+ return // network-level failure is best-effort — initialize already succeeded
1231
+ }
1232
+ // Same status semantics as every other call site (_checkStatus): 401/407
1233
+ // → oauth-required (propagates → DEAD), redirect/other non-2xx → error →
1234
+ // DEAD. Pre-fix this swallowed ALL statuses, letting the handshake
1235
+ // proceed past `initialized` while the server was rejecting our requests.
1236
+ await this._checkStatus(res, method)
1237
+ await this._discardBody(res)
1238
+ } finally {
1239
+ clearTimeout(timer)
1240
+ this._controllers.delete(controller)
1241
+ }
1242
+ }
1243
+
1244
+ // --- shared helpers ------------------------------------------------------
1245
+
1246
+ /**
1247
+ * Return a refusal reason when the configured url targets the cloud
1248
+ * metadata service / link-local range (#6834 sharp edge), else null.
1249
+ * Literal hosts are checked directly (the URL parser already canonicalized
1250
+ * hex/decimal tricks); DNS names get a best-effort lookup so a name
1251
+ * resolving into the blocked range is refused too. Lookup ERRORS pass
1252
+ * through — fetch will surface them as ordinary connect failures. Full
1253
+ * resolution pinning / DNS-rebinding defence stays in #6834.
1254
+ */
1255
+ async _refuseMetadataTarget() {
1256
+ let hostname
1257
+ try {
1258
+ hostname = new URL(this._url).hostname
1259
+ } catch {
1260
+ return null // fetch will surface the malformed url as a connect failure
1261
+ }
1262
+ if (isBlockedMetadataHost(hostname)) {
1263
+ return 'refusing cloud-metadata / link-local endpoint (never a legitimate MCP server)'
1264
+ }
1265
+ const bare = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname
1266
+ const isLiteral = /^[\d.]+$/.test(bare) || bare.includes(':')
1267
+ if (!isLiteral) {
1268
+ try {
1269
+ const addrs = await lookup(bare, { all: true })
1270
+ if (addrs.some(({ address }) => isBlockedMetadataHost(address))) {
1271
+ return 'refusing DNS name resolving to a cloud-metadata / link-local address'
1272
+ }
1273
+ } catch { /* resolution failures surface via fetch */ }
1274
+ }
1275
+ return null
1276
+ }
1277
+
1278
+ _applyInitResult(initResult) {
1279
+ if (!initResult || typeof initResult !== 'object') {
1280
+ throw new Error('initialize returned non-object result')
1281
+ }
1282
+ // #6823: capture advertised capabilities to gate prompts/resources fetches.
1283
+ this._serverCapabilities =
1284
+ initResult.capabilities && typeof initResult.capabilities === 'object'
1285
+ ? initResult.capabilities
1286
+ : {}
1287
+ const serverVersion = initResult.protocolVersion
1288
+ if (typeof serverVersion === 'string') {
1289
+ this._negotiatedProtocolVersion = serverVersion
1290
+ if (serverVersion !== MCP_PROTOCOL_VERSION) {
1291
+ this._log.warn(`MCP server ${this.name}: protocolVersion mismatch — requested=${MCP_PROTOCOL_VERSION} server=${serverVersion} (negotiating to server value)`)
1292
+ }
1293
+ }
1294
+ }
1295
+
1296
+ _setTools(toolsResult) {
1297
+ const tools = Array.isArray(toolsResult?.tools) ? toolsResult.tools : []
1298
+ this._tools = Object.freeze(tools.map((t) => Object.freeze({ ...t })))
1299
+ }
1300
+
1301
+ /**
1302
+ * #6823: capability-gated prompts/list + resources/list, run after tools/list
1303
+ * in both remote handshakes. Uses the shared `_serverCapabilities` gate and
1304
+ * the non-fatal `_loadListing` so a prompt/resource fetch failure never fails
1305
+ * the connect.
1306
+ */
1307
+ async _loadPromptsAndResources() {
1308
+ const caps = this._serverCapabilities || {}
1309
+ if (caps.prompts) this._prompts = await this._loadListing('prompts/list', 'prompts')
1310
+ if (caps.resources) this._resources = await this._loadListing('resources/list', 'resources')
1311
+ }
1312
+
1313
+ _buildHeaders({ json = false, acceptStream = false } = {}) {
1314
+ const headers = { ...this._headers }
1315
+ if (acceptStream) headers.Accept = 'application/json, text/event-stream'
1316
+ if (json) headers['Content-Type'] = 'application/json'
1317
+ // #6821 Streamable HTTP: echo the session id + negotiated protocol version
1318
+ // on every post-initialize request per the 2025-03-26 / 2025-06-18 spec.
1319
+ if (this._sessionId) headers['Mcp-Session-Id'] = this._sessionId
1320
+ if (this._negotiatedProtocolVersion) headers['MCP-Protocol-Version'] = this._negotiatedProtocolVersion
1321
+ return this._applyOAuthHeader(headers)
1322
+ }
1323
+
1324
+ /**
1325
+ * #6822: when an OAuth access token exists, replace ANY authorization header
1326
+ * the config carried (case-insensitively — a config `authorization` collides
1327
+ * with a fresh `Authorization`, sending TWO auth headers) with the OAuth
1328
+ * bearer, which is the fresher credential. Mutates + returns `headers`. When
1329
+ * there is no token, the config's own header (whatever its case) passes
1330
+ * through untouched.
1331
+ */
1332
+ _applyOAuthHeader(headers) {
1333
+ if (!this._accessToken) return headers
1334
+ for (const key of Object.keys(headers)) {
1335
+ if (key.toLowerCase() === 'authorization') delete headers[key]
1336
+ }
1337
+ headers.Authorization = `Bearer ${this._accessToken}`
1338
+ return headers
1339
+ }
1340
+
1341
+ /**
1342
+ * #6822: build the 401/407 error, capturing the `WWW-Authenticate` header so the
1343
+ * OAuth flow can discover the resource metadata. The header names only public
1344
+ * discovery URLs (never a token), so retaining it is safe.
1345
+ */
1346
+ _oauthError(res, status) {
1347
+ const err = new Error(`MCP server ${this.name} requires OAuth (HTTP ${status})`)
1348
+ err._oauthRequired = true
1349
+ try { err._wwwAuthenticate = res?.headers?.get?.('www-authenticate') || null } catch { err._wwwAuthenticate = null }
1350
+ return err
1351
+ }
1352
+
1353
+ async _checkStatus(res, method) {
1354
+ const status = res.status
1355
+ if (status >= 200 && status < 300) return
1356
+ // Non-2xx: no throw path below ever reads the body, so cancel/drain it
1357
+ // first — an unread Streamable-HTTP response body keeps its stream/socket
1358
+ // dangling (a leaked handle, the #6835 hang class), and for the legacy SSE
1359
+ // call sites the caller's own `_discardBody(res)` never runs once we throw.
1360
+ // _discardBody wraps its own work in try/catch, so this drain can never
1361
+ // throw-and-mask the status error we raise below.
1362
+ await this._discardBody(res)
1363
+ if (status === 401 || status === 407) {
1364
+ throw this._oauthError(res, status)
1365
+ }
1366
+ // #6834: with redirect:'manual' a 3xx surfaces here as-is. Refuse it
1367
+ // explicitly — following would replay our credentialed headers against
1368
+ // whatever origin the Location header names.
1369
+ if (status >= 300 && status < 400) {
1370
+ throw new Error(`MCP server ${this.name} HTTP ${status} redirect on ${method} — refused (redirects are not followed)`)
1371
+ }
1372
+ if (status === 404) {
1373
+ // #6835: a 404 means our Streamable HTTP session id is no longer valid —
1374
+ // the server GC'd the session (a real long-lived-session scenario). Drop
1375
+ // the stale id and, if this happened mid-session (live READY client with a
1376
+ // held session), tear the client down to DEAD. See _expireSession.
1377
+ this._expireSession(method)
1378
+ }
1379
+ throw new Error(`MCP server ${this.name} HTTP ${status} on ${method}`)
1380
+ }
1381
+
1382
+ /**
1383
+ * #6835: handle a 404 (Streamable HTTP session expiry). Always drops the stale
1384
+ * session id. When it fired on a LIVE session (state READY with a session id we
1385
+ * were echoing), the server has GC'd our session server-side — leaving the
1386
+ * client READY would keep the fleet advertising tools that now silently 404 on
1387
+ * every call (the zombie). The remote transport has no lazy re-handshake
1388
+ * (single-connect model, #6821), so tear the client down to DEAD: the fleet
1389
+ * drops its tools, matching the stdio restart-exhaustion contract; recovery is
1390
+ * a session restart or a server re-enable (which rebuilds a fresh client).
1391
+ *
1392
+ * A stateless server (never issued a session id) keeps the prior per-call
1393
+ * behaviour — a lone 404 there stays READY and the next call retries, mirroring
1394
+ * the transient-network-blip handling.
1395
+ */
1396
+ _expireSession(method) {
1397
+ const wasLive = this._state === MCP_STATES.READY && this._sessionId != null
1398
+ this._sessionId = null
1399
+ if (!wasLive) return
1400
+ this._log.warn(`MCP server ${this.name}: Streamable HTTP session expired (HTTP 404 on ${method}) — marking the server dead`)
1401
+ // Abort any other in-flight requests against the now-dead session so no
1402
+ // reader/stream lingers past the transition (the request that observed the
1403
+ // 404 has already resolved; aborting its controller is a no-op). Clear the
1404
+ // set after aborting — mirroring destroy() — so the DEAD transition retains
1405
+ // no now-aborted controllers and a later destroy() repeats no abort work.
1406
+ for (const c of this._controllers) { try { c.abort() } catch { /* already settled */ } }
1407
+ this._controllers.clear()
1408
+ this._toDead()
1409
+ }
1410
+
1411
+ async _discardBody(res) {
1412
+ try {
1413
+ if (res?.body && typeof res.body.cancel === 'function') await res.body.cancel()
1414
+ else if (res && typeof res.arrayBuffer === 'function') await res.arrayBuffer()
1415
+ } catch { /* nothing to drain */ }
1416
+ }
1417
+
1418
+ _rejectAllPending(err) {
1419
+ for (const settle of this._pending.values()) {
1420
+ try { settle({ id: null, error: { message: err.message } }) } catch { /* already settled */ }
1421
+ }
1422
+ this._pending.clear()
1423
+ }
1424
+
1425
+ _toDead() {
1426
+ this._tools = []
1427
+ // #6823: parity with the stdio client — a dead remote server contributes
1428
+ // zero prompts/resources.
1429
+ this._prompts = []
1430
+ this._resources = []
1431
+ this._rejectAllPending(new Error('MCP remote client dead'))
1432
+ this._setState(MCP_STATES.DEAD)
1433
+ this.emit('dead')
1434
+ }
1435
+
1436
+ _setState(next) {
1437
+ if (this._state === next) return
1438
+ const prev = this._state
1439
+ this._state = next
1440
+ this.emit('state', { prev, next })
1441
+ }
1442
+ }
1443
+
1444
+ /**
1445
+ * Pick the transport for a parsed MCP server config (#6821). A `url` selects
1446
+ * the remote (Streamable HTTP / SSE) client; otherwise the stdio child-process
1447
+ * client. Keeps byok-mcp-fleet.js transport-agnostic — it just calls this.
1448
+ */
1449
+ export function createMcpClient(config, opts = {}) {
1450
+ const isRemote = typeof config?.url === 'string' && config.url.length > 0
1451
+ return isRemote ? new MCPRemoteClient(config, opts) : new MCPClient(config, opts)
1452
+ }