/** * @license * Copyright 2026 aphrody-code * SPDX-License-Identifier: Apache-2.0 */ import { z } from "zod"; import { McpServer } from "@modelcontextprotocol/server"; import { serveStdio } from "@modelcontextprotocol/server/stdio"; import { Database } from "bun:sqlite"; import { join } from "node:path"; import { getCapabilities } from "../capabilities.ts"; import { getBxcDir } from "../utils/paths.ts"; import packageManifest from "../../package.json" with { type: "json" }; import type { Page } from "../api/browser.ts"; import { DEFAULT_SESSION, type PageProfile, PageSessionRegistry } from "./page-sessions.ts"; // Bxc Native Imports (dynamically loaded inside tool execution for cold start speed) const pageSessions = new PageSessionRegistry({ factory: async (profile) => { const { Browser } = await import("../api/browser.ts"); return (await Browser.newPage({ profile })) as Page; }, }); const sessionField = z .string() .min(1) .max(128) .optional() .describe( 'Browser session id. Each session owns an isolated page; defaults to "default".', ); /** Session id from the tool arguments, else the transport session, else default. */ function sessionIdOf(args: { session?: string }, extra?: { sessionId?: string }): string { return args.session ?? extra?.sessionId ?? DEFAULT_SESSION; } async function getOrCreatePage( args: { session?: string }, extra?: { sessionId?: string }, profile?: PageProfile, ): Promise { return pageSessions.acquire(sessionIdOf(args, extra), profile); } function createServer(): McpServer { const server = new McpServer({ name: "bxc", version: packageManifest.version, }); server.registerTool( "bxc_archive_item", { description: "Retrieve an Internet Archive item's public metadata and file manifest without downloading media.", inputSchema: z.object({ identifier: z.string().min(1) }), annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true }, }, async (args) => { const { archive } = await import("../archive/index.ts"); const item = await archive.getItem(args.identifier); return { content: [{ type: "text", text: JSON.stringify(item, null, 2) }], structuredContent: item }; }, ); server.registerTool( "bxc_archive_search", { description: "Search Internet Archive's public catalog via AdvancedSearch, for example: collection:prelinger AND mediatype:movies.", inputSchema: z.object({ query: z.string().min(1), rows: z.number().int().min(1).max(1000).default(50), page: z.number().int().min(1).default(1) }), annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true }, }, async (args) => { const { archive } = await import("../archive/index.ts"); const result = await archive.search(args.query, { rows: args.rows, page: args.page }); return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }], structuredContent: result }; }, ); server.registerTool( "bxc_archive_wayback", { description: "List public Wayback Machine captures through the CDX API; no archived content is downloaded.", inputSchema: z.object({ url: z.string().url(), from: z.string().optional(), to: z.string().optional(), limit: z.number().int().min(1).max(1000).default(100) }), annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true }, }, async (args) => { const { archive } = await import("../archive/index.ts"); const captures = await archive.cdx(args.url, { from: args.from, to: args.to, limit: args.limit }); return { content: [{ type: "text", text: JSON.stringify(captures, null, 2) }], structuredContent: { captures } }; }, ); server.registerTool( "bxc_capabilities", { title: "Discover BXC capabilities", description: "List the canonical BXC CLI commands, MCP tools, API routes, and packages. Call this first when deciding whether BXC can handle a browser, crawl, search, extraction, media, anime, Google, Gemini, X, Grok, frames, or automation task.", inputSchema: z.object({}), annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }, }, async () => ({ content: [{ type: "text", text: JSON.stringify(getCapabilities()) }], structuredContent: getCapabilities(), }), ); /** Maps a friendly search vertical to Google's `udm` result-mode code. */ const VERTICAL_UDM: Record = { web: 14, images: 2, news: 12, videos: 7, books: 36, }; /** * 1. SQLite Memory System Tuning */ let db: Database | null = null; let setStatement: any = null; let getStatement: any = null; function getDb() { if (db) return db; // Never default to the working directory: that scattered one database per // launch location (and dropped scratch files into repositories). const dbPath = process.env.BXC_MEMORY_DB || join(getBxcDir(), "memory.sqlite"); db = new Database(dbPath); db.run("PRAGMA journal_mode = WAL;"); db.run("PRAGMA synchronous = NORMAL;"); db.run("PRAGMA temp_store = MEMORY;"); db.run(` CREATE TABLE IF NOT EXISTS memories ( id INTEGER PRIMARY KEY AUTOINCREMENT, key TEXT UNIQUE, value TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `); setStatement = db.prepare( "INSERT OR REPLACE INTO memories (key, value) VALUES (?, ?)", ); getStatement = db.prepare("SELECT value FROM memories WHERE key = ?"); return db; } server.registerTool( "tune_memory_sqlite", { description: "Stores or retrieves a fine-tuned memory fact in the high-performance SQLite database.", inputSchema: z.object({ action: z.enum(["get", "set"]), key: z.string(), value: z.string().optional(), }), }, async (args) => { getDb(); if (args.action === "set" && args.value) { setStatement.run(args.key, args.value); return { content: [ { type: "text", text: `Memory '${args.key}' tuned and saved to SQLite.`, }, ], }; } else { const result = getStatement.get(args.key) as | { value: string } | undefined; return { content: [ { type: "text", text: result ? result.value : `No memory found for key '${args.key}'.`, }, ], }; } }, ); /** * 2. Scrape to Markdown */ server.registerTool( "bxc_scrape_markdown", { description: "Scrapes a URL and returns its content in clean GFM Markdown.", inputSchema: z.object({ url: z.string().url(), profile: z .enum(["static", "fast", "http", "stealth", "max"]) .default("static"), force: z .boolean() .default(false) .describe("Bypass cache and crawl live."), }), }, async (args) => { const { smartFetch } = await import("../crawler/crawl-utils.ts"); try { const result = await smartFetch(args.url, { force: args.force, initialProfile: args.profile, }); return { content: [{ type: "text", text: result.markdown }] }; } catch (err) { return { content: [ { type: "text", text: `Error: Failed to scrape ${args.url}. Details: ${err instanceof Error ? err.message : String(err)}`, }, ], isError: true, }; } }, ); /** * 3. Detect Frameworks */ server.registerTool( "bxc_detect_frameworks", { description: "Identifies web frameworks and anti-bot protections on a URL.", inputSchema: z.object({ url: z.string().url(), }), }, async (args) => { const { Browser } = await import("../api/browser.ts"); const { detectFrameworks } = await import("../detect.ts"); const page = await Browser.newPage({ profile: "http" }); try { await page.goto(args.url); const html = await page.content(); const frameworks = await detectFrameworks({ html, headers: {} }); return { content: [{ type: "text", text: JSON.stringify(frameworks, null, 2) }], }; } finally { await page.close(); } }, ); /** * 5. CDP Native JS Evaluation */ server.registerTool( "bxc_cdp_evaluate", { description: "Executes raw JavaScript in the page context via V8.", inputSchema: z.object({ url: z.string().url(), script: z.string(), profile: z.enum(["static", "fast", "http", "stealth"]).default("stealth"), }), }, async (args) => { const { Browser } = await import("../api/browser.ts"); const page = await Browser.newPage({ profile: args.profile }); try { await page.goto(args.url); // evaluate() requires a function; wrap the raw script string const result = await page.evaluate( new Function(args.script) as () => unknown, ); return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }], }; } finally { await page.close(); } }, ); /** * 6. Google Web Search (powerful) */ server.registerTool( "bxc_search", { description: "Powerful Google Web Search. Returns ranked organic results (title, URL, snippet) and, with `rich`, the featured snippet / knowledge panel / People-Also-Ask / related searches. Authenticates automatically from ~/.bxc/cookies/google.json when present. Prefer this over manual scraping for any web lookup, fact-finding, current-events, or research task. Supports verticals (web/images/news/videos/books).", inputSchema: z.object({ query: z.string().describe("The search query."), num: z .number() .int() .min(1) .max(20) .optional() .describe("Number of results to request."), hl: z.string().optional().describe("UI language, e.g. 'en', 'fr'."), gl: z.string().optional().describe("Region bias, e.g. 'US', 'FR'."), domain: z .string() .optional() .describe("Google domain, e.g. 'google.fr'."), vertical: z .enum(["web", "images", "news", "videos", "books"]) .default("web") .describe("Search vertical."), rich: z .boolean() .default(false) .describe( "Include featured snippet / knowledge panel / PAA / related searches.", ), }), }, async (args) => { const { googleSearchRich } = await import("../google/search.ts"); const r = await googleSearchRich(args.query, { hl: args.hl, gl: args.gl, num: args.num, domain: args.domain, udm: args.rich ? undefined : (VERTICAL_UDM[args.vertical] ?? 14), classic: !args.rich, }); const payload = { query: r.query, authenticated: r.authenticated, transport: r.profileUsed, totalResults: r.totalResults, correctedQuery: r.correctedQuery, organic: r.organic.map((o) => ({ position: o.position, title: o.title, url: o.url, snippet: o.snippet, })), ...(args.rich ? { featuredSnippet: r.featuredSnippet, knowledgePanel: r.knowledgePanel, peopleAlsoAsk: r.peopleAlsoAsk, relatedSearches: r.relatedSearches, } : {}), }; return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }], }; }, ); /** * 7. Google-grade fetch + structured-data extraction */ server.registerTool( "bxc_google_fetch", { description: "Fetches a URL and returns its clean GFM Markdown plus structured metadata extracted in one pass: JSON-LD, OpenGraph, Twitter cards, canonical URL and meta description. Ideal for handing an AI both a page's content and its machine-readable metadata in a single call.", inputSchema: z.object({ url: z.string().url(), profile: z .enum(["static", "http", "fast", "stealth", "max"]) .default("http"), force: z .boolean() .default(false) .describe("Bypass cache and crawl live."), }), }, async (args) => { const { smartFetch } = await import("../crawler/crawl-utils.ts"); try { const result = await smartFetch(args.url, { force: args.force, initialProfile: args.profile as any, }); return { content: [ { type: "text", text: JSON.stringify( { url: args.url, structured: result.structured, markdown: result.markdown, }, null, 2, ), }, ], }; } catch (err) { return { content: [ { type: "text", text: `Error: Failed to fetch ${args.url}. Details: ${err instanceof Error ? err.message : String(err)}`, }, ], isError: true, }; } }, ); /** * 8. WBO Leaderboard Standings */ server.registerTool( "browser_navigate", { description: "Navigate the active browser page to a URL and wait for it to load.", inputSchema: z.object({ url: z.string().url().describe("URL to navigate to."), profile: z .enum(["static", "fast", "http", "stealth", "max"]) .optional() .describe( "Profile for this session. Omit to keep the session's current profile (stealth for a new session); a different profile replaces the session's page.", ), session: sessionField, }), }, async (args, extra) => { const page = await getOrCreatePage(args, extra, args.profile); const res = await page.goto(args.url); return { content: [ { type: "text", text: `Navigated to ${args.url}. Status: ${res.status} ${res.statusText}`, }, ], }; }, ); server.registerTool( "browser_snapshot", { description: "Get the current page content as text (title, URL, and readable body text or GFM Markdown).", inputSchema: z.object({ session: sessionField }), }, async (args, extra) => { const page = await getOrCreatePage(args, extra); const title = await page.title(); const url = page.url(); const markdown = await page.markdown(); return { content: [ { type: "text", text: `URL: ${url}\nTitle: ${title}\n\n${markdown}`, }, ], }; }, ); server.registerTool( "browser_click", { description: "Click an element matching the CSS selector.", inputSchema: z.object({ selector: z.string().describe("CSS selector of the element to click."), session: sessionField, }), }, async (args, extra) => { const page = await getOrCreatePage(args, extra); await page.click(args.selector); return { content: [ { type: "text", text: `Clicked element: ${args.selector}`, }, ], }; }, ); server.registerTool( "browser_fill", { description: "Set the value of an input element.", inputSchema: z.object({ selector: z.string().describe("CSS selector of the input element."), value: z.string().describe("Value to set."), session: sessionField, }), }, async (args, extra) => { const page = await getOrCreatePage(args, extra); await page.evaluate( ({ selector, value }: { selector: string; value: string }) => { const el = document.querySelector(selector) as HTMLInputElement | null; if (!el) throw new Error(`Element not found: ${selector}`); el.value = value; el.dispatchEvent(new Event("input", { bubbles: true })); el.dispatchEvent(new Event("change", { bubbles: true })); }, { selector: args.selector, value: args.value }, ); return { content: [ { type: "text", text: `Filled element '${args.selector}' with value.`, }, ], }; }, ); server.registerTool( "browser_type", { description: "Type text into an input element.", inputSchema: z.object({ selector: z.string().describe("CSS selector of the element."), text: z.string().describe("Text to type."), session: sessionField, }), }, async (args, extra) => { const page = await getOrCreatePage(args, extra); await page.type(args.selector, args.text); return { content: [ { type: "text", text: `Typed into element '${args.selector}'.`, }, ], }; }, ); server.registerTool( "browser_press_key", { description: "Dispatch a keyboard event (press key) on an element or the document.", inputSchema: z.object({ key: z.string().describe("Key name (e.g. Enter, Tab, Escape)."), selector: z .string() .optional() .describe("CSS selector (optional, defaults to document)."), session: sessionField, }), }, async (args, extra) => { const page = await getOrCreatePage(args, extra); await page.evaluate( ({ key, selector }: { key: string; selector: string }) => { const target = selector ? document.querySelector(selector) : document; if (!target) throw new Error(`Element not found: ${selector}`); target.dispatchEvent( new KeyboardEvent("keydown", { key, bubbles: true }), ); target.dispatchEvent( new KeyboardEvent("keyup", { key, bubbles: true }), ); }, { key: args.key, selector: args.selector ?? "" }, ); return { content: [ { type: "text", text: `Pressed key '${args.key}'.`, }, ], }; }, ); server.registerTool( "browser_select_option", { description: "Select an option from a