/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @module bxc/cluster/serve * * `bxc serve --agent`: one process serving the agent web layer (PLAN.md * Phase 3.2) — the HTTP API (`createBxcApp`), MCP over streamable HTTP at * `/mcp` when the MCP server factory is exported, and a `MassiveCrawler` * daemon writing into the same index the API and MCP tools search. With * `--redis` + `--frontier` the crawler joins a sharded cluster instead of * using a local frontier. * * Extra routes (same bearer token as the API when `--token` is set): * - `GET /agent/stats` — crawler (and frontier) statistics; * - `POST /agent/crawl` — `{ "urls": [...] }` enqueues seeds into the daemon; * - `ALL /mcp` — MCP streamable HTTP (stateless). * * Local tooling only: binds 127.0.0.1 by default and never starts the public * origin. */ import { resolve } from "node:path"; import type { Server } from "bun"; import type { CommonOptions } from "../cli/shared.ts"; import { MassiveCrawler, type MassiveCrawlerOptions, type MassiveCrawlerStats, } from "../crawler/MassiveCrawler.ts"; import { registrableDomain } from "../profiles/etld.ts"; import { stripQueryFamilyKey } from "../queue/frontier/scoring.ts"; import { RequestQueue } from "../queue/RequestQueue.ts"; import type { ShardedFrontierStats } from "../queue/sharded/RedisFrontier.ts"; import { normalizeUrl } from "../rust/bridge.ts"; import { intFlag, parseFlags, parseLadder } from "./cli-args.ts"; import { type ClusterWorker, startClusterWorker } from "./worker.ts"; export interface AgentServerOptions { /** HTTP port (0 = ephemeral). Default: 8787. */ port?: number; /** Bind address. Default: 127.0.0.1. */ host?: string; /** Index database shared by the crawler, the API and the MCP tools. Default: `BXC_DB_PATH` or `~/.bxc/bxc.sqlite`. */ sqlitePath?: string; /** Local frontier (local mode). Default: `bxc-agent-frontier` in the storage directory. */ queuePath?: string; /** Seeds crawled at start. */ seeds?: string[]; /** Join a sharded cluster instead of using a local frontier. */ redisUrl?: string; frontier?: string; shards?: number; maxShards?: number; workerId?: string; ladder?: MassiveCrawlerOptions["ladder"]; /** Maximum concurrent requests. Default: 32. */ concurrency?: number; goal?: string; /** Bearer token required by every route except `/health`. */ authToken?: string; /** Serve MCP over HTTP at `/mcp`. Default: true. */ mcp?: boolean; /** Run the crawler daemon. Default: true. */ crawl?: boolean; /** Mount Swagger docs. Default: true. */ swagger?: boolean; /** Mount GraphQL. Default: false. */ graphql?: boolean; /** Extra crawler options (depth, scope, proxies, fetcher, domain memory…). */ crawler?: Partial; /** Extra cluster worker frontier options (lease timing…). */ frontierOptions?: Parameters[0]["frontierOptions"]; log?: (msg: string) => void; } export interface AgentServerStats { ok: true; mode: "local" | "cluster" | "api-only"; url: string; index: string; mcp: boolean; crawler: MassiveCrawlerStats | null; frontier: ShardedFrontierStats | null; } export interface AgentServer { readonly url: string; readonly port: number; readonly hostname: string; /** `true` when `/mcp` is served. */ readonly mcp: boolean; readonly crawler: MassiveCrawler | null; readonly worker: ClusterWorker | null; /** Enqueue seeds into the running daemon; returns the number accepted. */ enqueue(urls: string[]): Promise; stats(): Promise; stop(): Promise; } interface McpHttp { fetch(request: Request): Promise; close(): Promise; } /** * MCP streamable HTTP handler over the stdio server's tool factory. Returns * null when `src/mcp/server.ts` does not export `createServer` (stdio * `bxc mcp` remains the MCP entry point then). */ async function createMcpHttp(log: (msg: string) => void): Promise { const [serverModule, sdk] = await Promise.all([ import("../mcp/server.ts") as Promise>, import("@modelcontextprotocol/server"), ]); const factory = serverModule.createServer; if (typeof factory !== "function") { log("MCP over HTTP disabled: src/mcp/server.ts does not export createServer; use `bxc mcp` (stdio)"); return null; } return sdk.createMcpHandler(factory as Parameters[0], { legacy: "stateless", onerror: (error) => log(`MCP HTTP error: ${error.message}`), }); } function domainKey(url: string): string { try { return registrableDomain(url); } catch { return ""; } } function isLoopback(host: string): boolean { return host === "127.0.0.1" || host === "::1" || host === "localhost" || host.startsWith("127."); } /** Start the single-process agent server. */ export async function startAgentServer(options: AgentServerOptions = {}): Promise { const log = options.log ?? ((msg: string) => console.error(`[bxc-agent] ${msg}`)); const host = options.host ?? "127.0.0.1"; const authToken = options.authToken ?? null; if (!isLoopback(host) && !authToken) log(`WARNING: listening on ${host} without --token`); if (options.redisUrl && !options.frontier) throw new Error("--redis requires --frontier "); // One index for crawler, API routes and MCP tools (they open `new BxcDB()`). const previousDbPath = process.env.BXC_DB_PATH; const sqlitePath = options.sqlitePath ? resolve(options.sqlitePath) : undefined; if (sqlitePath) process.env.BXC_DB_PATH = sqlitePath; const restoreEnv = () => { if (!sqlitePath) return; if (previousDbPath === undefined) delete process.env.BXC_DB_PATH; else process.env.BXC_DB_PATH = previousDbPath; }; let worker: ClusterWorker | null = null; let crawler: MassiveCrawler | null = null; let localQueue: RequestQueue | null = null; let done: Promise = Promise.resolve(); const concurrency = Math.max(1, options.concurrency ?? 32); let server: Server | null = null; let mcp: McpHttp | null = null; const stopCrawler = async () => { if (worker) { await worker.stop(); } else if (crawler) { crawler.stop(); await done; localQueue?.close(); crawler.db.close(); } }; try { if (options.crawl !== false) { if (options.redisUrl && options.frontier) { worker = await startClusterWorker({ redisUrl: options.redisUrl, frontier: options.frontier, shards: options.shards, maxShards: options.maxShards, workerId: options.workerId, queuePath: options.queuePath, sqlitePath, ladder: options.ladder, concurrency, goal: options.goal, seeds: options.seeds, crawler: { batchFlushSize: 10, ...options.crawler }, frontierOptions: options.frontierOptions, log, }); crawler = worker.crawler; } else { localQueue = RequestQueue.open(options.queuePath ?? "bxc-agent-frontier", { hostKeyFn: domainKey, maxInFlightPerHost: 8, familyKeyFn: stripQueryFamilyKey, goal: options.goal, enableRevisits: options.crawler?.enableRevisits ?? false, }); crawler = new MassiveCrawler({ daemon: true, sqliteDbPath: sqlitePath, ladder: options.ladder, goal: options.goal, minConcurrency: Math.min(concurrency, 10), maxConcurrency: concurrency, // Small index batches: pages become searchable within seconds. batchFlushSize: 10, log, ...options.crawler, requestQueue: localQueue, }); const running = crawler; done = running.run(options.seeds).catch((err) => { log(`crawler stopped with an error: ${err instanceof Error ? (err.stack ?? err.message) : err}`); }); } } const { createBxcApp } = await import("../server/app.ts"); const app = await createBxcApp({ graphql: options.graphql ?? false, swagger: options.swagger ?? true, requestLogger: false, downloads: false, authToken, }); if (options.mcp !== false) mcp = await createMcpHttp(log); const enqueue = async (urls: string[]): Promise => { const clean = urls.filter((u) => typeof u === "string" && /^https?:\/\//i.test(u)).map((u) => normalizeUrl(u)); if (clean.length === 0) return 0; if (worker) return (await worker.frontier.submit(clean)).queued; if (localQueue) { return localQueue.addRequests(clean.map((url) => ({ url, opts: { depth: 0, userData: { depth: 0 } } }))); } return 0; }; const unauthorized = (request: Request) => authToken !== null && request.headers.get("authorization") !== `Bearer ${authToken}`; let serverUrl = ""; const stats = async (): Promise => ({ ok: true, mode: worker ? "cluster" : crawler ? "local" : "api-only", url: serverUrl, index: process.env.BXC_DB_PATH ?? "~/.bxc/bxc.sqlite", mcp: mcp !== null, crawler: crawler?.stats() ?? null, frontier: worker ? await worker.frontier.stats() : null, }); server = Bun.serve({ port: options.port ?? 8787, hostname: host, // MCP SSE streams send keep-alives every 15 s. idleTimeout: 120, fetch: async (request) => { const { pathname } = new URL(request.url); if (pathname === "/mcp") { if (unauthorized(request)) return Response.json({ ok: false, error: "unauthorized" }, { status: 401 }); if (!mcp) { return Response.json( { ok: false, error: "MCP over HTTP is unavailable in this build; use `bxc mcp` (stdio)" }, { status: 404 }, ); } return mcp.fetch(request); } if (pathname === "/agent/stats" || pathname === "/agent/crawl") { if (unauthorized(request)) return Response.json({ ok: false, error: "unauthorized" }, { status: 401 }); if (pathname === "/agent/stats" && request.method === "GET") return Response.json(await stats()); if (pathname === "/agent/crawl" && request.method === "POST") { const body = (await request.json().catch(() => null)) as { urls?: unknown } | null; const urls = Array.isArray(body?.urls) ? (body.urls as string[]) : []; if (urls.length === 0) return Response.json({ ok: false, error: "expected { urls: [...] }" }, { status: 400 }); if (!crawler) return Response.json({ ok: false, error: "crawler disabled" }, { status: 409 }); return Response.json({ ok: true, accepted: await enqueue(urls) }); } return Response.json({ ok: false, error: "method not allowed" }, { status: 405 }); } return app.handle(request); }, }); serverUrl = `http://${host.includes(":") ? `[${host}]` : host}:${server.port}`; let stopping: Promise | null = null; const liveServer = server; return { url: serverUrl, port: liveServer.port as number, hostname: host, mcp: mcp !== null, crawler, worker, enqueue, stats, stop() { stopping ??= (async () => { liveServer.stop(true); await mcp?.close().catch(() => {}); await stopCrawler(); restoreEnv(); })(); return stopping; }, }; } catch (err) { server?.stop(true); await mcp?.close().catch(() => {}); await stopCrawler().catch(() => {}); restoreEnv(); throw err; } } // --------------------------------------------------------------------------- // CLI // --------------------------------------------------------------------------- const USAGE = `bxc serve --agent [options] One process: HTTP API + MCP over HTTP (/mcp) + crawler daemon on one index. Options: --port HTTP port (default 8787) --host Bind address (default 127.0.0.1) --sqlite Index database (default BXC_DB_PATH or ~/.bxc/bxc.sqlite) --queue Local frontier file (default: storage dir bxc-agent-frontier) --crawl Seeds crawled at start --redis Join a sharded cluster (requires --frontier) --frontier Cluster frontier name --shards Shard count when creating the frontier (default 16) --max-shards Cap on shards owned by this process --worker-id Unique worker id (default -) --ladder Fetch tiers, e.g. http,render,stealth --concurrency Concurrent requests (default 32) --max-depth Link depth limit (default 10) --goal Crawl goal for focused crawling --token Require Authorization: Bearer --no-mcp Do not serve /mcp --no-crawler API (and MCP) only -h, --help Show this message Routes: /api/v1/* (see /swagger), GET /agent/stats, POST /agent/crawl, /mcp `; export async function main(argv: string[] = process.argv.slice(2), opts?: CommonOptions): Promise { const args = argv.filter((a) => a !== "serve" && a !== "--agent"); if (args.includes("-h") || args.includes("--help")) { Bun.stdout.write(USAGE); return; } let flags: ReturnType; try { flags = parseFlags(args, { booleans: ["no-mcp", "no-crawler"], lists: ["crawl", "seed"] }); } catch (err) { console.error(`[bxc-agent] ${(err as Error).message}\n`); Bun.stderr.write(USAGE); process.exit(2); } const quiet = opts?.quiet === true; const log = (msg: string) => { if (!quiet) console.error(`[bxc-agent] ${msg}`); }; const maxDepth = intFlag(flags, "max-depth"); const server = await startAgentServer({ port: intFlag(flags, "port") ?? 8787, host: flags.values.get("host"), sqlitePath: flags.values.get("sqlite"), queuePath: flags.values.get("queue"), seeds: [...(flags.lists.get("crawl") ?? []), ...(flags.lists.get("seed") ?? [])], redisUrl: flags.values.get("redis"), frontier: flags.values.get("frontier"), shards: intFlag(flags, "shards"), maxShards: intFlag(flags, "max-shards"), workerId: flags.values.get("worker-id"), ladder: parseLadder(flags.values.get("ladder")), concurrency: intFlag(flags, "concurrency"), goal: flags.values.get("goal"), authToken: flags.values.get("token") ?? Bun.env.BXC_API_TOKEN, mcp: !flags.booleans.has("no-mcp"), crawl: !flags.booleans.has("no-crawler"), crawler: { ...(maxDepth !== undefined ? { maxDepth } : {}), ...(opts?.proxy ? { proxyPool: [opts.proxy] } : {}), }, log, }); const stats = await server.stats(); log( `listening on ${server.url} — API ${server.url}/api/v1, ${server.mcp ? `MCP ${server.url}/mcp` : "MCP via `bxc mcp` (stdio)"}, crawler ${stats.mode}, index ${stats.index}`, ); let signals = 0; const shutdown = (signal: string) => { signals++; if (signals > 1) process.exit(130); log(`${signal}: stopping (again to force)`); server.stop().then( () => process.exit(0), (err) => { console.error(`[bxc-agent] shutdown failed: ${err}`); process.exit(1); }, ); }; process.on("SIGINT", () => shutdown("SIGINT")); process.on("SIGTERM", () => shutdown("SIGTERM")); }