@chroxy/server 0.10.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.
- package/CONFIG.md +695 -0
- package/README.md +105 -0
- package/hooks/permission-hook.sh +285 -0
- package/package.json +69 -0
- package/scripts/fix-node-pty-helper.js +44 -0
- package/sidecar/Dockerfile +40 -0
- package/sidecar/PROTOCOL.md +691 -0
- package/sidecar/agent.js +1290 -0
- package/sidecar/package-lock.json +43 -0
- package/sidecar/package.json +17 -0
- package/src/activity-registry.js +491 -0
- package/src/anthropic-compatible-config.js +534 -0
- package/src/anthropic-compatible-session.js +579 -0
- package/src/anthropic-openai-shim.js +109 -0
- package/src/anthropic-openai-translate.js +377 -0
- package/src/auth-probes.js +296 -0
- package/src/background-shell-tracker.js +320 -0
- package/src/background-shells.js +125 -0
- package/src/base-session.js +1518 -0
- package/src/billing-budget.js +191 -0
- package/src/billing-canary-monitor.js +203 -0
- package/src/billing-class.js +149 -0
- package/src/bind-host.js +82 -0
- package/src/built-in-tools/bash-exec.js +167 -0
- package/src/built-in-tools/file-ops.js +198 -0
- package/src/built-in-tools/tool-transforms.js +179 -0
- package/src/builtin-commands.js +107 -0
- package/src/byok-compose-state-shared.js +31 -0
- package/src/byok-compose-state.js +234 -0
- package/src/byok-credentials.js +127 -0
- package/src/byok-event-translator.js +136 -0
- package/src/byok-mcp-client.js +404 -0
- package/src/byok-mcp-config.js +159 -0
- package/src/byok-mcp-fleet.js +214 -0
- package/src/byok-mcp-trust.js +175 -0
- package/src/byok-session.js +2019 -0
- package/src/byok-subagent-profiles.js +101 -0
- package/src/byok-tool-executor.js +813 -0
- package/src/byok-tools.js +271 -0
- package/src/channels/PACKAGING.md +181 -0
- package/src/channels/README.md +99 -0
- package/src/channels/chroxy-channel-server.js +248 -0
- package/src/checkpoint-manager.js +515 -0
- package/src/child-stream-guard.js +38 -0
- package/src/claude-channel-session.js +185 -0
- package/src/claude-model-catalog.js +266 -0
- package/src/claude-stream-parser.js +106 -0
- package/src/claude-tui/form-driver.js +874 -0
- package/src/claude-tui/pty-driver.js +520 -0
- package/src/claude-tui/tested-cli-version.js +22 -0
- package/src/claude-tui-attachments.js +342 -0
- package/src/claude-tui-session.js +4029 -0
- package/src/cli/config-cmd.js +34 -0
- package/src/cli/credentials-cmd.js +59 -0
- package/src/cli/deploy-cmd.js +167 -0
- package/src/cli/doctor-cmd.js +52 -0
- package/src/cli/identity-cmd.js +82 -0
- package/src/cli/init-cmd.js +209 -0
- package/src/cli/pages-cmd.js +167 -0
- package/src/cli/pair-code-cmd.js +108 -0
- package/src/cli/pair-discord-cmd.js +100 -0
- package/src/cli/providers-cmd.js +168 -0
- package/src/cli/server-cmd.js +94 -0
- package/src/cli/service-cmd.js +237 -0
- package/src/cli/session-cmd.js +143 -0
- package/src/cli/shared.js +194 -0
- package/src/cli/shell-cmd.js +130 -0
- package/src/cli/status-cmd.js +204 -0
- package/src/cli/tunnel-cmd.js +101 -0
- package/src/cli/update-cmd.js +45 -0
- package/src/cli/worktree-gc-cmd.js +195 -0
- package/src/cli-session.js +1820 -0
- package/src/cli.js +60 -0
- package/src/codex-app-server-client.js +156 -0
- package/src/codex-app-server-session.js +572 -0
- package/src/codex-session.js +604 -0
- package/src/config.js +1757 -0
- package/src/connection-info.js +42 -0
- package/src/connection-locality.js +55 -0
- package/src/content-blocks.js +42 -0
- package/src/control-room/byok-pool.js +130 -0
- package/src/control-room/constants.js +26 -0
- package/src/control-room/containers.js +258 -0
- package/src/control-room/emulators.js +279 -0
- package/src/control-room/handler-factory.js +142 -0
- package/src/control-room/host-prune.js +387 -0
- package/src/control-room/integrations.js +929 -0
- package/src/control-room/repo-runtime-config.js +239 -0
- package/src/control-room/repo-set.js +162 -0
- package/src/control-room/runners.js +479 -0
- package/src/control-room/simulators.js +223 -0
- package/src/control-room/skills-inventory.js +303 -0
- package/src/control-room/survey.js +685 -0
- package/src/control-room/wsl.js +182 -0
- package/src/conversation-scanner.js +270 -0
- package/src/conversation-scope.js +52 -0
- package/src/conversation-search.js +216 -0
- package/src/cost-budget-manager.js +190 -0
- package/src/credential-cipher.js +179 -0
- package/src/credential-store.js +786 -0
- package/src/credential-test.js +145 -0
- package/src/credentials-file.js +58 -0
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
- package/src/dashboard-next/dist/index.html +13 -0
- package/src/deepseek-credentials.js +58 -0
- package/src/deepseek-session.js +192 -0
- package/src/detect-thinking-keyword.js +67 -0
- package/src/dev-preview.js +227 -0
- package/src/devcontainer-config.js +269 -0
- package/src/device-preferences.js +267 -0
- package/src/diagnostics.js +187 -0
- package/src/diff-parser.js +157 -0
- package/src/discord-credentials.js +188 -0
- package/src/discord-pair-delivery.js +113 -0
- package/src/docker-byok-pool-stats.js +221 -0
- package/src/docker-byok-pool.js +841 -0
- package/src/docker-byok-session.js +2172 -0
- package/src/docker-image-allowlist.js +99 -0
- package/src/docker-sdk-session.js +396 -0
- package/src/docker-session.js +382 -0
- package/src/doctor-billing.js +179 -0
- package/src/doctor.js +667 -0
- package/src/duration.js +77 -0
- package/src/environment-manager.js +753 -0
- package/src/environment-statuses.js +20 -0
- package/src/environments/backends/docker.js +931 -0
- package/src/environments/backends/k8s.js +3030 -0
- package/src/environments/backends/rancher.js +326 -0
- package/src/environments/backends/types.js +332 -0
- package/src/event-ingest.js +546 -0
- package/src/event-normalizer.js +1083 -0
- package/src/external-session-registry.js +0 -0
- package/src/file-store.js +52 -0
- package/src/gemini-session.js +498 -0
- package/src/get-public-ip.js +52 -0
- package/src/git.js +15 -0
- package/src/github-webhook.js +256 -0
- package/src/handler-utils.js +663 -0
- package/src/handlers/checkpoint-handlers.js +202 -0
- package/src/handlers/control-room-handlers.js +1945 -0
- package/src/handlers/conversation-handlers.js +201 -0
- package/src/handlers/credential-handlers.js +247 -0
- package/src/handlers/evaluator-handlers.js +94 -0
- package/src/handlers/feature-handlers.js +332 -0
- package/src/handlers/file-handlers.js +142 -0
- package/src/handlers/ide-handlers.js +238 -0
- package/src/handlers/input-handlers.js +1048 -0
- package/src/handlers/pairing-handlers.js +94 -0
- package/src/handlers/repo-handlers.js +295 -0
- package/src/handlers/session-handlers.js +660 -0
- package/src/handlers/settings-handlers.js +818 -0
- package/src/handlers/skills-handlers.js +682 -0
- package/src/handlers/summarize-handlers.js +172 -0
- package/src/handlers/token-handlers.js +57 -0
- package/src/http-oversize.js +51 -0
- package/src/http-routes.js +1158 -0
- package/src/ide/search.js +268 -0
- package/src/ide/symbols.js +423 -0
- package/src/ip-utils.js +85 -0
- package/src/json-state-file.js +169 -0
- package/src/jsonl-reader.js +187 -0
- package/src/jsonl-subprocess-session.js +441 -0
- package/src/keychain.js +458 -0
- package/src/lan-ip.js +38 -0
- package/src/logger.js +388 -0
- package/src/mailbox-route.js +252 -0
- package/src/mcp-tools.js +46 -0
- package/src/message-transform.js +102 -0
- package/src/metrics.js +67 -0
- package/src/model-discovery.js +288 -0
- package/src/models.js +1426 -0
- package/src/notification-prefs.js +544 -0
- package/src/notifications/discord-billing-sink.js +323 -0
- package/src/notifications/discord-webhook-client.js +187 -0
- package/src/notifications/discord-webhook-sink.js +768 -0
- package/src/notifications/expo-push-sink.js +414 -0
- package/src/notifications/ready-body.js +177 -0
- package/src/notifications/sink-registry.js +98 -0
- package/src/notifications/sink.js +82 -0
- package/src/ollama-session.js +221 -0
- package/src/ollama-tags.js +238 -0
- package/src/openai-compatible-session.js +118 -0
- package/src/pages-store.js +255 -0
- package/src/pairing.js +836 -0
- package/src/path-hash-trust-ledger.js +311 -0
- package/src/per-session-settings.js +366 -0
- package/src/permission-audit.js +120 -0
- package/src/permission-hook.js +257 -0
- package/src/permission-manager.js +829 -0
- package/src/permission-resolver.js +144 -0
- package/src/platform.js +139 -0
- package/src/prompt-evaluator.js +386 -0
- package/src/providers.js +436 -0
- package/src/push.js +565 -0
- package/src/rate-limiter.js +433 -0
- package/src/redaction.js +206 -0
- package/src/sdk-session.js +1773 -0
- package/src/semver.js +92 -0
- package/src/server-cli/push-notification-handler.js +240 -0
- package/src/server-cli/server-orchestrator.js +168 -0
- package/src/server-cli/startup-display.js +146 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
- package/src/server-cli-child.js +207 -0
- package/src/server-cli.js +1223 -0
- package/src/server-identity.js +383 -0
- package/src/service.js +835 -0
- package/src/session-context.js +49 -0
- package/src/session-lock.js +60 -0
- package/src/session-manager.js +3257 -0
- package/src/session-message-history.js +511 -0
- package/src/session-preset-trust.js +78 -0
- package/src/session-preset.js +458 -0
- package/src/session-state-persistence.js +307 -0
- package/src/session-timeout-manager.js +166 -0
- package/src/session-token-store.js +83 -0
- package/src/shell-approval-info.js +45 -0
- package/src/shell-approval-store.js +163 -0
- package/src/shell-audit.js +63 -0
- package/src/skills-budget.js +181 -0
- package/src/skills-content-validator.js +106 -0
- package/src/skills-frontmatter.js +422 -0
- package/src/skills-loader.js +1893 -0
- package/src/skills-manager.js +256 -0
- package/src/skills-trust.js +532 -0
- package/src/skills-usage.js +335 -0
- package/src/snapshots-store.js +345 -0
- package/src/ssrf-guard.js +130 -0
- package/src/subagent-counter.js +149 -0
- package/src/summarize-session.js +268 -0
- package/src/supervisor.js +929 -0
- package/src/test-client.js +131 -0
- package/src/token-compare.js +28 -0
- package/src/token-manager.js +220 -0
- package/src/tool-result.js +87 -0
- package/src/transcript-tasks.js +334 -0
- package/src/tunnel/base.js +294 -0
- package/src/tunnel/cloudflare.js +281 -0
- package/src/tunnel/index.js +54 -0
- package/src/tunnel-check.js +84 -0
- package/src/turn-tracker.js +0 -0
- package/src/user-shell-registry.js +218 -0
- package/src/user-shell-session.js +411 -0
- package/src/utils/check-dependencies.js +70 -0
- package/src/utils/concurrency.js +24 -0
- package/src/utils/context-window-learn.js +148 -0
- package/src/utils/error-message.js +25 -0
- package/src/utils/format-bytes.js +35 -0
- package/src/utils/preflight.js +143 -0
- package/src/utils/resolve-binary.js +91 -0
- package/src/utils/respawn-rate-limiter.js +59 -0
- package/src/utils/sleep.js +58 -0
- package/src/utils/spawn-env.js +193 -0
- package/src/utils/validation-patterns.js +23 -0
- package/src/utils/win-spawn.js +98 -0
- package/src/version-check.js +16 -0
- package/src/web-task-manager.js +383 -0
- package/src/worktree-gc.js +418 -0
- package/src/worktree-reaper.js +168 -0
- package/src/ws-auth.js +645 -0
- package/src/ws-broadcaster.js +385 -0
- package/src/ws-client-manager.js +476 -0
- package/src/ws-client-sender.js +115 -0
- package/src/ws-file-ops/browser.js +594 -0
- package/src/ws-file-ops/common.js +163 -0
- package/src/ws-file-ops/git.js +298 -0
- package/src/ws-file-ops/index.js +52 -0
- package/src/ws-file-ops/reader.js +595 -0
- package/src/ws-forwarding.js +543 -0
- package/src/ws-handler-context.js +196 -0
- package/src/ws-history.js +1251 -0
- package/src/ws-message-handlers.js +165 -0
- package/src/ws-permissions.js +676 -0
- package/src/ws-schemas.js +119 -0
- package/src/ws-server.js +2866 -0
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP child-process lifecycle for the claude-byok provider (#4077).
|
|
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.
|
|
8
|
+
*
|
|
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.
|
|
15
|
+
*
|
|
16
|
+
* Out of scope (next stages):
|
|
17
|
+
* - Materializing into Anthropic SDK tools[] (#4078).
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { spawn } from 'node:child_process'
|
|
21
|
+
import { EventEmitter } from 'node:events'
|
|
22
|
+
import { readFileSync } from 'node:fs'
|
|
23
|
+
import { fileURLToPath } from 'node:url'
|
|
24
|
+
import { dirname, join } from 'node:path'
|
|
25
|
+
import { createLogger } from './logger.js'
|
|
26
|
+
import { CHROXY_SECRET_DENYLIST } from './utils/spawn-env.js'
|
|
27
|
+
import { prepareSpawn } from './utils/win-spawn.js'
|
|
28
|
+
|
|
29
|
+
// #4453: exponential restart backoff. The first restart still fires at ~1s
|
|
30
|
+
// after the death (no regression on the existing acceptance test); the
|
|
31
|
+
// second waits ~2s after that failure; the third waits ~4s. Total budget
|
|
32
|
+
// before DEAD is ~7s, up from the previous fixed 3s. This better matches
|
|
33
|
+
// "wedged dependency that needs a moment to recover" failure modes (e.g.
|
|
34
|
+
// a transient port conflict that resolves in ~5s would have been blown
|
|
35
|
+
// past by the previous 1/1/1 schedule).
|
|
36
|
+
//
|
|
37
|
+
// The array length is the authoritative max-attempt count — derive
|
|
38
|
+
// MAX_RESTART_ATTEMPTS from it so an operator who edits the schedule
|
|
39
|
+
// can't accidentally desync the two.
|
|
40
|
+
const RESTART_BACKOFF_MS = [1000, 2000, 4000]
|
|
41
|
+
const MAX_RESTART_ATTEMPTS = RESTART_BACKOFF_MS.length
|
|
42
|
+
const KILL_GRACE_MS = 1000
|
|
43
|
+
// #4454: handshake-request timeout. Some MCP servers (sandboxed containers,
|
|
44
|
+
// servers that download packages on startup) legitimately take >5s to reply
|
|
45
|
+
// to initialize / tools/list. Override per-config via `handshakeTimeoutMs`
|
|
46
|
+
// (preferred — sourced from ~/.claude.json → byok-mcp-config) or per-
|
|
47
|
+
// MCPClient via `opts.handshakeTimeoutMs` (used by tests). The export
|
|
48
|
+
// makes #4078 / future tooling able to read the default without
|
|
49
|
+
// re-deriving it. Both export and the override remain on the same
|
|
50
|
+
// "absolute upper bound for ONE handshake request" semantics — total
|
|
51
|
+
// handshake budget is up to 2× this (initialize + tools/list).
|
|
52
|
+
export const DEFAULT_HANDSHAKE_TIMEOUT_MS = 5000
|
|
53
|
+
export const DEFAULT_TOOL_CALL_TIMEOUT_MS = 30_000
|
|
54
|
+
|
|
55
|
+
// #4452: MCP spec version we request on initialize. Bumping this is a
|
|
56
|
+
// deliberate change — when MCP releases a new spec date and we adopt it,
|
|
57
|
+
// update this constant + verify against the negotiation log-warn output.
|
|
58
|
+
// Servers that don't recognise it should still accept the handshake
|
|
59
|
+
// (per spec) and reply with their own protocolVersion; the negotiation
|
|
60
|
+
// warn surfaces the mismatch without erroring.
|
|
61
|
+
export const MCP_PROTOCOL_VERSION = '2024-11-05'
|
|
62
|
+
|
|
63
|
+
// #4452: clientInfo.version on initialize. Derived from this package's
|
|
64
|
+
// package.json so MCP-server-side logs/debugging name a real chroxy
|
|
65
|
+
// version instead of the previous '1' placeholder. Synchronous read at
|
|
66
|
+
// module load is fine because the file is tiny and never changes
|
|
67
|
+
// mid-process.
|
|
68
|
+
function readPackageVersion() {
|
|
69
|
+
try {
|
|
70
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
71
|
+
const pkgPath = join(here, '..', 'package.json')
|
|
72
|
+
const raw = readFileSync(pkgPath, 'utf8')
|
|
73
|
+
const parsed = JSON.parse(raw)
|
|
74
|
+
if (typeof parsed?.version === 'string' && parsed.version.length > 0) {
|
|
75
|
+
return parsed.version
|
|
76
|
+
}
|
|
77
|
+
} catch {
|
|
78
|
+
// Fall through — never block startup on a missing/unreadable package.json.
|
|
79
|
+
}
|
|
80
|
+
return '0.0.0'
|
|
81
|
+
}
|
|
82
|
+
export const MCP_CLIENT_VERSION = readPackageVersion()
|
|
83
|
+
|
|
84
|
+
export const MCP_STATES = Object.freeze({
|
|
85
|
+
IDLE: 'idle',
|
|
86
|
+
STARTING: 'starting',
|
|
87
|
+
READY: 'ready',
|
|
88
|
+
RESTARTING: 'restarting',
|
|
89
|
+
DEAD: 'dead',
|
|
90
|
+
DESTROYED: 'destroyed',
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
export class MCPClient extends EventEmitter {
|
|
94
|
+
constructor(config, opts = {}) {
|
|
95
|
+
super()
|
|
96
|
+
this.name = config.name
|
|
97
|
+
this._config = config
|
|
98
|
+
this._log = opts.log || createLogger('byok-mcp')
|
|
99
|
+
// #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 →
|
|
102
|
+
// proceed; false → state=DEAD permanently, no child is ever spawned.
|
|
103
|
+
this._trustGate = opts.trustGate || null
|
|
104
|
+
// #4454: per-instance handshake timeout. Precedence (high → low):
|
|
105
|
+
// 1. opts.handshakeTimeoutMs (constructor; tests / fleet pass-through)
|
|
106
|
+
// 2. config.handshakeTimeoutMs (per-MCP-server, sourced from ~/.claude.json)
|
|
107
|
+
// 3. DEFAULT_HANDSHAKE_TIMEOUT_MS module constant
|
|
108
|
+
// Same defensive guard as resultTimeoutMs in byok-session: non-finite
|
|
109
|
+
// / non-positive (NaN, Infinity, 0, -1, '5s') falls through to the next
|
|
110
|
+
// tier because setTimeout coerces those to 0ms and would make every
|
|
111
|
+
// handshake look broken.
|
|
112
|
+
this._handshakeTimeoutMs =
|
|
113
|
+
(Number.isFinite(opts.handshakeTimeoutMs) && opts.handshakeTimeoutMs > 0 && opts.handshakeTimeoutMs) ||
|
|
114
|
+
(Number.isFinite(config?.handshakeTimeoutMs) && config.handshakeTimeoutMs > 0 && config.handshakeTimeoutMs) ||
|
|
115
|
+
DEFAULT_HANDSHAKE_TIMEOUT_MS
|
|
116
|
+
this._state = MCP_STATES.IDLE
|
|
117
|
+
this._tools = []
|
|
118
|
+
this._child = null
|
|
119
|
+
this._stdoutBuf = ''
|
|
120
|
+
this._nextId = 1
|
|
121
|
+
this._pending = new Map()
|
|
122
|
+
this._restartTimer = null
|
|
123
|
+
this._restartAttempts = 0
|
|
124
|
+
this._destroyed = false
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
get state() { return this._state }
|
|
128
|
+
get tools() { return this._tools }
|
|
129
|
+
|
|
130
|
+
async start() {
|
|
131
|
+
if (this._destroyed) throw new Error('MCPClient destroyed')
|
|
132
|
+
if (this._state === MCP_STATES.READY) return
|
|
133
|
+
if (this._state === MCP_STATES.DEAD) return
|
|
134
|
+
// #4457: trust gate fires BEFORE spawn. Deny → permanent DEAD, no child
|
|
135
|
+
// process is ever created. Trust gate throwing is treated as deny so
|
|
136
|
+
// the spawn surface fails closed.
|
|
137
|
+
if (this._trustGate) {
|
|
138
|
+
let allowed
|
|
139
|
+
try {
|
|
140
|
+
allowed = await this._trustGate()
|
|
141
|
+
} catch (err) {
|
|
142
|
+
this._log.warn(`MCP server ${this.name}: trust gate threw: ${err?.message || err}`)
|
|
143
|
+
allowed = false
|
|
144
|
+
}
|
|
145
|
+
if (!allowed) {
|
|
146
|
+
this._setState(MCP_STATES.DEAD)
|
|
147
|
+
this.emit('dead')
|
|
148
|
+
return
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
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.
|
|
156
|
+
if (this._state !== MCP_STATES.READY && this._state !== MCP_STATES.DEAD) {
|
|
157
|
+
await new Promise((resolve) => {
|
|
158
|
+
const onState = ({ next }) => {
|
|
159
|
+
if (next === MCP_STATES.READY || next === MCP_STATES.DEAD) {
|
|
160
|
+
this.off('state', onState)
|
|
161
|
+
resolve()
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
this.on('state', onState)
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Build the env for the spawned MCP server child. Inherits the operator's
|
|
171
|
+
* full process env plus any user-configured `_config.env`, then strips the
|
|
172
|
+
* chroxy-owned daemon secrets (#6311) — the full-authority API_TOKEN must
|
|
173
|
+
* never reach an MCP server subprocess, which could read it and seize the
|
|
174
|
+
* daemon. Extracted so the strip is unit-testable without a real spawn.
|
|
175
|
+
*
|
|
176
|
+
* @returns {Record<string, string>}
|
|
177
|
+
*/
|
|
178
|
+
_buildChildEnv() {
|
|
179
|
+
const env = { ...process.env, ...this._config.env }
|
|
180
|
+
for (const key of CHROXY_SECRET_DENYLIST) {
|
|
181
|
+
delete env[key]
|
|
182
|
+
}
|
|
183
|
+
return env
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
_spawnAndHandshake() {
|
|
187
|
+
this._setState(MCP_STATES.STARTING)
|
|
188
|
+
let child
|
|
189
|
+
try {
|
|
190
|
+
// #6504 — route a user-configured .cmd/.bat MCP command through cmd.exe on
|
|
191
|
+
// Windows (Node 24 rejects spawning a .cmd shim directly with EINVAL, e.g.
|
|
192
|
+
// an npx-style shim). prepareSpawn is a no-op for .exe/POSIX, so non-Windows
|
|
193
|
+
// behaviour is unchanged; its cross-spawn escaping passes the user-supplied
|
|
194
|
+
// args verbatim through cmd.exe (round-tripped in win-spawn.test.js).
|
|
195
|
+
const spawnSpec = prepareSpawn(this._config.command, this._config.args)
|
|
196
|
+
child = spawn(spawnSpec.command, spawnSpec.args, {
|
|
197
|
+
env: this._buildChildEnv(),
|
|
198
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
199
|
+
...spawnSpec.options,
|
|
200
|
+
})
|
|
201
|
+
} catch (err) {
|
|
202
|
+
this._log.warn(`MCP server ${this.name}: spawn threw: ${err?.message || err}`)
|
|
203
|
+
this._onExit(null, null)
|
|
204
|
+
return
|
|
205
|
+
}
|
|
206
|
+
this._child = child
|
|
207
|
+
child.on('error', (err) => {
|
|
208
|
+
this._log.warn(`MCP server ${this.name}: child error: ${err?.message || err}`)
|
|
209
|
+
})
|
|
210
|
+
child.stderr.on('data', (chunk) => {
|
|
211
|
+
this._log.debug(`MCP server ${this.name} stderr: ${chunk.toString().trimEnd()}`)
|
|
212
|
+
})
|
|
213
|
+
child.stdout.on('data', (chunk) => this._onStdoutChunk(chunk))
|
|
214
|
+
child.on('exit', (code, signal) => this._onExit(code, signal))
|
|
215
|
+
|
|
216
|
+
this._handshake().catch((err) => {
|
|
217
|
+
this._log.warn(`MCP server ${this.name}: handshake failed: ${err?.message || err}`)
|
|
218
|
+
this._killChild()
|
|
219
|
+
})
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async _handshake() {
|
|
223
|
+
const initResult = await this._request('initialize', {
|
|
224
|
+
protocolVersion: MCP_PROTOCOL_VERSION,
|
|
225
|
+
capabilities: {},
|
|
226
|
+
clientInfo: { name: 'chroxy-byok', version: MCP_CLIENT_VERSION },
|
|
227
|
+
}, this._handshakeTimeoutMs)
|
|
228
|
+
if (!initResult || typeof initResult !== 'object') {
|
|
229
|
+
throw new Error('initialize returned non-object result')
|
|
230
|
+
}
|
|
231
|
+
// #4452: negotiation log-warn. If the server replies with a different
|
|
232
|
+
// protocolVersion than we requested, log it once so a future spec
|
|
233
|
+
// mismatch is debuggable. Per spec the server's value wins — we don't
|
|
234
|
+
// error, both sides are expected to interoperate at the server's
|
|
235
|
+
// declared version. Bumping MCP_PROTOCOL_VERSION should silence the
|
|
236
|
+
// warn for the matching server.
|
|
237
|
+
const serverVersion = initResult.protocolVersion
|
|
238
|
+
if (typeof serverVersion === 'string' && serverVersion !== MCP_PROTOCOL_VERSION) {
|
|
239
|
+
this._log.warn(`MCP server ${this.name}: protocolVersion mismatch — requested=${MCP_PROTOCOL_VERSION} server=${serverVersion} (negotiating to server value)`)
|
|
240
|
+
}
|
|
241
|
+
this._notify('notifications/initialized')
|
|
242
|
+
const toolsResult = await this._request('tools/list', {}, this._handshakeTimeoutMs)
|
|
243
|
+
const tools = Array.isArray(toolsResult?.tools) ? toolsResult.tools : []
|
|
244
|
+
this._tools = Object.freeze(tools.map((t) => Object.freeze({ ...t })))
|
|
245
|
+
this._restartAttempts = 0
|
|
246
|
+
this._setState(MCP_STATES.READY)
|
|
247
|
+
this.emit('ready', this._tools)
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async callTool(toolName, args, timeoutMs = DEFAULT_TOOL_CALL_TIMEOUT_MS) {
|
|
251
|
+
if (this._state !== MCP_STATES.READY) {
|
|
252
|
+
throw new Error(`MCP server ${this.name} not ready (state=${this._state})`)
|
|
253
|
+
}
|
|
254
|
+
return this._request('tools/call', { name: toolName, arguments: args || {} }, timeoutMs)
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
_request(method, params, timeoutMs) {
|
|
258
|
+
return new Promise((resolve, reject) => {
|
|
259
|
+
const id = this._nextId++
|
|
260
|
+
const payload = JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n'
|
|
261
|
+
let timer = null
|
|
262
|
+
const settle = (err, val) => {
|
|
263
|
+
if (timer) clearTimeout(timer)
|
|
264
|
+
this._pending.delete(id)
|
|
265
|
+
if (err) reject(err); else resolve(val)
|
|
266
|
+
}
|
|
267
|
+
this._pending.set(id, settle)
|
|
268
|
+
timer = setTimeout(() => settle(new Error(`MCP ${method} timeout`)), timeoutMs)
|
|
269
|
+
if (!this._child?.stdin?.writable) {
|
|
270
|
+
settle(new Error('MCP child stdin not writable'))
|
|
271
|
+
return
|
|
272
|
+
}
|
|
273
|
+
this._child.stdin.write(payload, (err) => {
|
|
274
|
+
if (err) settle(err)
|
|
275
|
+
})
|
|
276
|
+
})
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
_notify(method, params) {
|
|
280
|
+
if (!this._child?.stdin?.writable) return
|
|
281
|
+
this._child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method, params }) + '\n')
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
_onStdoutChunk(chunk) {
|
|
285
|
+
this._stdoutBuf += chunk.toString('utf8')
|
|
286
|
+
const lines = this._stdoutBuf.split('\n')
|
|
287
|
+
this._stdoutBuf = lines.pop() ?? ''
|
|
288
|
+
for (const line of lines) {
|
|
289
|
+
if (!line) continue
|
|
290
|
+
let msg
|
|
291
|
+
try {
|
|
292
|
+
msg = JSON.parse(line)
|
|
293
|
+
} catch (err) {
|
|
294
|
+
this._log.warn(`MCP server ${this.name}: non-JSON line: ${line.slice(0, 80)}`)
|
|
295
|
+
continue
|
|
296
|
+
}
|
|
297
|
+
if (msg.id == null) {
|
|
298
|
+
// Notification from the server (per JSON-RPC spec: `id` is required
|
|
299
|
+
// on responses, absent on notifications). Ignored silently — they
|
|
300
|
+
// are a normal part of the protocol (e.g. `notifications/cancelled`,
|
|
301
|
+
// server-initiated progress events) and would only add log noise.
|
|
302
|
+
continue
|
|
303
|
+
}
|
|
304
|
+
if (this._pending.has(msg.id)) {
|
|
305
|
+
const settle = this._pending.get(msg.id)
|
|
306
|
+
if (msg.error) settle(new Error(msg.error.message || 'MCP RPC error'))
|
|
307
|
+
else settle(null, msg.result)
|
|
308
|
+
} else {
|
|
309
|
+
// #4455: orphan response — server emitted a response with an id we
|
|
310
|
+
// never sent (or one we already settled). Could be a buggy server
|
|
311
|
+
// emitting a stale id after restart, a state-machine bug on the
|
|
312
|
+
// server side, or a duplicate. Not necessarily an error (don't
|
|
313
|
+
// warn); but without a log we'd have no audit trail when debugging
|
|
314
|
+
// "why doesn't my MCP tool respond". Capture the unmatched id and
|
|
315
|
+
// a small shape marker so future investigation has something to
|
|
316
|
+
// grep for.
|
|
317
|
+
const shape = msg.error ? 'error' : 'result'
|
|
318
|
+
this._log.debug(`MCP server ${this.name}: orphan JSON-RPC response id=${msg.id} shape=${shape}`)
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
_onExit(code, signal) {
|
|
324
|
+
const wasStartingOrReady = this._state === MCP_STATES.STARTING || this._state === MCP_STATES.READY
|
|
325
|
+
for (const settle of this._pending.values()) settle(new Error('MCP child exited'))
|
|
326
|
+
this._pending.clear()
|
|
327
|
+
this._stdoutBuf = ''
|
|
328
|
+
this._child = null
|
|
329
|
+
|
|
330
|
+
if (this._destroyed) {
|
|
331
|
+
this._setState(MCP_STATES.DESTROYED)
|
|
332
|
+
return
|
|
333
|
+
}
|
|
334
|
+
if (!wasStartingOrReady) return
|
|
335
|
+
|
|
336
|
+
this._tools = []
|
|
337
|
+
this._restartAttempts += 1
|
|
338
|
+
// #4453: gate on `>` (not `>=`) so the FULL RESTART_BACKOFF_MS schedule
|
|
339
|
+
// is consumed before declaring DEAD. Pre-#4453 the gate fired on `>=`
|
|
340
|
+
// and MAX_RESTART_ATTEMPTS=3 — meaning only 2 restart delays were
|
|
341
|
+
// actually applied (the 3rd post-spawn-death went straight to DEAD with
|
|
342
|
+
// the 3rd entry of the schedule unused). Under `>`, MAX=3 yields 3
|
|
343
|
+
// applied delays (1s/2s/4s), and DEAD fires after the 4th post-death
|
|
344
|
+
// count crosses the bound. Issue framing: "max 3 attempts before
|
|
345
|
+
// declaring dead" means 3 restarts actually happen, then DEAD.
|
|
346
|
+
if (this._restartAttempts > MAX_RESTART_ATTEMPTS) {
|
|
347
|
+
this._log.warn(`MCP server ${this.name}: dead after ${this._restartAttempts - 1} failed attempts (last exit code=${code} signal=${signal})`)
|
|
348
|
+
this._setState(MCP_STATES.DEAD)
|
|
349
|
+
this.emit('dead')
|
|
350
|
+
return
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
this._setState(MCP_STATES.RESTARTING)
|
|
354
|
+
this.emit('restart', { attempt: this._restartAttempts, code, signal })
|
|
355
|
+
// #4453: pick the delay for this attempt from the backoff schedule.
|
|
356
|
+
// _restartAttempts was bumped above; subtract 1 to index. Defensive
|
|
357
|
+
// fallback to the last entry guards against a future refactor that
|
|
358
|
+
// diverges MAX_RESTART_ATTEMPTS from the array length.
|
|
359
|
+
const delayIdx = Math.min(this._restartAttempts - 1, RESTART_BACKOFF_MS.length - 1)
|
|
360
|
+
const delay = RESTART_BACKOFF_MS[delayIdx]
|
|
361
|
+
this._restartTimer = setTimeout(() => {
|
|
362
|
+
this._restartTimer = null
|
|
363
|
+
if (this._destroyed) return
|
|
364
|
+
this._spawnAndHandshake()
|
|
365
|
+
}, delay)
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
_killChild() {
|
|
369
|
+
if (!this._child) return
|
|
370
|
+
try { this._child.kill('SIGTERM') } catch {}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
destroy() {
|
|
374
|
+
if (this._destroyed) return Promise.resolve()
|
|
375
|
+
this._destroyed = true
|
|
376
|
+
if (this._restartTimer) {
|
|
377
|
+
clearTimeout(this._restartTimer)
|
|
378
|
+
this._restartTimer = null
|
|
379
|
+
}
|
|
380
|
+
const child = this._child
|
|
381
|
+
if (!child) {
|
|
382
|
+
this._setState(MCP_STATES.DESTROYED)
|
|
383
|
+
return Promise.resolve()
|
|
384
|
+
}
|
|
385
|
+
return new Promise((resolve) => {
|
|
386
|
+
const onExit = () => {
|
|
387
|
+
clearTimeout(killTimer)
|
|
388
|
+
resolve()
|
|
389
|
+
}
|
|
390
|
+
child.once('exit', onExit)
|
|
391
|
+
try { child.kill('SIGTERM') } catch {}
|
|
392
|
+
const killTimer = setTimeout(() => {
|
|
393
|
+
try { child.kill('SIGKILL') } catch {}
|
|
394
|
+
}, KILL_GRACE_MS)
|
|
395
|
+
})
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
_setState(next) {
|
|
399
|
+
if (this._state === next) return
|
|
400
|
+
const prev = this._state
|
|
401
|
+
this._state = next
|
|
402
|
+
this.emit('state', { prev, next })
|
|
403
|
+
}
|
|
404
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP config discovery for the claude-byok provider.
|
|
3
|
+
*
|
|
4
|
+
* Foundation only for #4048/#4076: parse Claude-style mcpServers blocks and
|
|
5
|
+
* expose safe read-only metadata. This module deliberately does not spawn MCP
|
|
6
|
+
* children or wire tools.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { existsSync, readFileSync, statSync } from 'node:fs'
|
|
10
|
+
import { homedir } from 'node:os'
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Defensive upper bound on the size of `~/.claude.json`. Today the file is
|
|
15
|
+
* small (a few KB), but it is owned by Claude Code, not by us — a future
|
|
16
|
+
* schema change that starts persisting conversation history into it could
|
|
17
|
+
* grow it substantially. Reading hundreds of MB synchronously at session-start
|
|
18
|
+
* would block the server, so we bail with a single warning above this cap.
|
|
19
|
+
*/
|
|
20
|
+
export const CLAUDE_CONFIG_MAX_BYTES = 10 * 1024 * 1024
|
|
21
|
+
|
|
22
|
+
export function defaultClaudeConfigPath() {
|
|
23
|
+
return process.env.CHROXY_CLAUDE_CONFIG || join(homedir(), '.claude.json')
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Coerce an args array to strings only. Pushes one warning per dropped entry
|
|
28
|
+
* naming the server, the offending index (`args[<i>]`), and the value's type
|
|
29
|
+
* so a user who typoed a number-as-number gets a signal instead of a silent
|
|
30
|
+
* strip. Non-arrays drop the whole field with a single warning.
|
|
31
|
+
*/
|
|
32
|
+
function coerceStringArray(value, { warnings, serverName }) {
|
|
33
|
+
if (value == null) return []
|
|
34
|
+
if (!Array.isArray(value)) {
|
|
35
|
+
warnings.push(
|
|
36
|
+
`MCP server ${serverName}: ignoring args (expected array, got ${typeof value})`,
|
|
37
|
+
)
|
|
38
|
+
return []
|
|
39
|
+
}
|
|
40
|
+
const out = []
|
|
41
|
+
for (let i = 0; i < value.length; i++) {
|
|
42
|
+
const item = value[i]
|
|
43
|
+
if (typeof item === 'string') {
|
|
44
|
+
out.push(item)
|
|
45
|
+
} else {
|
|
46
|
+
warnings.push(
|
|
47
|
+
`MCP server ${serverName}: dropping args[${i}] (expected string, got ${typeof item})`,
|
|
48
|
+
)
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return out
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Coerce an env object to string→string only. Pushes one warning per dropped
|
|
56
|
+
* key naming the server, the offending field (`env.<KEY>`), and the value's
|
|
57
|
+
* type. Non-objects drop the whole field with a single warning.
|
|
58
|
+
*/
|
|
59
|
+
function coerceEnv(value, { warnings, serverName }) {
|
|
60
|
+
if (value == null) return {}
|
|
61
|
+
if (typeof value !== 'object' || Array.isArray(value)) {
|
|
62
|
+
warnings.push(
|
|
63
|
+
`MCP server ${serverName}: ignoring env (expected object, got ${Array.isArray(value) ? 'array' : typeof value})`,
|
|
64
|
+
)
|
|
65
|
+
return {}
|
|
66
|
+
}
|
|
67
|
+
const env = {}
|
|
68
|
+
for (const [key, raw] of Object.entries(value)) {
|
|
69
|
+
if (typeof key !== 'string' || key.length === 0) continue
|
|
70
|
+
if (typeof raw === 'string') {
|
|
71
|
+
env[key] = raw
|
|
72
|
+
} else {
|
|
73
|
+
warnings.push(
|
|
74
|
+
`MCP server ${serverName}: dropping env.${key} (expected string, got ${typeof raw})`,
|
|
75
|
+
)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return env
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Parse a Claude-style MCP config object.
|
|
83
|
+
*
|
|
84
|
+
* @param {unknown} raw
|
|
85
|
+
* @returns {{ servers: Array<{ name: string, command: string, args: string[], env: Record<string, string> }>, warnings: string[] }}
|
|
86
|
+
*/
|
|
87
|
+
export function parseClaudeMcpConfig(raw) {
|
|
88
|
+
const warnings = []
|
|
89
|
+
const servers = []
|
|
90
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
91
|
+
return { servers, warnings: ['MCP config root must be an object'] }
|
|
92
|
+
}
|
|
93
|
+
const block = raw.mcpServers
|
|
94
|
+
if (block == null) return { servers, warnings }
|
|
95
|
+
if (typeof block !== 'object' || Array.isArray(block)) {
|
|
96
|
+
return { servers, warnings: ['mcpServers must be an object'] }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
for (const [name, entry] of Object.entries(block)) {
|
|
100
|
+
if (!name) {
|
|
101
|
+
warnings.push('Skipping MCP server with empty name')
|
|
102
|
+
continue
|
|
103
|
+
}
|
|
104
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
|
|
105
|
+
warnings.push(`Skipping MCP server ${name}: entry must be an object`)
|
|
106
|
+
continue
|
|
107
|
+
}
|
|
108
|
+
if (typeof entry.command !== 'string' || entry.command.length === 0) {
|
|
109
|
+
warnings.push(`Skipping MCP server ${name}: command is required`)
|
|
110
|
+
continue
|
|
111
|
+
}
|
|
112
|
+
servers.push({
|
|
113
|
+
name,
|
|
114
|
+
command: entry.command,
|
|
115
|
+
args: coerceStringArray(entry.args, { warnings, serverName: name }),
|
|
116
|
+
env: coerceEnv(entry.env, { warnings, serverName: name }),
|
|
117
|
+
})
|
|
118
|
+
}
|
|
119
|
+
return { servers, warnings }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Read and parse a Claude-style MCP config file.
|
|
124
|
+
*
|
|
125
|
+
* @param {string} filePath
|
|
126
|
+
* @returns {{ servers: Array<{ name: string, command: string, args: string[], env: Record<string, string> }>, warnings: string[], missing: boolean }}
|
|
127
|
+
*/
|
|
128
|
+
export function loadClaudeMcpConfig(filePath = defaultClaudeConfigPath()) {
|
|
129
|
+
if (!filePath || !existsSync(filePath)) {
|
|
130
|
+
return { servers: [], warnings: [], missing: true }
|
|
131
|
+
}
|
|
132
|
+
try {
|
|
133
|
+
// statSync is cheap; do it before readFileSync so a pathologically large
|
|
134
|
+
// file (see CLAUDE_CONFIG_MAX_BYTES) does not block startup.
|
|
135
|
+
const stat = statSync(filePath)
|
|
136
|
+
if (stat.size > CLAUDE_CONFIG_MAX_BYTES) {
|
|
137
|
+
const warning = `MCP config ${filePath} exceeds size cap (${stat.size} bytes > ${CLAUDE_CONFIG_MAX_BYTES} bytes); skipping load`
|
|
138
|
+
console.warn(`[byok-mcp-config] ${warning}`)
|
|
139
|
+
return { servers: [], warnings: [warning], missing: false }
|
|
140
|
+
}
|
|
141
|
+
const raw = JSON.parse(readFileSync(filePath, 'utf8'))
|
|
142
|
+
return { ...parseClaudeMcpConfig(raw), missing: false }
|
|
143
|
+
} catch (err) {
|
|
144
|
+
return {
|
|
145
|
+
servers: [],
|
|
146
|
+
warnings: [`Failed to parse MCP config ${filePath}: ${err?.message || String(err)}`],
|
|
147
|
+
missing: false,
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function toMcpServerMetadata(server) {
|
|
153
|
+
return Object.freeze({
|
|
154
|
+
name: server.name,
|
|
155
|
+
command: server.command,
|
|
156
|
+
args: Object.freeze([...server.args]),
|
|
157
|
+
envKeys: Object.freeze(Object.keys(server.env).sort()),
|
|
158
|
+
})
|
|
159
|
+
}
|