#!/usr/bin/env bun /** * cdp-toolkit CLI. * * bun run src/cli.ts [--target ] [--json ''] [-- ...] * bun run src/cli.ts --list * * Argv parsing rules (see CONTRACT.md "Integration"): * - First positional token is the tool name (a key of TOOLS). * - `--json ''` parses a JSON object and merges it into the args object. * - `--target ` sets `args.target` (a TargetSelector string). * - Any other `--key value` pair becomes `args.key`. When the tool's MANIFEST * inputSchema declares the key `type: "string"`, the raw string is kept * as-is (so a CDP requestId like "91775.10" is not turned into the number * 91775.1). Otherwise the value is coerced: "true"/"false" -> boolean, a * numeric string -> number, else the raw string. A bare `--flag` with no following value (or followed by another * --flag) is treated as boolean true. * - Explicit `--key` pairs OVERRIDE keys merged from `--json` (last writer * wins; --json is applied first, then the individual flags). * * Output: * - success -> JSON.stringify(result ?? null, null, 2) to stdout, exit 0. * - throw -> JSON.stringify({ error: message }) to stderr, exit 1. * - no tool -> usage message to stderr, exit 1. * - --list -> all tool names (one per line) to stdout, exit 0. */ import { TOOLS, TOOL_NAMES, type ToolName } from "./index.ts"; import { resolveBackend, stripBrowserFlag, stripConnectFlag, startFirefoxSession } from "./backend.ts"; import { toolAvailability } from "./capabilities.ts"; import { FIREFOX_TOOLS } from "./firefox-tools.ts"; import { leaseFromArgs, withLeaseScope } from "./leases.ts"; import { ENDPOINTS_FIREFOX_MESSAGE, stripEndpointArgs, usesEndpointArgs, withEndpointScope } from "./endpoints.ts"; import { MANIFEST } from "./manifest.ts"; import { assertAllowed } from "./policy.ts"; import { runInstaller } from "./install/wizard.ts"; import { realpathSync } from "node:fs"; import { fileURLToPath } from "node:url"; /** * True when this module is the process's entry script — the ONLY condition under which main() * runs. Works under both node and bun, ESM included: compare this module's real path with the * realpath of argv[1] (realpath resolves the bunx/npm bin symlink and any /tmp-style symlinked * directory). Importing this module (tests, embedders) leaves argv[1] pointing elsewhere, so the * import stays silent — no tool dispatch, no usage message. */ function isDirectRun(): boolean { const entry = process.argv[1]; if (!entry) return false; try { return fileURLToPath(import.meta.url) === realpathSync(entry); } catch { // argv[1] may not exist as a file (eval strings, wrappers); never treat that as direct. return false; } } const USAGE = `cdp-toolkit: raw single-target CDP, 29-tool chrome-devtools-mcp parity, plus a Firefox backend over WebDriver BiDi. Usage: bun run src/cli.ts [--browser chrome|firefox] [--connect ] [--target ] [--json ''] [-- ...] bun run src/cli.ts --list [--browser chrome|firefox] bun run src/cli.ts --capabilities [--browser chrome|firefox] bun run src/cli.ts --help | -h # this message bun run src/cli.ts --help | -h # that tool's arguments, sourced from its schema Examples: bun run src/cli.ts list_pages bun run src/cli.ts navigate_page --target index:0 --url https://example.com bun run src/cli.ts click --target index:0 --uid 42 bun run src/cli.ts evaluate_script --json '{"expression":"1+2"}' bun run src/cli.ts take_screenshot --target url:example --fullPage true bun run src/cli.ts --browser firefox take_snapshot bun run src/cli.ts --capabilities --browser firefox bun run src/cli.ts take_screenshot --help bun run src/cli.ts --connect 9223 take_snapshot # attach to your own logged-in Firefox (implies --browser firefox) --help/-h is recognised ANYWHERE in argv, before any tool dispatch: it never touches the browser (no CDP connection, no lease, no file written) and is never passed through as a tool argument, even when it appears after a tool name. Backend selection: --browser chrome|firefox, else the CDP_BROWSER env var, else "chrome" (default, zero behavior change for existing users). Firefox runs in one of two modes: - LAUNCH (default): a fresh throwaway-profile Firefox is spawned for this one invocation, used for exactly one tool call, then disposed (session ended, process killed) before the process exits. This is a login wall for anything that needs your real session. - ATTACH (--connect , or the CDP_FIREFOX_ENDPOINT env var): connects to a Firefox YOU already started with --remote-debugging-port, so tools see your real logged-in profile. This process never launches or kills that Firefox; dispose only ends the BiDi session. --connect implies --browser firefox and conflicts with an explicit --browser chrome. Firefox allows only one active BiDi session at a time, so a client that dies without disposing cleanly (e.g. SIGKILL) can leave the slot occupied until Firefox restarts. Target selector grammar: active | index:N | url: | title: | label: | plus worker: (Chrome only) for evaluate_script, list_network_requests, get_network_request and list_console_messages ONLY: an MV3 extension's background service worker, e.g. worker:. An idle-evicted worker is started first unless wake:false. Recording a worker keeps it alive for the length of the capture. Leases: pass --lease to act on a tab another agent claimed with claim_page (MCP only). Run list_leases to see who holds what; release_page --lease gives a lease back. Run with --list to print every tool name available under the selected backend. Run with --capabilities to see, per tool, whether it is available and (if not) which capability the selected backend is missing.`; /** Coerce a raw CLI string into boolean / number / string. */ function coerce(raw: string): boolean | number | string { if (raw === "true") return true; if (raw === "false") return false; // Numbers: only when the trimmed string round-trips through Number cleanly. if (raw.trim() !== "" && !Number.isNaN(Number(raw)) && /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(raw.trim())) { return Number(raw); } return raw; } /** * Coerce one `--key value` using the tool's declared schema type. A key the * schema types as "string" keeps its raw text verbatim; coercing it would turn * an id that merely LOOKS numeric ("91775.10", "007") into a number that no * longer matches, or into a different string entirely. Every other key (or a * tool/key the manifest doesn't know) falls back to coerce(). */ function coerceForTool(tool: string | undefined, key: string, raw: string): boolean | number | string { const spec = tool === undefined ? undefined : MANIFEST.find((t) => t.name === tool); const prop = spec?.inputSchema.properties?.[key] as { type?: unknown } | undefined; if (prop?.type === "string") return raw; return coerce(raw); } interface ParsedArgs { tool?: string; list: boolean; capabilities: boolean; help: boolean; args: Record; } /** Parse process argv (already sliced to drop the runtime + script, and with --browser already stripped). */ export function parseArgv(argv: string[]): ParsedArgs { const out: ParsedArgs = { list: false, capabilities: false, help: false, args: {} }; // Collect flag pairs separately so --json can be merged BEFORE individual // flags override it, regardless of token order. let jsonObj: Record | undefined; // Raw values are kept until the tool name is known (it may follow the flags), // so coercion can consult that tool's schema. const flagPairs: Array<[string, string | true]> = []; for (let i = 0; i < argv.length; i++) { const token = argv[i]!; if (token === "--list") { out.list = true; continue; } if (token === "--capabilities") { out.capabilities = true; continue; } // Recognised ANYWHERE in argv (not just as the first token), and BEFORE the // generic "--key value" branch below, so --help/-h can never be swallowed as // a tool argument (the bug: `take_screenshot --help` used to run the tool // with args.help=true; `-h` doesn't even start with "--", so without this // explicit check it fell through to the positional branch and, if a tool // name was already set, was silently dropped and the tool ran anyway). if (token === "--help" || token === "-h") { out.help = true; continue; } if (token.startsWith("--")) { const key = token.slice(2); const next = argv[i + 1]; // A value follows unless we're at the end or the next token is another flag. const hasValue = next !== undefined && !next.startsWith("--"); const rawValue = hasValue ? next! : "true"; if (hasValue) i++; if (key === "json") { const parsed = JSON.parse(rawValue) as unknown; if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) { throw new Error("--json must be a JSON object"); } jsonObj = parsed as Record; continue; } if (key === "target") { flagPairs.push(["target", rawValue]); continue; } flagPairs.push([key, hasValue ? rawValue : true]); continue; } // First non-flag positional is the tool name; ignore any extras. if (out.tool === undefined) out.tool = token; } // --json first, then explicit flags win. if (jsonObj) Object.assign(out.args, jsonObj); for (const [k, v] of flagPairs) { out.args[k] = v === true || k === "target" ? v : coerceForTool(out.tool, k, v); } return out; } function isToolName(name: string): name is ToolName { return Object.prototype.hasOwnProperty.call(TOOLS, name); } /** A JSON-Schema property shape narrow enough for the fields --help prints. */ interface HelpProp { type?: string | string[]; enum?: unknown[]; description?: string; } /** "string", "string|array" (a union type array), or an enum rendered as "png|jpeg". */ function formatType(prop: HelpProp | undefined): string { if (!prop) return "any"; if (Array.isArray(prop.enum) && prop.enum.length > 0) return prop.enum.map(String).join("|"); if (Array.isArray(prop.type)) return prop.type.join("|"); return prop.type ?? "any"; } /** * Print one tool's usage sourced ENTIRELY from MANIFEST's inputSchema (src/manifest.ts) — the * same JSON Schema the MCP server advertises via tools/list. This is a read of that single * source of truth, not a second hand-maintained argument list that could drift from it. */ function printToolHelp(name: ToolName): void { const spec = MANIFEST.find((t) => t.name === name); if (!spec) { // Every TOOLS entry has a MANIFEST entry (auditCoverage() in mcp.ts warns otherwise); this // is a defensive fallback, not an expected path. process.stdout.write(`${name}\n`); return; } const required = new Set(spec.inputSchema.required ?? []); const props = (spec.inputSchema.properties ?? {}) as Record; const keys = Object.keys(props); const lines = [spec.name, "", spec.description, ""]; if (keys.length === 0) { lines.push("Arguments: none."); } else { lines.push("Arguments:"); for (const key of keys) { const prop = props[key]; const reqTag = required.has(key) ? "required" : "optional"; lines.push(` --${key} <${formatType(prop)}> (${reqTag})`); if (prop?.description) lines.push(` ${prop.description}`); } } lines.push("", `Usage: cdp ${spec.name} [--target ] [--json ''] [-- ...]`); process.stdout.write(`${lines.join("\n")}\n`); } async function main(): Promise { const rawArgv = process.argv.slice(2); // `install` is a CLI-ONLY subcommand (the `cdp install` wizard), not an MCP tool: it is not in // TOOLS/MANIFEST and never appears in --list or tools/list. Dispatch it FIRST — before --browser // resolution, --help, and tool dispatch — so `cdp install --help` reaches the installer's own // help rather than the global USAGE, and so nothing below can reinterpret its flags. if (rawArgv[0] === "install") { return await runInstaller(rawArgv.slice(1)); } const { kind: browser, endpoint } = resolveBackend(rawArgv); const parsed = parseArgv(stripConnectFlag(stripBrowserFlag(rawArgv))); // --help/-h short-circuits BEFORE any availability lookup or backend touch — no CDP // connection, no lease, no file written. This must be the very first thing checked in // main(), ahead of --list/--capabilities, so a --help gesture can never be downgraded // into a real dispatch by any branch below it. if (parsed.help) { if (!parsed.tool) { process.stdout.write(`${USAGE}\n`); return 0; } if (!isToolName(parsed.tool)) { process.stderr.write( `${JSON.stringify({ error: `unknown tool '${parsed.tool}'. Run --list to see all ${TOOL_NAMES.length} tools.` })}\n`, ); return 1; } printToolHelp(parsed.tool); return 0; } const availability = toolAvailability(browser); const availableSet = new Set(availability.available); if (parsed.capabilities) { const lines = [`backend: ${browser}`, "", "available:"]; for (const name of availability.available) lines.push(` ${name}`); lines.push("", "unavailable:"); for (const u of availability.unavailable) lines.push(` ${u.name} (needs: ${u.missing.join(", ")})`); process.stdout.write(`${lines.join("\n")}\n`); return 0; } if (parsed.list) { process.stdout.write(`${availability.available.join("\n")}\n`); return 0; } if (!parsed.tool) { process.stderr.write(`${USAGE}\n`); return 1; } if (!isToolName(parsed.tool)) { process.stderr.write( `${JSON.stringify({ error: `unknown tool '${parsed.tool}'. Run --list to see all ${TOOL_NAMES.length} tools.` })}\n`, ); return 1; } if (!availableSet.has(parsed.tool)) { const gap = availability.unavailable.find((u) => u.name === parsed.tool); process.stderr.write( `${JSON.stringify({ error: `tool '${parsed.tool}' is not available under --browser ${browser}${gap ? ` (needs: ${gap.missing.join(", ")})` : ""}. Run --capabilities --browser ${browser} to see the full list.`, })}\n`, ); return 1; } // Decision: the CLI cannot claim a lease. Per backend.ts, a CLI invocation is // one process per call, so the claiming process is already dead by the next // call and the dead-pid rule would make the lease reclaimable at once, // regardless of ttlMs. A lease that is reclaimable on arrival is worse than // no lease, because it reads as protection that is not there. Every OTHER // CLI call still goes through assertLeaseOk and may present --lease. if (parsed.tool === "claim_page") { process.stderr.write( `${JSON.stringify({ error: "claim_page is not available from the CLI: a CLI invocation is one process per call, so the lease it claimed would be reclaimable immediately by the dead-pid rule. Claim from the cdp-toolkit MCP server, which is long lived, then pass the token to CLI calls with --lease .", })}\n`, ); return 1; } // ONE lease scope per invocation, wrapping BOTH backend branches, exactly as // mcp.ts does. `--lease ` lands in parsed.args like any other flag, so // no tool signature changes and a tool added later is covered for free. const tool = parsed.tool; return withLeaseScope(leaseFromArgs(parsed.args), async () => { if (browser === "chrome") { const fn = TOOLS[tool]; // Same endpoint scope as mcp.ts's runTool: the endpoint:/ prefix (or // --endpoint) is resolved and stripped once, here. A bad name or a malformed // CDP_ENDPOINTS throws to main's catch, which prints {"error": ...} and exits 1. const { endpoint, args: toolArgs } = stripEndpointArgs(parsed.args); // Read-only endpoint policy, before the tool runs (same check as mcp.ts's runTool). // A PolicyError throws to main's catch: {"error": "'click' is not allowed on endpoint ..."}, exit 1. assertAllowed(tool, endpoint, toolArgs); // The registry's value type is the union of all tool signatures; each tool // validates its own args at runtime, so we hand the parsed object through. const result = await withEndpointScope(endpoint, () => (fn as (args: unknown) => Promise)(toolArgs)); process.stdout.write(`${JSON.stringify(result ?? null, null, 2)}\n`); return 0; } // Firefox: one process per invocation. Launch (or, with --connect/CDP_FIREFOX_ENDPOINT, // attach), run exactly one tool call, always dispose, even if the tool call itself throws — // in launch mode that reaps the spawned process; in attach mode it only ends the BiDi session. if (usesEndpointArgs(parsed.args)) { process.stderr.write(`${JSON.stringify({ error: ENDPOINTS_FIREFOX_MESSAGE })}\n`); return 1; } const neutralFn = FIREFOX_TOOLS[tool]; if (!neutralFn) { process.stderr.write(`${JSON.stringify({ error: `tool '${tool}' has no Firefox implementation wired` })}\n`); return 1; } const session = await startFirefoxSession({ endpoint }); try { const result = await neutralFn(session.driver, parsed.args as never); process.stdout.write(`${JSON.stringify(result ?? null, null, 2)}\n`); return 0; } finally { await session.dispose(); } }); } if (isDirectRun()) { main() .then((code) => process.exit(code)) .catch((err: unknown) => { const message = err instanceof Error ? err.message : String(err); process.stderr.write(`${JSON.stringify({ error: message })}\n`); process.exit(1); }); }