MCPcopy Create free account
hub / github.com/colbymchenry/codegraph / connectWithHello

Function connectWithHello

src/mcp/proxy.ts:172–210  ·  view source on GitHub ↗
(
  socketPath: string,
  expectedVersion: string = CodeGraphPackageVersion,
  helloTimeoutMs: number = DAEMON_HELLO_TIMEOUT_MS,
)

Source from the content-addressed store, hash-verified

170 * for the hello, so a caller with a deadline can spend no more than it has.
171 */
172export async function connectWithHello(
173 socketPath: string,
174 expectedVersion: string = CodeGraphPackageVersion,
175 helloTimeoutMs: number = DAEMON_HELLO_TIMEOUT_MS,
176): Promise<net.Socket | 'older-version' | 'version-mismatch' | null> {
177 if (process.platform !== 'win32' && !fs.existsSync(socketPath)) return null;
178 const socket = net.createConnection(socketPath);
179 socket.setEncoding('utf8');
180 // Keep an 'error' listener attached for the socket's ENTIRE life. readHelloLine
181 // attaches its own and then REMOVES it on success (its cleanup()), which left a
182 // window — from here until the caller attaches its onDaemonLost handler — where
183 // a socket 'error' had NO listener. In Node an unhandled socket 'error' is
184 // re-thrown as an uncaughtException, which the global fatal handler turns into
185 // process.exit(1); to an MCP client that surfaces as a bare "Transport closed"
186 // (#974). The window is rarely hit on a healthy FS but is common on flaky
187 // AF_UNIX-over-DrvFs (WSL2 /mnt drives). A no-op guard makes the error
188 // recoverable: the follow-up 'close' drives the caller's normal fallback.
189 socket.on('error', () => { /* absorbed — see #974; 'close' drives the fallback */ });
190 const hello = await readHelloLine(socket, helloTimeoutMs).catch(() => null);
191 if (!hello) {
192 socket.destroy();
193 return null; // no daemon yet — caller should keep polling
194 }
195 if (hello.codegraph !== expectedVersion) {
196 // A daemon IS up but it's the wrong version — definitive, not a "not yet".
197 socket.destroy();
198 // An older release is the launcher's to replace (#2335); it says what it did.
199 if (isOlderRelease(hello.codegraph, expectedVersion)) return 'older-version';
200 // Any other: don't poll; the caller serves in-process so we never run stale-vs-new.
201 process.stderr.write(
202 `[CodeGraph MCP] Found a daemon on ${socketPath} but version (${hello.codegraph}) ` +
203 `differs from ours (${expectedVersion}); serving this session in-process.\n`
204 );
205 return 'version-mismatch';
206 }
207 logAttachedDaemon(socketPath, hello);
208 sendClientHello(socket);
209 return socket;
210}
211
212/**
213 * Tell the daemon our pids right after we verify its hello, so its liveness

Callers 4

activateFunction · 0.90

Calls 7

isOlderReleaseFunction · 0.90
readHelloLineFunction · 0.85
logAttachedDaemonFunction · 0.85
sendClientHelloFunction · 0.85
onMethod · 0.65
writeMethod · 0.65
destroyMethod · 0.45

Tested by

no test coverage detected