attach
Connect to an existing Chrome browser instance to retrieve the active tab URL and total tab count. Essential first step for interacting with pages and detecting handoff triggers.
Instructions
Connect to a running Chrome instance (must be launched with --remote-debugging-port). Returns the active tab URL and total tab count. Always call this first.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| port | No | CDP port; default 9222 |
Implementation Reference
- src/index.ts:150-188 (handler)The handler function for the 'attach' tool. Connects to a Chrome instance via CDP on the specified port (default 9222), creates or picks an active tab, and returns status, URL, title, and tab count.
async function attach(args: { port?: number }) { const port = args.port ?? 9222; if (browser) { return { status: 'already attached', url: page?.url() ?? null, }; } try { browser = await chromium.connectOverCDP(`http://localhost:${port}`); } catch (e) { return { error: `Could not connect to Chrome on port ${port}. ` + `Launch Chrome with: open -a "Google Chrome" --args --remote-debugging-port=${port} --user-data-dir=$HOME/.chrome-pilot`, details: (e as Error).message, }; } const contexts = browser.contexts(); if (contexts.length === 0) { return { error: 'Browser has no contexts. Open at least one tab.' }; } const ctx = contexts[0]; const pages = ctx.pages(); if (pages.length === 0) { page = await ctx.newPage(); } else { // Pick the most recently active-looking tab: prefer non-blank, non-chrome:// URLs. page = pages.find(p => { const u = p.url(); return u && !u.startsWith('chrome://') && u !== 'about:blank'; }) ?? pages[0]; } return { status: 'attached', url: page.url(), title: await page.title().catch(() => '(unavailable)'), tabCount: pages.length, }; } - src/index.ts:343-352 (schema)Tool registration metadata for 'attach', defining its name, description, and input schema (optional port parameter).
{ name: 'attach', description: 'Connect to a running Chrome instance (must be launched with --remote-debugging-port). ' + 'Returns the active tab URL and total tab count. Always call this first.', inputSchema: { type: 'object', properties: { port: { type: 'number', description: 'CDP port; default 9222' } }, }, }, - src/index.ts:461-461 (registration)The request handler switch-case that dispatches the 'attach' tool name to the attach function.
case 'attach': result = await attach(args as { port?: number }); break; - src/index.ts:78-84 (helper)Helper function that throws an error referencing attach if no page is active, used by other tools to ensure attach was called first.
function requirePage(): Page { if (!page) { throw new Error( 'Not attached. Call `attach` first (Chrome must be running with --remote-debugging-port=9222).' ); } return page;