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

Function runLocalHandshakeProxy

src/mcp/proxy.ts:217–417  ·  view source on GitHub ↗
(deps: LocalHandshakeDeps)

Source from the content-addressed store, hash-verified

215 * never costs the old fall-back-to-direct robustness.
216 */
217export async function runLocalHandshakeProxy(deps: LocalHandshakeDeps): Promise<void> {
218 let daemonStatus: 'connecting' | 'ready' | 'failed' = 'connecting';
219 let daemonSocket: net.Socket | null = null;
220 let clientInitId: unknown = undefined; // suppress the daemon's reply to the forwarded initialize
221 // Telemetry attribution for the in-process fallback only — calls routed to
222 // the daemon are counted by the daemon's own session (which receives the
223 // forwarded initialize, clientInfo included), never double-counted here.
224 let telemetryClient: ClientInfo | undefined;
225 const pending: string[] = []; // client lines buffered until the daemon resolves
226 let engine: MCPEngine | null = null;
227 let engineReady: Promise<void> | null = null;
228 let shuttingDown = false;
229 // Requests forwarded to the daemon and not yet answered, keyed by JSON-RPC id.
230 // If the daemon dies mid-session (#662 — e.g. an MCP host SIGTERM's it when a
231 // new session starts), these would otherwise hang forever; we re-serve them
232 // in-process so the host always gets a reply.
233 const inflight = new Map<unknown, string>();
234 // Explore call history for the ONE host connection this proxy serves (CG-17).
235 // Only the daemon-unavailable fallback below uses it; when the daemon is up,
236 // the tracking happens on the daemon's own MCPSession.
237 const exploreSession = new ExploreSessionState();
238 const trackInflight = (line: string): void => {
239 try {
240 const m = JSON.parse(line) as JsonRpc;
241 if (m && m.id !== undefined && typeof m.method === 'string' && m.method !== 'initialize') {
242 inflight.set(m.id, line);
243 }
244 } catch { /* unparseable — nothing we could re-serve anyway */ }
245 };
246
247 const writeClient = (obj: JsonRpc | string): void => {
248 try { process.stdout.write((typeof obj === 'string' ? obj : JSON.stringify(obj)) + '\n'); } catch { /* host gone */ }
249 };
250 const shutdown = (): void => {
251 if (shuttingDown) return; shuttingDown = true;
252 try { daemonSocket?.destroy(); } catch { /* ignore */ }
253 try { engine?.stop(); } catch { /* ignore */ }
254 process.exit(0);
255 };
256 const ensureEngine = (): Promise<void> => {
257 if (!engine) engine = deps.makeEngine();
258 if (!engineReady) engineReady = engine.ensureInitialized(deps.root).catch(() => { /* degraded */ });
259 return engineReady;
260 };
261 // Daemon-unavailable fallback: serve a client message in-process.
262 const handleLocally = async (line: string): Promise<void> => {
263 let msg: JsonRpc; try { msg = JSON.parse(line) as JsonRpc; } catch { return; }
264 const id = msg.id;
265 if (msg.method === 'tools/call' && id !== undefined) {
266 try {
267 await ensureEngine();
268 const params = (msg.params || {}) as { name: string; arguments?: Record<string, unknown> };
269 const result = await engine!.getToolHandler().execute(params.name, params.arguments || {}, exploreSession);
270 writeClient({ jsonrpc: '2.0', id, result });
271 getTelemetry().recordUsage('mcp_tool', params.name, !result.isError, telemetryClient);
272 } catch (err) {
273 writeClient({ jsonrpc: '2.0', id, error: { code: -32603, message: err instanceof Error ? err.message : String(err) } });
274 }

Callers 1

Calls 14

initializeInstructionsFunction · 0.90
getStaticToolsFunction · 0.90
routeToDaemonFunction · 0.85
writeClientFunction · 0.85
shutdownFunction · 0.85
trackInflightFunction · 0.85
handleLocallyFunction · 0.85
onMethod · 0.65
writeMethod · 0.65

Tested by

no test coverage detected