index.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. /**
  2. * CodeGraph MCP Server
  3. *
  4. * Model Context Protocol server that exposes CodeGraph functionality
  5. * as tools for AI assistants like Claude.
  6. *
  7. * @module mcp
  8. *
  9. * @example
  10. * ```typescript
  11. * import { MCPServer } from 'codegraph';
  12. *
  13. * const server = new MCPServer('/path/to/project');
  14. * await server.start();
  15. * ```
  16. *
  17. * Runtime modes (decided in {@link MCPServer.start}):
  18. *
  19. * - **Direct** — one process serves one MCP client over stdio. The pre-#411
  20. * behavior; used when the user opts out (`CODEGRAPH_NO_DAEMON=1`), no
  21. * `.codegraph/` is reachable, or the daemon machinery fails for any reason.
  22. * - **Proxy** — what an MCP host actually talks to when sharing is on: a thin
  23. * stdio↔socket pipe to the shared daemon. The proxy carries the #277 PPID
  24. * watchdog, so a SIGKILL'd host reaps its proxy promptly. See {@link ./proxy.ts}.
  25. * - **Daemon** — a *detached* background process (its own session/process
  26. * group) that serves N proxies over a Unix-domain socket / named pipe,
  27. * sharing one CodeGraph + watcher + SQLite handle. Spawned on demand; never a
  28. * child of any host, so it survives individual sessions and is reaped by
  29. * client-refcount + idle timeout. See {@link ./daemon.ts} and issue #411.
  30. *
  31. * The detached-daemon + always-proxy split is the fix for the review finding
  32. * that the original in-process daemon (a) was the first host's child, so closing
  33. * that terminal severed every other client, and (b) disabled the PPID watchdog,
  34. * regressing #277 (orphaned daemons on host SIGKILL).
  35. */
  36. import * as fs from 'fs';
  37. import * as path from 'path';
  38. import { spawn, StdioOptions } from 'child_process';
  39. import { resolveServerRoot, getCodeGraphDir } from '../directory';
  40. import { StdioTransport } from './transport';
  41. import { MCPEngine } from './engine';
  42. import { MCPSession } from './session';
  43. import {
  44. Daemon,
  45. clearStaleDaemonLock,
  46. isProcessAlive,
  47. tryAcquireDaemonLock,
  48. } from './daemon';
  49. import { connectWithHello, runLocalHandshakeProxy } from './proxy';
  50. import { getDaemonSocketCandidates, probeDaemonIdentity } from './daemon-paths';
  51. import { getTelemetry } from '../telemetry';
  52. import { checkForUpdateInBackground } from '../upgrade/update-check';
  53. import { EARLY_PPID } from './early-ppid';
  54. import { supervisionLostReason, parsePpidPollMs, parseHostPpid } from './ppid-watchdog';
  55. import { installMainThreadWatchdog, WatchdogHandle } from './liveness-watchdog';
  56. import { armStartupHandshakeTimeout } from './startup-handshake';
  57. import { treatStdinFailureAsShutdown } from './stdin-teardown';
  58. import { HOST_PPID_ENV } from '../extraction/wasm-runtime-flags';
  59. /**
  60. * Env var that marks a process as the *detached daemon* itself (set by
  61. * {@link spawnDetachedDaemon} when it re-invokes the CLI). Without it a
  62. * `serve --mcp` invocation is a launcher that connects-or-spawns; with it, the
  63. * process IS the daemon and must never try to spawn another (infinite spawn).
  64. */
  65. const DAEMON_INTERNAL_ENV = 'CODEGRAPH_DAEMON_INTERNAL';
  66. /**
  67. * Retries for the detached daemon arbitrating the O_EXCL lock against a racing
  68. * sibling. Tiny — the lock resolves on the first round in practice; the retries
  69. * only cover clearing a genuinely stale (dead-pid) lockfile.
  70. */
  71. const TAKEOVER_MAX_RETRIES = 5;
  72. const TAKEOVER_RETRY_DELAY_MS = 100;
  73. /**
  74. * How long a launcher waits for a freshly-spawned daemon to bind its socket
  75. * before giving up and running in-process. The daemon binds the socket *before*
  76. * the (backgrounded) engine/grammar warm-up, so this only needs to cover node
  77. * process startup. 60 × 100ms = 6s of headroom for a cold/slow box; on the
  78. * common path the socket appears within a few rounds.
  79. */
  80. // Poll finely (25ms) so the proxy attaches the instant the freshly-spawned
  81. // daemon binds, instead of waiting up to a coarse 100ms after — shaves the
  82. // cold-start handshake (the window the headless agent races). Same ~6s total
  83. // give-up budget (240 × 25ms), just finer granularity; socket-connect probes
  84. // are cheap. Paired with deferring the CodeGraph load (engine.ts) off the bind
  85. // path, this narrows the "No such tool available" race window.
  86. const DAEMON_CONNECT_MAX_RETRIES = 240;
  87. const DAEMON_CONNECT_RETRY_DELAY_MS = 25;
  88. /** Whether `CODEGRAPH_NO_DAEMON` was set to a truthy value. */
  89. function daemonOptOutSet(): boolean {
  90. const raw = process.env.CODEGRAPH_NO_DAEMON;
  91. if (!raw) return false;
  92. return raw !== '0' && raw.toLowerCase() !== 'false';
  93. }
  94. /** Whether this process was spawned to BE the detached daemon. */
  95. function daemonInternalSet(): boolean {
  96. const raw = process.env[DAEMON_INTERNAL_ENV];
  97. return !!raw && raw !== '0' && raw.toLowerCase() !== 'false';
  98. }
  99. /**
  100. * Prefix every `process.stderr.write` chunk with an ISO-8601 timestamp. Called
  101. * once, only when this process becomes the detached daemon — whose stderr is
  102. * appended to `.codegraph/daemon.log`. Before #1431 no log line carried a
  103. * timestamp, so watchdog kills and restarts could be counted but never placed
  104. * in time. (The watchdog child writes its kill notice through its own
  105. * inherited fd 2, bypassing this wrapper — it stamps that line itself.)
  106. */
  107. export function timestampStderrLines(): void {
  108. const orig = process.stderr.write.bind(process.stderr);
  109. process.stderr.write = ((chunk: string | Uint8Array, ...rest: unknown[]) => {
  110. return (orig as (...args: unknown[]) => boolean)(stampLogChunk(chunk), ...rest);
  111. }) as typeof process.stderr.write;
  112. }
  113. /** Prepend `[<ISO-8601>] ` to a log chunk; unknown chunk types pass through. */
  114. export function stampLogChunk(chunk: string | Uint8Array): string | Uint8Array {
  115. try {
  116. const stamp = `[${new Date().toISOString()}] `;
  117. if (typeof chunk === 'string') return stamp + chunk;
  118. if (Buffer.isBuffer(chunk)) return Buffer.concat([Buffer.from(stamp), chunk]);
  119. } catch { /* stamping is best-effort; never block the write */ }
  120. return chunk;
  121. }
  122. /**
  123. * Watchdog `progressPaths` for a server keyed on `root`'s index: the SQLite DB
  124. * + its WAL. With these, the #850 liveness watchdog only kills on heartbeat
  125. * silence when the DB files are NOT advancing — the same slow-disk deferral
  126. * the CLI `index`/`init` path got in #1231. Without it, one >timeout
  127. * synchronous statement on a big DB (multi-GB index behind Windows Defender)
  128. * SIGKILLs a perfectly healthy daemon — and a daemon SIGKILL'd at the end of
  129. * nearly every session is what ratcheted the WAL leak in #1431. A true wedge
  130. * still dies: a wedged loop writes nothing, so the files stay still.
  131. */
  132. export function watchdogProgressPaths(root: string | null): { progressPaths?: string[] } {
  133. if (!root) return {};
  134. const dbPath = path.join(getCodeGraphDir(root), 'codegraph.db');
  135. return { progressPaths: [dbPath, `${dbPath}-wal`] };
  136. }
  137. /**
  138. * Resolve the project root the daemon machinery should key on. Returns
  139. * `null` when no `.codegraph/` is reachable from the candidate path — in
  140. * that case the caller must run in direct mode, since the daemon lockfile
  141. * and socket both live under `.codegraph/`.
  142. *
  143. * Uses the same resolution as the engine (#1606): up-walk first, then the
  144. * bounded workspace down-scan that adopts a SINGLE indexed sub-project. A
  145. * workspace root above one indexed child therefore gets the shared daemon
  146. * (one watcher, one writer, keyed on the child) instead of a direct-mode
  147. * server per host.
  148. *
  149. * The result is canonicalized with `realpathSync` so every client converges on
  150. * the same socket/lock path regardless of how it expressed the path: a client
  151. * launched with cwd under a symlink (e.g. macOS `/var` → `/private/var`, where
  152. * spawned `process.cwd()` is already realpath'd) and one that passed a
  153. * symlinked `rootUri` would otherwise hash to different sockets and silently
  154. * fail to share the daemon.
  155. */
  156. function resolveDaemonRoot(explicitPath: string | null): string | null {
  157. const candidate = explicitPath ?? process.cwd();
  158. const root = resolveServerRoot(candidate).root;
  159. if (!root) return null;
  160. try { return fs.realpathSync(root); } catch { return root; }
  161. }
  162. /**
  163. * Spawn the shared daemon as a fully detached background process: its own
  164. * session/process group (so a SIGHUP/SIGINT to the launcher's terminal can't
  165. * reach it) with stdio decoupled from the launcher (logs to
  166. * `.codegraph/daemon.log`). Re-invokes the *same* CLI faithfully across dev and
  167. * bundled launches by reusing `process.argv[0]` (the right node), the current
  168. * `process.execArgv` (carries `--liftoff-only`, so the daemon never re-execs)
  169. * and `process.argv[1]` (this script). The spawned process self-arbitrates the
  170. * O_EXCL lock, so racing launchers may each spawn one — losers exit and every
  171. * launcher proxies through the single winner.
  172. */
  173. function spawnDetachedDaemon(root: string): void {
  174. const scriptPath = process.argv[1];
  175. if (!scriptPath) {
  176. // No resolvable CLI entry point to re-invoke — let the caller fall back to
  177. // direct mode rather than spawn something broken.
  178. throw new Error('cannot resolve CLI script path to spawn the daemon');
  179. }
  180. let logFd: number | null = null;
  181. let stdio: StdioOptions = 'ignore';
  182. try {
  183. logFd = fs.openSync(path.join(getCodeGraphDir(root), 'daemon.log'), 'a');
  184. stdio = ['ignore', logFd, logFd];
  185. } catch {
  186. stdio = 'ignore'; // no log file — discard daemon output rather than fail
  187. }
  188. try {
  189. // The daemon has no host: scrub the threaded host pid so it can't leak
  190. // into the daemon's env (and from there into anything the daemon spawns),
  191. // where a long-dead session's host pid would trigger spurious shutdowns.
  192. const env: NodeJS.ProcessEnv = { ...process.env, [DAEMON_INTERNAL_ENV]: '1' };
  193. delete env[HOST_PPID_ENV];
  194. const child = spawn(
  195. process.execPath,
  196. [...process.execArgv, scriptPath, 'serve', '--mcp', '--path', root],
  197. {
  198. detached: true,
  199. stdio,
  200. windowsHide: true,
  201. env,
  202. },
  203. );
  204. child.unref();
  205. } finally {
  206. // The child holds its own dup of the log fd now; the launcher doesn't need it.
  207. if (logFd !== null) {
  208. try { fs.closeSync(logFd); } catch { /* ignore */ }
  209. }
  210. }
  211. }
  212. /**
  213. * MCP Server for CodeGraph
  214. *
  215. * Implements the Model Context Protocol to expose CodeGraph
  216. * functionality as tools that can be called by AI assistants.
  217. *
  218. * Backwards-compatible constructor and `start()` signature with the
  219. * pre-issue-#411 implementation: callers continue to do
  220. * `new MCPServer(path).start()`. Internally we now pick from direct / proxy /
  221. * daemon at start time.
  222. */
  223. export class MCPServer {
  224. private projectPath: string | null;
  225. // Direct-mode-only state. In daemon mode the per-connection sessions live
  226. // inside the Daemon class; in proxy mode there is no session at all.
  227. private session: MCPSession | null = null;
  228. private engine: MCPEngine | null = null;
  229. private daemon: Daemon | null = null;
  230. private ppidWatchdog: ReturnType<typeof setInterval> | null = null;
  231. // Worker-thread liveness watchdog (#850). Long-lived modes only; SIGKILLs the
  232. // process if the main thread wedges in a non-yielding sync loop.
  233. private livenessWatchdog: WatchdogHandle | null = null;
  234. // PPID watchdog baseline — from the CLI entry's earliest-possible capture
  235. // (early-ppid.ts). Capturing here (construction) already lost the race when
  236. // the launcher was killed during module loading (#1185).
  237. private originalPpid: number = EARLY_PPID;
  238. private hostPpid: number | null = parseHostPpid(process.env[HOST_PPID_ENV]);
  239. // Idempotency guard for stop().
  240. private stopped = false;
  241. private mode: 'unstarted' | 'direct' | 'proxy' | 'daemon' = 'unstarted';
  242. constructor(projectPath?: string) {
  243. this.projectPath = projectPath || null;
  244. }
  245. /**
  246. * Start the MCP server.
  247. *
  248. * Decision order:
  249. * 1. `CODEGRAPH_NO_DAEMON=1` → direct mode (unchanged pre-#411 behavior).
  250. * 2. `CODEGRAPH_DAEMON_INTERNAL=1` → we ARE the detached daemon; listen.
  251. * 3. No `.codegraph/` reachable → direct mode (the daemon's lockfile and
  252. * socket both live under `.codegraph/`).
  253. * 4. Otherwise connect to (or spawn) the shared daemon and proxy to it.
  254. *
  255. * On any unexpected failure in step 4 we transparently fall back to direct
  256. * mode — a misbehaving daemon must never block a session from starting.
  257. */
  258. async start(): Promise<void> {
  259. // Long-lived process (direct / proxy / daemon alike): flush buffered
  260. // telemetry opportunistically. Fire-and-forget + unref'd — adds nothing
  261. // to the handshake path and never keeps the process alive.
  262. getTelemetry().startInterval();
  263. // #1243: the MCP config launches the local binary, so a server left
  264. // running drifts behind releases with no signal. Refresh the shared
  265. // update-check cache in the background and log ONE stderr notice when a
  266. // newer version exists (stderr only — stdout is the protocol channel).
  267. // The notice also reaches the agent via the initialize instructions and
  268. // codegraph_status. Fire-and-forget: adds nothing to the handshake path.
  269. checkForUpdateInBackground();
  270. // The detached daemon process itself. Checked before the opt-out so the
  271. // daemon honors the same env it was spawned with (it never sets NO_DAEMON).
  272. if (daemonInternalSet()) {
  273. return this.startDaemonProcess();
  274. }
  275. // Direct mode if the user opted out. Setting the env var is sufficient to
  276. // get the pre-#411 single-process behavior.
  277. if (daemonOptOutSet()) {
  278. return this.startDirect('CODEGRAPH_NO_DAEMON set');
  279. }
  280. const root = resolveDaemonRoot(this.projectPath);
  281. if (!root) {
  282. // No initialized project found — daemon mode has nowhere to put its
  283. // socket. The fresh-checkout / outside-project case; behave as before.
  284. return this.startDirect('no .codegraph/ root found');
  285. }
  286. try {
  287. // Answer the MCP handshake LOCALLY (instant tool registration — no waiting
  288. // ~600ms for the daemon to spawn+bind, which produced the cold-start race)
  289. // and forward tool CALLS to the shared daemon, connected in the background.
  290. // Runs until the host disconnects; the proxy installs its own watchdog and
  291. // falls back to an in-process engine if the daemon never comes up.
  292. this.mode = 'proxy';
  293. await this.runProxyWithLocalHandshake(root);
  294. return;
  295. } catch (err) {
  296. // Belt-and-braces: a throw during proxy SETUP (before the client was served)
  297. // is still safe to recover from with a direct-mode session.
  298. const msg = err instanceof Error ? err.message : String(err);
  299. process.stderr.write(`[CodeGraph MCP] Proxy path failed (${msg}); falling back to direct mode.\n`);
  300. return this.startDirect('proxy path threw');
  301. }
  302. }
  303. /**
  304. * Stop the server. In daemon mode this triggers graceful shutdown of every
  305. * connected session; in direct mode it mirrors the pre-#411 behavior (close
  306. * cg, exit). Proxy mode never routes through here — the proxy exits itself.
  307. */
  308. stop(): void {
  309. if (this.stopped) return;
  310. this.stopped = true;
  311. if (this.ppidWatchdog) {
  312. clearInterval(this.ppidWatchdog);
  313. this.ppidWatchdog = null;
  314. }
  315. if (this.livenessWatchdog) {
  316. this.livenessWatchdog.stop();
  317. this.livenessWatchdog = null;
  318. }
  319. if (this.daemon) {
  320. void this.daemon.stop('stop()');
  321. // Daemon.stop calls process.exit; nothing else to do.
  322. return;
  323. }
  324. if (this.session) {
  325. this.session.stop();
  326. this.session = null;
  327. }
  328. if (this.engine) {
  329. this.engine.stop();
  330. this.engine = null;
  331. }
  332. process.exit(0);
  333. }
  334. /** Single-process stdio MCP session — the pre-issue-#411 code path. */
  335. private async startDirect(reason: string): Promise<void> {
  336. if (reason && process.env.CODEGRAPH_MCP_DEBUG) {
  337. process.stderr.write(`[CodeGraph MCP] Direct mode: ${reason}.\n`);
  338. }
  339. this.engine = new MCPEngine();
  340. const transport = new StdioTransport();
  341. this.session = new MCPSession(transport, this.engine, {
  342. explicitProjectPath: this.projectPath,
  343. });
  344. if (this.projectPath) {
  345. // Background init so the initialize response stays fast (#172).
  346. void this.engine.ensureInitialized(this.projectPath);
  347. }
  348. this.session.start();
  349. // Detect parent-process death — same logic as pre-refactor. When stdin
  350. // closes we go through StdioTransport's `process.exit(0)` already, but
  351. // SIGKILL of the parent doesn't reliably close stdin on Linux (#277).
  352. // Also treat a stdin `'error'` (a socket-backed stdin can fail with
  353. // ECONNRESET/hangup instead of a clean close) as shutdown, and destroy the
  354. // stream so a hung fd can't busy-spin the event loop (#799).
  355. treatStdinFailureAsShutdown(() => this.stop());
  356. // Backstop for a launch abandoned during startup (#1185): launcher killed
  357. // before EARLY_PPID could see it + host holding our pipes open. A server
  358. // that never receives a byte of MCP traffic isn't serving anyone. Armed
  359. // after session.start() attached the real stdin consumer.
  360. armStartupHandshakeTimeout(() => {
  361. process.stderr.write(
  362. '[CodeGraph MCP] No MCP traffic since startup; assuming an abandoned launch and shutting down (#1185). ' +
  363. 'Tune with CODEGRAPH_STARTUP_HANDSHAKE_TIMEOUT_MS (0 disables).\n'
  364. );
  365. this.stop();
  366. });
  367. this.mode = 'direct';
  368. this.installSignalHandlers();
  369. this.installPpidWatchdog();
  370. this.livenessWatchdog = installMainThreadWatchdog(watchdogProgressPaths(resolveDaemonRoot(this.projectPath)));
  371. }
  372. /**
  373. * Run as the detached shared daemon (process spawned with
  374. * `CODEGRAPH_DAEMON_INTERNAL=1`). Arbitrate the O_EXCL lock, then either
  375. * become the daemon (bind the socket, serve forever) or — if a live daemon
  376. * already holds the lock — exit so we don't leak a redundant process.
  377. *
  378. * No PPID watchdog and no stdin handlers: the daemon is detached on purpose
  379. * and reaps itself via client-refcount + idle timeout (see {@link Daemon}).
  380. */
  381. private async startDaemonProcess(): Promise<void> {
  382. // In daemon mode stderr IS `.codegraph/daemon.log`; stamp every line so
  383. // kills/restarts can be placed in time (#1431 — the log was undatable).
  384. timestampStderrLines();
  385. const root = resolveDaemonRoot(this.projectPath) ?? this.projectPath ?? process.cwd();
  386. for (let attempt = 0; attempt < TAKEOVER_MAX_RETRIES; attempt++) {
  387. const lock = tryAcquireDaemonLock(root);
  388. if (lock.kind === 'acquired') {
  389. const daemon = new Daemon(root);
  390. await daemon.start();
  391. this.daemon = daemon;
  392. this.mode = 'daemon';
  393. // The detached daemon has no PPID watchdog or stdin lifeline, so a
  394. // wedged main thread would pin a core forever (#850). The liveness
  395. // watchdog is its only recovery path.
  396. this.livenessWatchdog = installMainThreadWatchdog(watchdogProgressPaths(root));
  397. return; // the net.Server keeps the process alive
  398. }
  399. // Taken. If the holder is alive, another daemon already serves (or is
  400. // binding) — we're redundant; exit cleanly so the launcher proxies to it.
  401. const existing = lock.existing;
  402. if (existing && existing.pid > 0 && isProcessAlive(existing.pid)) {
  403. // Give a newly-elected daemon time to bind, then require its socket hello
  404. // to match the lock PID/version. PID existence alone accepts an unrelated
  405. // process after OS PID reuse and permanently wedges startup (#1553).
  406. const age = Date.now() - existing.startedAt;
  407. const stillStarting = existing.startedAt > 0 && age >= 0 && age < 10_000;
  408. if (stillStarting || await probeDaemonIdentity(existing)) {
  409. process.stderr.write(
  410. `[CodeGraph daemon] Another daemon (pid ${existing.pid}) already holds the lock; exiting.\n`
  411. );
  412. process.exit(0);
  413. }
  414. }
  415. // Holder is dead (or the record is unreadable) — clear it (pid-verified,
  416. // so we never delete a live daemon's lock) and retry the acquire.
  417. clearStaleDaemonLock(lock.pidPath, existing?.pid, { allowLivePid: true });
  418. await sleep(TAKEOVER_RETRY_DELAY_MS);
  419. }
  420. process.stderr.write('[CodeGraph daemon] Could not acquire the daemon lock; exiting.\n');
  421. process.exit(0);
  422. }
  423. /**
  424. * Proxy mode (the common case). Serve the MCP handshake LOCALLY for instant
  425. * tool registration, forwarding tool calls to the shared daemon — which is
  426. * connected in the background (probed, then spawned + polled if absent) so the
  427. * handshake never waits ~600ms on it. Runs until the host disconnects; the
  428. * proxy falls back to an in-process engine if the daemon never binds, so this
  429. * never wedges a session.
  430. */
  431. private async runProxyWithLocalHandshake(root: string): Promise<void> {
  432. // The daemon may relocate its socket past an in-project filesystem that can't
  433. // host one (ExFAT/FAT volumes, WSL2 DrvFs; #997) to the deterministic tmpdir
  434. // fallback. We don't read the bound path from the lockfile — both sides walk
  435. // the SAME ordered candidate list, so we converge on whichever the daemon
  436. // bound with zero coordination. The in-project candidate is tried first, so a
  437. // normal repo pays nothing extra (it connects on the very first probe).
  438. const candidates = getDaemonSocketCandidates(root);
  439. const connectAnyCandidate = async (): Promise<Awaited<ReturnType<typeof connectWithHello>>> => {
  440. for (const candidate of candidates) {
  441. const s = await connectWithHello(candidate);
  442. // A wrong-version daemon IS up — definitive; propagate so the caller
  443. // serves in-process instead of spawning + polling for 6s. Don't keep
  444. // probing fallbacks past it.
  445. if (s === 'version-mismatch') return s;
  446. if (s) return s;
  447. }
  448. return null;
  449. };
  450. const getDaemonSocket = async () => {
  451. // Fast path: a daemon may already be listening (on either candidate).
  452. const probe = await connectAnyCandidate();
  453. if (probe === 'version-mismatch') return null; // definitive — serve in-process, don't poll for 6s
  454. if (probe) return probe;
  455. // None reachable — spawn one (detached) and poll for its bind.
  456. spawnDetachedDaemon(root);
  457. for (let attempt = 0; attempt < DAEMON_CONNECT_MAX_RETRIES; attempt++) {
  458. await sleep(DAEMON_CONNECT_RETRY_DELAY_MS);
  459. const s = await connectAnyCandidate();
  460. if (s === 'version-mismatch') return null;
  461. if (s) return s;
  462. }
  463. return null; // never bound — the proxy serves this session in-process
  464. };
  465. await runLocalHandshakeProxy({ getDaemonSocket, makeEngine: () => new MCPEngine(), root });
  466. }
  467. /** Standard SIGINT/SIGTERM handlers that route to our `stop()` (direct mode). */
  468. private installSignalHandlers(): void {
  469. process.on('SIGINT', () => this.stop());
  470. process.on('SIGTERM', () => this.stop());
  471. }
  472. /**
  473. * PPID watchdog (#277) — direct mode only. Daemon mode is detached on purpose
  474. * and reaps via idle timeout; proxy mode installs its own watchdog inside
  475. * {@link runProxy}. So this only ever runs for an in-process direct session.
  476. */
  477. private installPpidWatchdog(): void {
  478. if (this.mode !== 'direct') return;
  479. const pollMs = parsePpidPollMs(process.env.CODEGRAPH_PPID_POLL_MS);
  480. if (pollMs <= 0) return;
  481. this.ppidWatchdog = setInterval(() => {
  482. const reason = supervisionLostReason({
  483. originalPpid: this.originalPpid,
  484. currentPpid: process.ppid,
  485. hostPpid: this.hostPpid,
  486. isAlive: isProcessAlive,
  487. });
  488. if (reason) {
  489. process.stderr.write(
  490. `[CodeGraph MCP] Parent process exited (${reason}); shutting down.\n`
  491. );
  492. this.stop();
  493. }
  494. }, pollMs);
  495. this.ppidWatchdog.unref();
  496. }
  497. }
  498. function sleep(ms: number): Promise<void> {
  499. // Deliberately NOT unref'd. During the daemon connect/takeover retry loop we
  500. // may be between processes — no socket bound yet, no transport, no listener
  501. // pinning the event loop. An unref'd timer would let Node drain the loop and
  502. // exit silently before we get a chance to try again.
  503. return new Promise((resolve) => { setTimeout(resolve, ms); });
  504. }
  505. // Export for use in CLI
  506. export { StdioTransport } from './transport';
  507. export { tools, ToolHandler } from './tools';
  508. // Surface a few daemon-mode bits for tests + diagnostics.
  509. export { Daemon } from './daemon';
  510. export { CodeGraphPackageVersion } from './version';