Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,26 @@ export async function startMcpServer(engine: BrainEngine) {

const transport = new StdioServerTransport();
await server.connect(transport);

// Exit cleanly when MCP client disconnects (stdin EOF) or on signals.
// Without this, orphaned serve processes accumulate and contend for the
// PGLite write lock, causing ingest jobs (email-sync) to time out.
let shuttingDown = false;
const shutdown = (reason: string, code = 0) => {
if (shuttingDown) return;
shuttingDown = true;
process.stderr.write(`[gbrain-serve] shutdown: ${reason}\n`);
Promise.resolve(engine.disconnect?.())
.catch(() => {})
.finally(() => process.exit(code));
};
process.stdin.on('end', () => shutdown('stdin end'));
process.stdin.on('close', () => shutdown('stdin close'));
// @ts-ignore — SDK exposes onclose on transport
transport.onclose = () => shutdown('transport close');
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('SIGHUP', () => shutdown('SIGHUP'));
}

// Backward compat: used by `gbrain call` command (trusted local path).
Expand Down