Overview
Concrete function that connects to an existing MCP bridge WebSocket daemon, auto-spawning one if not running, with exponential backoff retry.
Description
The connectWithAutoSpawn function is the daemon lifecycle manager for the MCP bridge. It first tries connecting to an existing daemon at `ws://127.0.0.1:9223/bridge`. If that fails, it spawns a new daemon process (detached, unref'd) via `node:child_process.fork` pointing to `daemon.js`. It then retries connection with exponential backoff (starting at 300ms, multiplying by 1.5, capped at 2000ms) for up to 10 attempts. The daemon is a standalone WebSocket server that relays messages between bridge clients and the browser extension.
Usage
- Called on bridge startup to establish daemon connection.
- Called by `ensureDaemonConnection` to reconnect if the connection is lost.
Code Reference
Source Location
- Repository: AIPex
- File: mcp-bridge/src/bridge.ts
- Lines: L175-247 (connectWithAutoSpawn, tryConnectToDaemon, spawnDaemon)
Signature
async function connectWithAutoSpawn(): Promise<WebSocket>
function tryConnectToDaemon(): Promise<WebSocket>
function spawnDaemon(): void
// Configuration constants:
const DAEMON_URL = "ws://127.0.0.1:9223/bridge"
const MAX_CONNECT_ATTEMPTS = 10
const INITIAL_BACKOFF_MS = 300
async function ensureDaemonConnection(): Promise<void>
function setupDaemonConnection(ws: WebSocket): void
Import
// Internal to mcp-bridge package — not exported as a public API.
// The bridge CLI entry point calls this on startup.
I/O Contract
Inputs
| Name |
Type |
Required |
Description
|
| (none) |
— |
— |
Reads CLI args (--port, --host) from process.argv
|
Outputs
| Name |
Type |
Description
|
| returns |
Promise<WebSocket> |
Connected WebSocket to the daemon
|
Usage Examples
Bridge Startup Flow
// mcp-bridge/src/bridge.ts main() function:
async function main() {
const ws = await connectWithAutoSpawn();
setupDaemonConnection(ws);
const transport = new StdioServerTransport();
await server.connect(transport);
log("AIPex MCP Bridge started (stdio → daemon relay)");
}
// The function internally:
// 1. tryConnectToDaemon() → if success, return existing connection
// 2. spawnDaemon() → fork daemon.js as detached process
// 3. Retry loop with backoff (300ms → 450ms → 675ms → ... → 2000ms max)
// 4. Throw if all 10 attempts fail
Related Pages
Implements Principle
Requires Environment
Page Connections
Double-click a node to navigate. Hold to expand connections.