Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/cli.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,6 +110,11 @@ export const cliOptions = {
description: 'Marionette port to connect to when using --connect-existing (default: 2828)',
default: Number(process.env.MARIONETTE_PORT ?? '2828'),
},
marionetteHost: {
type: 'string',
description: 'Marionette host to connect to when using --connect-existing (default: 127.0.0.1). Also used as the BiDi WebSocket connect address when different from 127.0.0.1.',
default: process.env.MARIONETTE_HOST ?? '127.0.0.1',
},
env: {
type: 'array',
description:
Expand Down
117 changes: 102 additions & 15 deletions src/firefox/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,7 @@ import { spawn, type ChildProcess } from 'node:child_process';
import { mkdirSync, openSync, closeSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import WebSocket from 'ws';
import type { FirefoxLaunchOptions } from './types.js';
import { log, logDebug } from '../utils/logger.js';

Expand DownExpand Up@@ -129,21 +130,26 @@ class GeckodriverHttpDriver implements IDriver {
private baseUrl: string;
private sessionId: string;
private gdProcess: ChildProcess;
private webSocketUrl: string | null;
private bidiConnection: IBiDi | null = null;

constructor(baseUrl: string, sessionId: string, gdProcess: ChildProcess) {
constructor(baseUrl: string, sessionId: string, gdProcess: ChildProcess, webSocketUrl: string | null) {
this.baseUrl = baseUrl;
this.sessionId = sessionId;
this.gdProcess = gdProcess;
this.webSocketUrl = webSocketUrl;
}

static async connect(marionettePort: number): Promise<GeckodriverHttpDriver> {
static async connect(marionettePort: number, marionetteHost = '127.0.0.1'): Promise<GeckodriverHttpDriver> {
// Find geckodriver binary via selenium-manager
const path = await import('node:path');
const { execFileSync } = await import('node:child_process');

let geckodriverPath: string;
try {
// selenium-manager ships with selenium-webdriver and resolves/downloads geckodriver
// selenium-manager ships with selenium-webdriver and resolves/downloads geckodriver.
// Use --driver instead of --browser to skip downloading Firefox, which is
// already running externally in connect-existing mode.
const { createRequire } = await import('node:module');
const require = createRequire(import.meta.url);
const swPkg = require.resolve('selenium-webdriver/package.json');
Expand All@@ -157,7 +163,7 @@ class GeckodriverHttpDriver implements IDriver {
const ext = process.platform === 'win32' ? '.exe' : '';
const smBin = path.join(swDir, 'bin', platform, `selenium-manager${ext}`);
const result = JSON.parse(
execFileSync(smBin, ['--browser', 'firefox', '--output', 'json'], { encoding: 'utf-8' })
execFileSync(smBin, ['--driver', 'geckodriver', '--output', 'json'], { encoding: 'utf-8' })
);
geckodriverPath = result.result.driver_path;
} catch {
Expand All@@ -175,7 +181,7 @@ class GeckodriverHttpDriver implements IDriver {
// Use --port=0 to let the OS assign a free port atomically (geckodriver ≥0.34.0)
const gd = spawn(
geckodriverPath,
['--connect-existing', '--marionette-port', String(marionettePort), '--port', '0'],
['--connect-existing', '--marionette-host', marionetteHost, '--marionette-port', String(marionettePort), '--port', '0'],
{ stdio: ['ignore', 'pipe', 'pipe'] }
);

Expand DownExpand Up@@ -206,11 +212,11 @@ class GeckodriverHttpDriver implements IDriver {

const baseUrl = `http://127.0.0.1:${port}`;

// Create a WebDriver session
// Create a WebDriver session with BiDi opt-in
const resp = await fetch(`${baseUrl}/session`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ capabilities: { alwaysMatch: {} } }),
body: JSON.stringify({ capabilities: { alwaysMatch: { webSocketUrl: true } } }),
});
const json = (await resp.json()) as {
value: { sessionId: string; capabilities: Record<string, unknown> };
Expand All@@ -219,7 +225,21 @@ class GeckodriverHttpDriver implements IDriver {
throw new Error(`Failed to create session: ${JSON.stringify(json)}`);
}

return new GeckodriverHttpDriver(baseUrl, json.value.sessionId, gd);
let wsUrl = json.value.capabilities.webSocketUrl as string | undefined;
logDebug(`Session capabilities webSocketUrl: ${wsUrl ?? 'not present'}, marionetteHost: ${marionetteHost}`);
if (wsUrl && marionetteHost !== '127.0.0.1') {
// Rewrite the URL to connect through the remote host / tunnel.
const parsed = new URL(wsUrl);
parsed.hostname = marionetteHost;
wsUrl = parsed.toString();
}
if (wsUrl) {
logDebug(`BiDi WebSocket URL: ${wsUrl}`);
} else {
logDebug('BiDi WebSocket URL not available (Firefox may not support it or Remote Agent is not running)');
}

return new GeckodriverHttpDriver(baseUrl, json.value.sessionId, gd, wsUrl ?? null);
}

private async cmd(method: string, path: string, body?: unknown): Promise<unknown> {
Expand DownExpand Up@@ -422,6 +442,10 @@ class GeckodriverHttpDriver implements IDriver {
}

async quit(): Promise<void> {
if (this.bidiConnection) {
(this.bidiConnection.socket as unknown as WebSocket).close();
this.bidiConnection = null;
}
try {
await this.cmd('DELETE', '');
} catch {
Expand All@@ -430,13 +454,75 @@ class GeckodriverHttpDriver implements IDriver {
this.gdProcess.kill();
}

/** Kill the geckodriver process without closing Firefox */
kill(): void {
/** Kill the geckodriver process without closing Firefox.
* Deletes the session first so Marionette accepts new connections. */
async kill(): Promise<void> {
if (this.bidiConnection) {
(this.bidiConnection.socket as unknown as WebSocket).close();
this.bidiConnection = null;
}
try {
await this.cmd('DELETE', '');
} catch {
// ignore
}
this.gdProcess.kill();
}

getBidi(): Promise<IBiDi> {
throw new Error('BiDi not available in connect-existing mode');
/**
* Return a BiDi handle. Opens a WebSocket to Firefox's Remote Agent on
* first call, using the webSocketUrl returned in the session capabilities.
*/
async getBidi(): Promise<IBiDi> {
if (this.bidiConnection) return this.bidiConnection;
if (!this.webSocketUrl) {
throw new Error(
'BiDi is not available: no webSocketUrl in session capabilities. ' +
'Ensure Firefox was started with --remote-debugging-port.'
);
}

const ws = new WebSocket(this.webSocketUrl);
await new Promise<void>((resolve, reject) => {
ws.on('open', resolve);
ws.on('error', (e: any) => {
const msg = e?.message || e?.error?.message || e?.error || e?.type || JSON.stringify(e) || String(e);
reject(new Error(`BiDi WS to ${this.webSocketUrl}: ${msg}`));
});
});

let cmdId = 0;
const subscribe = async (event: string, contexts?: string[]): Promise<void> => {
const msg: Record<string, unknown> = {
id: ++cmdId,
method: 'session.subscribe',
params: { events: [event] },
};
if (contexts) msg.params = { events: [event], contexts };
ws.send(JSON.stringify(msg));
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error(`BiDi subscribe timeout for ${event}`)), 5000);
const onMsg = (data: WebSocket.Data) => {
try {
const payload = JSON.parse(data.toString());
if (payload.id === cmdId) {
clearTimeout(timeout);
ws.off('message', onMsg);
if (payload.error) {
reject(new Error(`BiDi subscribe error: ${payload.error}`));
} else {
resolve();
}
}
} catch { /* ignore parse errors from event messages */ }
};
ws.on('message', onMsg);
});
logDebug(`BiDi subscribed to ${event}`);
};

this.bidiConnection = { subscribe, socket: ws as unknown as IBiDiSocket } as any;
return this.bidiConnection;
}
}

Expand DownExpand Up@@ -503,7 +589,8 @@ export class FirefoxCore {
// We bypass selenium-webdriver because its BiDi auto-upgrade hangs
// when used with geckodriver's --connect-existing mode.
const port = this.options.marionettePort ?? 2828;
this.driver = await GeckodriverHttpDriver.connect(port);
const host = this.options.marionetteHost ?? '127.0.0.1';
this.driver = await GeckodriverHttpDriver.connect(port, host);
} else {
// Set up output file for capturing Firefox stdout/stderr
if (this.options.logFile) {
Expand DownExpand Up@@ -640,7 +727,7 @@ export class FirefoxCore {
*/
reset(): void {
if (this.driver && this.options.connectExisting && 'kill' in this.driver) {
(this.driver as { kill(): void }).kill();
(this.driver as { kill(): Promise<void> }).kill();
}
this.driver = null;
this.currentContextId = null;
Expand DownExpand Up@@ -762,7 +849,7 @@ export class FirefoxCore {
async close(): Promise<void> {
if (this.driver) {
if (this.options.connectExisting && 'kill' in this.driver) {
(this.driver as { kill(): void }).kill();
await (this.driver as { kill(): Promise<void> }).kill();
} else if ('quit' in this.driver) {
await (this.driver as { quit(): Promise<void> }).quit();
}
Expand Down
1 change: 1 addition & 0 deletions src/firefox/types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,6 +60,7 @@ export interface FirefoxLaunchOptions {
acceptInsecureCerts?: boolean | undefined;
connectExisting?: boolean | undefined;
marionettePort?: number | undefined;
marionetteHost?: string | undefined;
env?: Record<string, string> | undefined;
logFile?: string | undefined;
/** Firefox preferences to set at startup via moz:firefoxOptions */
Expand Down
26 changes: 23 additions & 3 deletions src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,11 +98,11 @@ export async function getFirefox(): Promise<FirefoxDevTools> {
if (firefox) {
const isConnected = await firefox.isConnected();
if (!isConnected) {
log('Firefox connection lost - browser was closed or disconnected');
log('Firefox connection lost, reconnecting...');
resetFirefox();
throw new FirefoxDisconnectedError('Browser was closed');
} else {
return firefox;
}
return firefox;
}

// No existing instance - create new connection
Expand DownExpand Up@@ -142,6 +142,7 @@ export async function getFirefox(): Promise<FirefoxDevTools> {
acceptInsecureCerts: args.acceptInsecureCerts,
connectExisting: args.connectExisting,
marionettePort: args.marionettePort,
marionetteHost: args.marionetteHost,
env: envVars,
logFile: args.outputFile ?? undefined,
prefs,
Expand DownExpand Up@@ -358,6 +359,25 @@ async function main() {

log('Firefox DevTools MCP server running on stdio');
log('Ready to accept tool requests');

// Clean up the Marionette session so Firefox accepts new connections.
// Without this, the session stays locked after the MCP client disconnects.
const cleanup = async () => {
if (firefox) {
try {
await firefox.close();
} catch {
// ignore
}
}
await server.close();
process.exit(0);
};
process.on('SIGTERM', cleanup);
process.on('SIGINT', cleanup);
// StdioServerTransport does not fire onclose on stdin EOF.
process.stdin.on('end', cleanup);
process.stdin.on('close', cleanup);
}

// Only run main() if this file is executed directly (not imported)
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/cli.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,6 +110,11 @@ export const cliOptions = {
description: 'Marionette port to connect to when using --connect-existing (default: 2828)',
default: Number(process.env.MARIONETTE_PORT ?? '2828'),
},
marionetteHost: {
type: 'string',
description: 'Marionette host to connect to when using --connect-existing (default: 127.0.0.1). Also used as the BiDi WebSocket connect address when different from 127.0.0.1.',
default: process.env.MARIONETTE_HOST ?? '127.0.0.1',
},
env: {
type: 'array',
description:
Expand Down
117 changes: 102 additions & 15 deletions src/firefox/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,7 @@ import { spawn, type ChildProcess } from 'node:child_process';
import { mkdirSync, openSync, closeSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import WebSocket from 'ws';
import type { FirefoxLaunchOptions } from './types.js';
import { log, logDebug } from '../utils/logger.js';

Expand DownExpand Up@@ -129,21 +130,26 @@ class GeckodriverHttpDriver implements IDriver {
private baseUrl: string;
private sessionId: string;
private gdProcess: ChildProcess;
private webSocketUrl: string | null;
private bidiConnection: IBiDi | null = null;

constructor(baseUrl: string, sessionId: string, gdProcess: ChildProcess) {
constructor(baseUrl: string, sessionId: string, gdProcess: ChildProcess, webSocketUrl: string | null) {
this.baseUrl = baseUrl;
this.sessionId = sessionId;
this.gdProcess = gdProcess;
this.webSocketUrl = webSocketUrl;
}

static async connect(marionettePort: number): Promise<GeckodriverHttpDriver> {
static async connect(marionettePort: number, marionetteHost = '127.0.0.1'): Promise<GeckodriverHttpDriver> {
// Find geckodriver binary via selenium-manager
const path = await import('node:path');
const { execFileSync } = await import('node:child_process');

let geckodriverPath: string;
try {
// selenium-manager ships with selenium-webdriver and resolves/downloads geckodriver
// selenium-manager ships with selenium-webdriver and resolves/downloads geckodriver.
// Use --driver instead of --browser to skip downloading Firefox, which is
// already running externally in connect-existing mode.
const { createRequire } = await import('node:module');
const require = createRequire(import.meta.url);
const swPkg = require.resolve('selenium-webdriver/package.json');
Expand All@@ -157,7 +163,7 @@ class GeckodriverHttpDriver implements IDriver {
const ext = process.platform === 'win32' ? '.exe' : '';
const smBin = path.join(swDir, 'bin', platform, `selenium-manager${ext}`);
const result = JSON.parse(
execFileSync(smBin, ['--browser', 'firefox', '--output', 'json'], { encoding: 'utf-8' })
execFileSync(smBin, ['--driver', 'geckodriver', '--output', 'json'], { encoding: 'utf-8' })
);
geckodriverPath = result.result.driver_path;
} catch {
Expand All@@ -175,7 +181,7 @@ class GeckodriverHttpDriver implements IDriver {
// Use --port=0 to let the OS assign a free port atomically (geckodriver ≥0.34.0)
const gd = spawn(
geckodriverPath,
['--connect-existing', '--marionette-port', String(marionettePort), '--port', '0'],
['--connect-existing', '--marionette-host', marionetteHost, '--marionette-port', String(marionettePort), '--port', '0'],
{ stdio: ['ignore', 'pipe', 'pipe'] }
);

Expand DownExpand Up@@ -206,11 +212,11 @@ class GeckodriverHttpDriver implements IDriver {

const baseUrl = `http://127.0.0.1:${port}`;

// Create a WebDriver session
// Create a WebDriver session with BiDi opt-in
const resp = await fetch(`${baseUrl}/session`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ capabilities: { alwaysMatch: {} } }),
body: JSON.stringify({ capabilities: { alwaysMatch: { webSocketUrl: true } } }),
});
const json = (await resp.json()) as {
value: { sessionId: string; capabilities: Record<string, unknown> };
Expand All@@ -219,7 +225,21 @@ class GeckodriverHttpDriver implements IDriver {
throw new Error(`Failed to create session: ${JSON.stringify(json)}`);
}

return new GeckodriverHttpDriver(baseUrl, json.value.sessionId, gd);
let wsUrl = json.value.capabilities.webSocketUrl as string | undefined;
logDebug(`Session capabilities webSocketUrl: ${wsUrl ?? 'not present'}, marionetteHost: ${marionetteHost}`);
if (wsUrl && marionetteHost !== '127.0.0.1') {
// Rewrite the URL to connect through the remote host / tunnel.
const parsed = new URL(wsUrl);
parsed.hostname = marionetteHost;
wsUrl = parsed.toString();
}
if (wsUrl) {
logDebug(`BiDi WebSocket URL: ${wsUrl}`);
} else {
logDebug('BiDi WebSocket URL not available (Firefox may not support it or Remote Agent is not running)');
}

return new GeckodriverHttpDriver(baseUrl, json.value.sessionId, gd, wsUrl ?? null);
}

private async cmd(method: string, path: string, body?: unknown): Promise<unknown> {
Expand DownExpand Up@@ -422,6 +442,10 @@ class GeckodriverHttpDriver implements IDriver {
}

async quit(): Promise<void> {
if (this.bidiConnection) {
(this.bidiConnection.socket as unknown as WebSocket).close();
this.bidiConnection = null;
}
try {
await this.cmd('DELETE', '');
} catch {
Expand All@@ -430,13 +454,75 @@ class GeckodriverHttpDriver implements IDriver {
this.gdProcess.kill();
}

/** Kill the geckodriver process without closing Firefox */
kill(): void {
/** Kill the geckodriver process without closing Firefox.
* Deletes the session first so Marionette accepts new connections. */
async kill(): Promise<void> {
if (this.bidiConnection) {
(this.bidiConnection.socket as unknown as WebSocket).close();
this.bidiConnection = null;
}
try {
await this.cmd('DELETE', '');
} catch {
// ignore
}
this.gdProcess.kill();
}

getBidi(): Promise<IBiDi> {
throw new Error('BiDi not available in connect-existing mode');
/**
* Return a BiDi handle. Opens a WebSocket to Firefox's Remote Agent on
* first call, using the webSocketUrl returned in the session capabilities.
*/
async getBidi(): Promise<IBiDi> {
if (this.bidiConnection) return this.bidiConnection;
if (!this.webSocketUrl) {
throw new Error(
'BiDi is not available: no webSocketUrl in session capabilities. ' +
'Ensure Firefox was started with --remote-debugging-port.'
);
}

const ws = new WebSocket(this.webSocketUrl);
await new Promise<void>((resolve, reject) => {
ws.on('open', resolve);
ws.on('error', (e: any) => {
const msg = e?.message || e?.error?.message || e?.error || e?.type || JSON.stringify(e) || String(e);
reject(new Error(`BiDi WS to ${this.webSocketUrl}: ${msg}`));
});
});

let cmdId = 0;
const subscribe = async (event: string, contexts?: string[]): Promise<void> => {
const msg: Record<string, unknown> = {
id: ++cmdId,
method: 'session.subscribe',
params: { events: [event] },
};
if (contexts) msg.params = { events: [event], contexts };
ws.send(JSON.stringify(msg));
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error(`BiDi subscribe timeout for ${event}`)), 5000);
const onMsg = (data: WebSocket.Data) => {
try {
const payload = JSON.parse(data.toString());
if (payload.id === cmdId) {
clearTimeout(timeout);
ws.off('message', onMsg);
if (payload.error) {
reject(new Error(`BiDi subscribe error: ${payload.error}`));
} else {
resolve();
}
}
} catch { /* ignore parse errors from event messages */ }
};
ws.on('message', onMsg);
});
logDebug(`BiDi subscribed to ${event}`);
};

this.bidiConnection = { subscribe, socket: ws as unknown as IBiDiSocket } as any;
return this.bidiConnection;
}
}

Expand DownExpand Up@@ -503,7 +589,8 @@ export class FirefoxCore {
// We bypass selenium-webdriver because its BiDi auto-upgrade hangs
// when used with geckodriver's --connect-existing mode.
const port = this.options.marionettePort ?? 2828;
this.driver = await GeckodriverHttpDriver.connect(port);
const host = this.options.marionetteHost ?? '127.0.0.1';
this.driver = await GeckodriverHttpDriver.connect(port, host);
} else {
// Set up output file for capturing Firefox stdout/stderr
if (this.options.logFile) {
Expand DownExpand Up@@ -640,7 +727,7 @@ export class FirefoxCore {
*/
reset(): void {
if (this.driver && this.options.connectExisting && 'kill' in this.driver) {
(this.driver as { kill(): void }).kill();
(this.driver as { kill(): Promise<void> }).kill();
}
this.driver = null;
this.currentContextId = null;
Expand DownExpand Up@@ -762,7 +849,7 @@ export class FirefoxCore {
async close(): Promise<void> {
if (this.driver) {
if (this.options.connectExisting && 'kill' in this.driver) {
(this.driver as { kill(): void }).kill();
await (this.driver as { kill(): Promise<void> }).kill();
} else if ('quit' in this.driver) {
await (this.driver as { quit(): Promise<void> }).quit();
}
Expand Down
1 change: 1 addition & 0 deletions src/firefox/types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,6 +60,7 @@ export interface FirefoxLaunchOptions {
acceptInsecureCerts?: boolean | undefined;
connectExisting?: boolean | undefined;
marionettePort?: number | undefined;
marionetteHost?: string | undefined;
env?: Record<string, string> | undefined;
logFile?: string | undefined;
/** Firefox preferences to set at startup via moz:firefoxOptions */
Expand Down
26 changes: 23 additions & 3 deletions src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,11 +98,11 @@ export async function getFirefox(): Promise<FirefoxDevTools> {
if (firefox) {
const isConnected = await firefox.isConnected();
if (!isConnected) {
log('Firefox connection lost - browser was closed or disconnected');
log('Firefox connection lost, reconnecting...');
resetFirefox();
throw new FirefoxDisconnectedError('Browser was closed');
} else {
return firefox;
}
return firefox;
}

// No existing instance - create new connection
Expand DownExpand Up@@ -142,6 +142,7 @@ export async function getFirefox(): Promise<FirefoxDevTools> {
acceptInsecureCerts: args.acceptInsecureCerts,
connectExisting: args.connectExisting,
marionettePort: args.marionettePort,
marionetteHost: args.marionetteHost,
env: envVars,
logFile: args.outputFile ?? undefined,
prefs,
Expand DownExpand Up@@ -358,6 +359,25 @@ async function main() {

log('Firefox DevTools MCP server running on stdio');
log('Ready to accept tool requests');

// Clean up the Marionette session so Firefox accepts new connections.
// Without this, the session stays locked after the MCP client disconnects.
const cleanup = async () => {
if (firefox) {
try {
await firefox.close();
} catch {
// ignore
}
}
await server.close();
process.exit(0);
};
process.on('SIGTERM', cleanup);
process.on('SIGINT', cleanup);
// StdioServerTransport does not fire onclose on stdin EOF.
process.stdin.on('end', cleanup);
process.stdin.on('close', cleanup);
}

// Only run main() if this file is executed directly (not imported)
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/cli.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,6 +110,11 @@ export const cliOptions = {
description: 'Marionette port to connect to when using --connect-existing (default: 2828)',
default: Number(process.env.MARIONETTE_PORT ?? '2828'),
},
marionetteHost: {
type: 'string',
description: 'Marionette host to connect to when using --connect-existing (default: 127.0.0.1). Also used as the BiDi WebSocket connect address when different from 127.0.0.1.',
default: process.env.MARIONETTE_HOST ?? '127.0.0.1',
},
env: {
type: 'array',
description:
Expand Down
117 changes: 102 additions & 15 deletions src/firefox/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,7 @@ import { spawn, type ChildProcess } from 'node:child_process';
import { mkdirSync, openSync, closeSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import WebSocket from 'ws';
import type { FirefoxLaunchOptions } from './types.js';
import { log, logDebug } from '../utils/logger.js';

Expand DownExpand Up@@ -129,21 +130,26 @@ class GeckodriverHttpDriver implements IDriver {
private baseUrl: string;
private sessionId: string;
private gdProcess: ChildProcess;
private webSocketUrl: string | null;
private bidiConnection: IBiDi | null = null;

constructor(baseUrl: string, sessionId: string, gdProcess: ChildProcess) {
constructor(baseUrl: string, sessionId: string, gdProcess: ChildProcess, webSocketUrl: string | null) {
this.baseUrl = baseUrl;
this.sessionId = sessionId;
this.gdProcess = gdProcess;
this.webSocketUrl = webSocketUrl;
}

static async connect(marionettePort: number): Promise<GeckodriverHttpDriver> {
static async connect(marionettePort: number, marionetteHost = '127.0.0.1'): Promise<GeckodriverHttpDriver> {
// Find geckodriver binary via selenium-manager
const path = await import('node:path');
const { execFileSync } = await import('node:child_process');

let geckodriverPath: string;
try {
// selenium-manager ships with selenium-webdriver and resolves/downloads geckodriver
// selenium-manager ships with selenium-webdriver and resolves/downloads geckodriver.
// Use --driver instead of --browser to skip downloading Firefox, which is
// already running externally in connect-existing mode.
const { createRequire } = await import('node:module');
const require = createRequire(import.meta.url);
const swPkg = require.resolve('selenium-webdriver/package.json');
Expand All@@ -157,7 +163,7 @@ class GeckodriverHttpDriver implements IDriver {
const ext = process.platform === 'win32' ? '.exe' : '';
const smBin = path.join(swDir, 'bin', platform, `selenium-manager${ext}`);
const result = JSON.parse(
execFileSync(smBin, ['--browser', 'firefox', '--output', 'json'], { encoding: 'utf-8' })
execFileSync(smBin, ['--driver', 'geckodriver', '--output', 'json'], { encoding: 'utf-8' })
);
geckodriverPath = result.result.driver_path;
} catch {
Expand All@@ -175,7 +181,7 @@ class GeckodriverHttpDriver implements IDriver {
// Use --port=0 to let the OS assign a free port atomically (geckodriver ≥0.34.0)
const gd = spawn(
geckodriverPath,
['--connect-existing', '--marionette-port', String(marionettePort), '--port', '0'],
['--connect-existing', '--marionette-host', marionetteHost, '--marionette-port', String(marionettePort), '--port', '0'],
{ stdio: ['ignore', 'pipe', 'pipe'] }
);

Expand DownExpand Up@@ -206,11 +212,11 @@ class GeckodriverHttpDriver implements IDriver {

const baseUrl = `http://127.0.0.1:${port}`;

// Create a WebDriver session
// Create a WebDriver session with BiDi opt-in
const resp = await fetch(`${baseUrl}/session`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ capabilities: { alwaysMatch: {} } }),
body: JSON.stringify({ capabilities: { alwaysMatch: { webSocketUrl: true } } }),
});
const json = (await resp.json()) as {
value: { sessionId: string; capabilities: Record<string, unknown> };
Expand All@@ -219,7 +225,21 @@ class GeckodriverHttpDriver implements IDriver {
throw new Error(`Failed to create session: ${JSON.stringify(json)}`);
}

return new GeckodriverHttpDriver(baseUrl, json.value.sessionId, gd);
let wsUrl = json.value.capabilities.webSocketUrl as string | undefined;
logDebug(`Session capabilities webSocketUrl: ${wsUrl ?? 'not present'}, marionetteHost: ${marionetteHost}`);
if (wsUrl && marionetteHost !== '127.0.0.1') {
// Rewrite the URL to connect through the remote host / tunnel.
const parsed = new URL(wsUrl);
parsed.hostname = marionetteHost;
wsUrl = parsed.toString();
}
if (wsUrl) {
logDebug(`BiDi WebSocket URL: ${wsUrl}`);
} else {
logDebug('BiDi WebSocket URL not available (Firefox may not support it or Remote Agent is not running)');
}

return new GeckodriverHttpDriver(baseUrl, json.value.sessionId, gd, wsUrl ?? null);
}

private async cmd(method: string, path: string, body?: unknown): Promise<unknown> {
Expand DownExpand Up@@ -422,6 +442,10 @@ class GeckodriverHttpDriver implements IDriver {
}

async quit(): Promise<void> {
if (this.bidiConnection) {
(this.bidiConnection.socket as unknown as WebSocket).close();
this.bidiConnection = null;
}
try {
await this.cmd('DELETE', '');
} catch {
Expand All@@ -430,13 +454,75 @@ class GeckodriverHttpDriver implements IDriver {
this.gdProcess.kill();
}

/** Kill the geckodriver process without closing Firefox */
kill(): void {
/** Kill the geckodriver process without closing Firefox.
* Deletes the session first so Marionette accepts new connections. */
async kill(): Promise<void> {
if (this.bidiConnection) {
(this.bidiConnection.socket as unknown as WebSocket).close();
this.bidiConnection = null;
}
try {
await this.cmd('DELETE', '');
} catch {
// ignore
}
this.gdProcess.kill();
}

getBidi(): Promise<IBiDi> {
throw new Error('BiDi not available in connect-existing mode');
/**
* Return a BiDi handle. Opens a WebSocket to Firefox's Remote Agent on
* first call, using the webSocketUrl returned in the session capabilities.
*/
async getBidi(): Promise<IBiDi> {
if (this.bidiConnection) return this.bidiConnection;
if (!this.webSocketUrl) {
throw new Error(
'BiDi is not available: no webSocketUrl in session capabilities. ' +
'Ensure Firefox was started with --remote-debugging-port.'
);
}

const ws = new WebSocket(this.webSocketUrl);
await new Promise<void>((resolve, reject) => {
ws.on('open', resolve);
ws.on('error', (e: any) => {
const msg = e?.message || e?.error?.message || e?.error || e?.type || JSON.stringify(e) || String(e);
reject(new Error(`BiDi WS to ${this.webSocketUrl}: ${msg}`));
});
});

let cmdId = 0;
const subscribe = async (event: string, contexts?: string[]): Promise<void> => {
const msg: Record<string, unknown> = {
id: ++cmdId,
method: 'session.subscribe',
params: { events: [event] },
};
if (contexts) msg.params = { events: [event], contexts };
ws.send(JSON.stringify(msg));
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error(`BiDi subscribe timeout for ${event}`)), 5000);
const onMsg = (data: WebSocket.Data) => {
try {
const payload = JSON.parse(data.toString());
if (payload.id === cmdId) {
clearTimeout(timeout);
ws.off('message', onMsg);
if (payload.error) {
reject(new Error(`BiDi subscribe error: ${payload.error}`));
} else {
resolve();
}
}
} catch { /* ignore parse errors from event messages */ }
};
ws.on('message', onMsg);
});
logDebug(`BiDi subscribed to ${event}`);
};

this.bidiConnection = { subscribe, socket: ws as unknown as IBiDiSocket } as any;
return this.bidiConnection;
}
}

Expand DownExpand Up@@ -503,7 +589,8 @@ export class FirefoxCore {
// We bypass selenium-webdriver because its BiDi auto-upgrade hangs
// when used with geckodriver's --connect-existing mode.
const port = this.options.marionettePort ?? 2828;
this.driver = await GeckodriverHttpDriver.connect(port);
const host = this.options.marionetteHost ?? '127.0.0.1';
this.driver = await GeckodriverHttpDriver.connect(port, host);
} else {
// Set up output file for capturing Firefox stdout/stderr
if (this.options.logFile) {
Expand DownExpand Up@@ -640,7 +727,7 @@ export class FirefoxCore {
*/
reset(): void {
if (this.driver && this.options.connectExisting && 'kill' in this.driver) {
(this.driver as { kill(): void }).kill();
(this.driver as { kill(): Promise<void> }).kill();
}
this.driver = null;
this.currentContextId = null;
Expand DownExpand Up@@ -762,7 +849,7 @@ export class FirefoxCore {
async close(): Promise<void> {
if (this.driver) {
if (this.options.connectExisting && 'kill' in this.driver) {
(this.driver as { kill(): void }).kill();
await (this.driver as { kill(): Promise<void> }).kill();
} else if ('quit' in this.driver) {
await (this.driver as { quit(): Promise<void> }).quit();
}
Expand Down
1 change: 1 addition & 0 deletions src/firefox/types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,6 +60,7 @@ export interface FirefoxLaunchOptions {
acceptInsecureCerts?: boolean | undefined;
connectExisting?: boolean | undefined;
marionettePort?: number | undefined;
marionetteHost?: string | undefined;
env?: Record<string, string> | undefined;
logFile?: string | undefined;
/** Firefox preferences to set at startup via moz:firefoxOptions */
Expand Down
26 changes: 23 additions & 3 deletions src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,11 +98,11 @@ export async function getFirefox(): Promise<FirefoxDevTools> {
if (firefox) {
const isConnected = await firefox.isConnected();
if (!isConnected) {
log('Firefox connection lost - browser was closed or disconnected');
log('Firefox connection lost, reconnecting...');
resetFirefox();
throw new FirefoxDisconnectedError('Browser was closed');
} else {
return firefox;
}
return firefox;
}

// No existing instance - create new connection
Expand DownExpand Up@@ -142,6 +142,7 @@ export async function getFirefox(): Promise<FirefoxDevTools> {
acceptInsecureCerts: args.acceptInsecureCerts,
connectExisting: args.connectExisting,
marionettePort: args.marionettePort,
marionetteHost: args.marionetteHost,
env: envVars,
logFile: args.outputFile ?? undefined,
prefs,
Expand DownExpand Up@@ -358,6 +359,25 @@ async function main() {

log('Firefox DevTools MCP server running on stdio');
log('Ready to accept tool requests');

// Clean up the Marionette session so Firefox accepts new connections.
// Without this, the session stays locked after the MCP client disconnects.
const cleanup = async () => {
if (firefox) {
try {
await firefox.close();
} catch {
// ignore
}
}
await server.close();
process.exit(0);
};
process.on('SIGTERM', cleanup);
process.on('SIGINT', cleanup);
// StdioServerTransport does not fire onclose on stdin EOF.
process.stdin.on('end', cleanup);
process.stdin.on('close', cleanup);
}

// Only run main() if this file is executed directly (not imported)
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/cli.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,6 +110,11 @@ export const cliOptions = {
description: 'Marionette port to connect to when using --connect-existing (default: 2828)',
default: Number(process.env.MARIONETTE_PORT ?? '2828'),
},
marionetteHost: {
type: 'string',
description: 'Marionette host to connect to when using --connect-existing (default: 127.0.0.1). Also used as the BiDi WebSocket connect address when different from 127.0.0.1.',
default: process.env.MARIONETTE_HOST ?? '127.0.0.1',
},
env: {
type: 'array',
description:
Expand Down
117 changes: 102 additions & 15 deletions src/firefox/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,7 @@ import { spawn, type ChildProcess } from 'node:child_process';
import { mkdirSync, openSync, closeSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import WebSocket from 'ws';
import type { FirefoxLaunchOptions } from './types.js';
import { log, logDebug } from '../utils/logger.js';

Expand DownExpand Up@@ -129,21 +130,26 @@ class GeckodriverHttpDriver implements IDriver {
private baseUrl: string;
private sessionId: string;
private gdProcess: ChildProcess;
private webSocketUrl: string | null;
private bidiConnection: IBiDi | null = null;

constructor(baseUrl: string, sessionId: string, gdProcess: ChildProcess) {
constructor(baseUrl: string, sessionId: string, gdProcess: ChildProcess, webSocketUrl: string | null) {
this.baseUrl = baseUrl;
this.sessionId = sessionId;
this.gdProcess = gdProcess;
this.webSocketUrl = webSocketUrl;
}

static async connect(marionettePort: number): Promise<GeckodriverHttpDriver> {
static async connect(marionettePort: number, marionetteHost = '127.0.0.1'): Promise<GeckodriverHttpDriver> {
// Find geckodriver binary via selenium-manager
const path = await import('node:path');
const { execFileSync } = await import('node:child_process');

let geckodriverPath: string;
try {
// selenium-manager ships with selenium-webdriver and resolves/downloads geckodriver
// selenium-manager ships with selenium-webdriver and resolves/downloads geckodriver.
// Use --driver instead of --browser to skip downloading Firefox, which is
// already running externally in connect-existing mode.
const { createRequire } = await import('node:module');
const require = createRequire(import.meta.url);
const swPkg = require.resolve('selenium-webdriver/package.json');
Expand All@@ -157,7 +163,7 @@ class GeckodriverHttpDriver implements IDriver {
const ext = process.platform === 'win32' ? '.exe' : '';
const smBin = path.join(swDir, 'bin', platform, `selenium-manager${ext}`);
const result = JSON.parse(
execFileSync(smBin, ['--browser', 'firefox', '--output', 'json'], { encoding: 'utf-8' })
execFileSync(smBin, ['--driver', 'geckodriver', '--output', 'json'], { encoding: 'utf-8' })
);
geckodriverPath = result.result.driver_path;
} catch {
Expand All@@ -175,7 +181,7 @@ class GeckodriverHttpDriver implements IDriver {
// Use --port=0 to let the OS assign a free port atomically (geckodriver ≥0.34.0)
const gd = spawn(
geckodriverPath,
['--connect-existing', '--marionette-port', String(marionettePort), '--port', '0'],
['--connect-existing', '--marionette-host', marionetteHost, '--marionette-port', String(marionettePort), '--port', '0'],
{ stdio: ['ignore', 'pipe', 'pipe'] }
);

Expand DownExpand Up@@ -206,11 +212,11 @@ class GeckodriverHttpDriver implements IDriver {

const baseUrl = `http://127.0.0.1:${port}`;

// Create a WebDriver session
// Create a WebDriver session with BiDi opt-in
const resp = await fetch(`${baseUrl}/session`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ capabilities: { alwaysMatch: {} } }),
body: JSON.stringify({ capabilities: { alwaysMatch: { webSocketUrl: true } } }),
});
const json = (await resp.json()) as {
value: { sessionId: string; capabilities: Record<string, unknown> };
Expand All@@ -219,7 +225,21 @@ class GeckodriverHttpDriver implements IDriver {
throw new Error(`Failed to create session: ${JSON.stringify(json)}`);
}

return new GeckodriverHttpDriver(baseUrl, json.value.sessionId, gd);
let wsUrl = json.value.capabilities.webSocketUrl as string | undefined;
logDebug(`Session capabilities webSocketUrl: ${wsUrl ?? 'not present'}, marionetteHost: ${marionetteHost}`);
if (wsUrl && marionetteHost !== '127.0.0.1') {
// Rewrite the URL to connect through the remote host / tunnel.
const parsed = new URL(wsUrl);
parsed.hostname = marionetteHost;
wsUrl = parsed.toString();
}
if (wsUrl) {
logDebug(`BiDi WebSocket URL: ${wsUrl}`);
} else {
logDebug('BiDi WebSocket URL not available (Firefox may not support it or Remote Agent is not running)');
}

return new GeckodriverHttpDriver(baseUrl, json.value.sessionId, gd, wsUrl ?? null);
}

private async cmd(method: string, path: string, body?: unknown): Promise<unknown> {
Expand DownExpand Up@@ -422,6 +442,10 @@ class GeckodriverHttpDriver implements IDriver {
}

async quit(): Promise<void> {
if (this.bidiConnection) {
(this.bidiConnection.socket as unknown as WebSocket).close();
this.bidiConnection = null;
}
try {
await this.cmd('DELETE', '');
} catch {
Expand All@@ -430,13 +454,75 @@ class GeckodriverHttpDriver implements IDriver {
this.gdProcess.kill();
}

/** Kill the geckodriver process without closing Firefox */
kill(): void {
/** Kill the geckodriver process without closing Firefox.
* Deletes the session first so Marionette accepts new connections. */
async kill(): Promise<void> {
if (this.bidiConnection) {
(this.bidiConnection.socket as unknown as WebSocket).close();
this.bidiConnection = null;
}
try {
await this.cmd('DELETE', '');
} catch {
// ignore
}
this.gdProcess.kill();
}

getBidi(): Promise<IBiDi> {
throw new Error('BiDi not available in connect-existing mode');
/**
* Return a BiDi handle. Opens a WebSocket to Firefox's Remote Agent on
* first call, using the webSocketUrl returned in the session capabilities.
*/
async getBidi(): Promise<IBiDi> {
if (this.bidiConnection) return this.bidiConnection;
if (!this.webSocketUrl) {
throw new Error(
'BiDi is not available: no webSocketUrl in session capabilities. ' +
'Ensure Firefox was started with --remote-debugging-port.'
);
}

const ws = new WebSocket(this.webSocketUrl);
await new Promise<void>((resolve, reject) => {
ws.on('open', resolve);
ws.on('error', (e: any) => {
const msg = e?.message || e?.error?.message || e?.error || e?.type || JSON.stringify(e) || String(e);
reject(new Error(`BiDi WS to ${this.webSocketUrl}: ${msg}`));
});
});

let cmdId = 0;
const subscribe = async (event: string, contexts?: string[]): Promise<void> => {
const msg: Record<string, unknown> = {
id: ++cmdId,
method: 'session.subscribe',
params: { events: [event] },
};
if (contexts) msg.params = { events: [event], contexts };
ws.send(JSON.stringify(msg));
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error(`BiDi subscribe timeout for ${event}`)), 5000);
const onMsg = (data: WebSocket.Data) => {
try {
const payload = JSON.parse(data.toString());
if (payload.id === cmdId) {
clearTimeout(timeout);
ws.off('message', onMsg);
if (payload.error) {
reject(new Error(`BiDi subscribe error: ${payload.error}`));
} else {
resolve();
}
}
} catch { /* ignore parse errors from event messages */ }
};
ws.on('message', onMsg);
});
logDebug(`BiDi subscribed to ${event}`);
};

this.bidiConnection = { subscribe, socket: ws as unknown as IBiDiSocket } as any;
return this.bidiConnection;
}
}

Expand DownExpand Up@@ -503,7 +589,8 @@ export class FirefoxCore {
// We bypass selenium-webdriver because its BiDi auto-upgrade hangs
// when used with geckodriver's --connect-existing mode.
const port = this.options.marionettePort ?? 2828;
this.driver = await GeckodriverHttpDriver.connect(port);
const host = this.options.marionetteHost ?? '127.0.0.1';
this.driver = await GeckodriverHttpDriver.connect(port, host);
} else {
// Set up output file for capturing Firefox stdout/stderr
if (this.options.logFile) {
Expand DownExpand Up@@ -640,7 +727,7 @@ export class FirefoxCore {
*/
reset(): void {
if (this.driver && this.options.connectExisting && 'kill' in this.driver) {
(this.driver as { kill(): void }).kill();
(this.driver as { kill(): Promise<void> }).kill();
}
this.driver = null;
this.currentContextId = null;
Expand DownExpand Up@@ -762,7 +849,7 @@ export class FirefoxCore {
async close(): Promise<void> {
if (this.driver) {
if (this.options.connectExisting && 'kill' in this.driver) {
(this.driver as { kill(): void }).kill();
await (this.driver as { kill(): Promise<void> }).kill();
} else if ('quit' in this.driver) {
await (this.driver as { quit(): Promise<void> }).quit();
}
Expand Down
1 change: 1 addition & 0 deletions src/firefox/types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,6 +60,7 @@ export interface FirefoxLaunchOptions {
acceptInsecureCerts?: boolean | undefined;
connectExisting?: boolean | undefined;
marionettePort?: number | undefined;
marionetteHost?: string | undefined;
env?: Record<string, string> | undefined;
logFile?: string | undefined;
/** Firefox preferences to set at startup via moz:firefoxOptions */
Expand Down
26 changes: 23 additions & 3 deletions src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,11 +98,11 @@ export async function getFirefox(): Promise<FirefoxDevTools> {
if (firefox) {
const isConnected = await firefox.isConnected();
if (!isConnected) {
log('Firefox connection lost - browser was closed or disconnected');
log('Firefox connection lost, reconnecting...');
resetFirefox();
throw new FirefoxDisconnectedError('Browser was closed');
} else {
return firefox;
}
return firefox;
}

// No existing instance - create new connection
Expand DownExpand Up@@ -142,6 +142,7 @@ export async function getFirefox(): Promise<FirefoxDevTools> {
acceptInsecureCerts: args.acceptInsecureCerts,
connectExisting: args.connectExisting,
marionettePort: args.marionettePort,
marionetteHost: args.marionetteHost,
env: envVars,
logFile: args.outputFile ?? undefined,
prefs,
Expand DownExpand Up@@ -358,6 +359,25 @@ async function main() {

log('Firefox DevTools MCP server running on stdio');
log('Ready to accept tool requests');

// Clean up the Marionette session so Firefox accepts new connections.
// Without this, the session stays locked after the MCP client disconnects.
const cleanup = async () => {
if (firefox) {
try {
await firefox.close();
} catch {
// ignore
}
}
await server.close();
process.exit(0);
};
process.on('SIGTERM', cleanup);
process.on('SIGINT', cleanup);
// StdioServerTransport does not fire onclose on stdin EOF.
process.stdin.on('end', cleanup);
process.stdin.on('close', cleanup);
}

// Only run main() if this file is executed directly (not imported)
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/cli.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,6 +110,11 @@ export const cliOptions = {
description: 'Marionette port to connect to when using --connect-existing (default: 2828)',
default: Number(process.env.MARIONETTE_PORT ?? '2828'),
},
marionetteHost: {
type: 'string',
description: 'Marionette host to connect to when using --connect-existing (default: 127.0.0.1). Also used as the BiDi WebSocket connect address when different from 127.0.0.1.',
default: process.env.MARIONETTE_HOST ?? '127.0.0.1',
},
env: {
type: 'array',
description:
Expand Down
117 changes: 102 additions & 15 deletions src/firefox/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,7 @@ import { spawn, type ChildProcess } from 'node:child_process';
import { mkdirSync, openSync, closeSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import WebSocket from 'ws';
import type { FirefoxLaunchOptions } from './types.js';
import { log, logDebug } from '../utils/logger.js';

Expand DownExpand Up@@ -129,21 +130,26 @@ class GeckodriverHttpDriver implements IDriver {
private baseUrl: string;
private sessionId: string;
private gdProcess: ChildProcess;
private webSocketUrl: string | null;
private bidiConnection: IBiDi | null = null;

constructor(baseUrl: string, sessionId: string, gdProcess: ChildProcess) {
constructor(baseUrl: string, sessionId: string, gdProcess: ChildProcess, webSocketUrl: string | null) {
this.baseUrl = baseUrl;
this.sessionId = sessionId;
this.gdProcess = gdProcess;
this.webSocketUrl = webSocketUrl;
}

static async connect(marionettePort: number): Promise<GeckodriverHttpDriver> {
static async connect(marionettePort: number, marionetteHost = '127.0.0.1'): Promise<GeckodriverHttpDriver> {
// Find geckodriver binary via selenium-manager
const path = await import('node:path');
const { execFileSync } = await import('node:child_process');

let geckodriverPath: string;
try {
// selenium-manager ships with selenium-webdriver and resolves/downloads geckodriver
// selenium-manager ships with selenium-webdriver and resolves/downloads geckodriver.
// Use --driver instead of --browser to skip downloading Firefox, which is
// already running externally in connect-existing mode.
const { createRequire } = await import('node:module');
const require = createRequire(import.meta.url);
const swPkg = require.resolve('selenium-webdriver/package.json');
Expand All@@ -157,7 +163,7 @@ class GeckodriverHttpDriver implements IDriver {
const ext = process.platform === 'win32' ? '.exe' : '';
const smBin = path.join(swDir, 'bin', platform, `selenium-manager${ext}`);
const result = JSON.parse(
execFileSync(smBin, ['--browser', 'firefox', '--output', 'json'], { encoding: 'utf-8' })
execFileSync(smBin, ['--driver', 'geckodriver', '--output', 'json'], { encoding: 'utf-8' })
);
geckodriverPath = result.result.driver_path;
} catch {
Expand All@@ -175,7 +181,7 @@ class GeckodriverHttpDriver implements IDriver {
// Use --port=0 to let the OS assign a free port atomically (geckodriver ≥0.34.0)
const gd = spawn(
geckodriverPath,
['--connect-existing', '--marionette-port', String(marionettePort), '--port', '0'],
['--connect-existing', '--marionette-host', marionetteHost, '--marionette-port', String(marionettePort), '--port', '0'],
{ stdio: ['ignore', 'pipe', 'pipe'] }
);

Expand DownExpand Up@@ -206,11 +212,11 @@ class GeckodriverHttpDriver implements IDriver {

const baseUrl = `http://127.0.0.1:${port}`;

// Create a WebDriver session
// Create a WebDriver session with BiDi opt-in
const resp = await fetch(`${baseUrl}/session`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ capabilities: { alwaysMatch: {} } }),
body: JSON.stringify({ capabilities: { alwaysMatch: { webSocketUrl: true } } }),
});
const json = (await resp.json()) as {
value: { sessionId: string; capabilities: Record<string, unknown> };
Expand All@@ -219,7 +225,21 @@ class GeckodriverHttpDriver implements IDriver {
throw new Error(`Failed to create session: ${JSON.stringify(json)}`);
}

return new GeckodriverHttpDriver(baseUrl, json.value.sessionId, gd);
let wsUrl = json.value.capabilities.webSocketUrl as string | undefined;
logDebug(`Session capabilities webSocketUrl: ${wsUrl ?? 'not present'}, marionetteHost: ${marionetteHost}`);
if (wsUrl && marionetteHost !== '127.0.0.1') {
// Rewrite the URL to connect through the remote host / tunnel.
const parsed = new URL(wsUrl);
parsed.hostname = marionetteHost;
wsUrl = parsed.toString();
}
if (wsUrl) {
logDebug(`BiDi WebSocket URL: ${wsUrl}`);
} else {
logDebug('BiDi WebSocket URL not available (Firefox may not support it or Remote Agent is not running)');
}

return new GeckodriverHttpDriver(baseUrl, json.value.sessionId, gd, wsUrl ?? null);
}

private async cmd(method: string, path: string, body?: unknown): Promise<unknown> {
Expand DownExpand Up@@ -422,6 +442,10 @@ class GeckodriverHttpDriver implements IDriver {
}

async quit(): Promise<void> {
if (this.bidiConnection) {
(this.bidiConnection.socket as unknown as WebSocket).close();
this.bidiConnection = null;
}
try {
await this.cmd('DELETE', '');
} catch {
Expand All@@ -430,13 +454,75 @@ class GeckodriverHttpDriver implements IDriver {
this.gdProcess.kill();
}

/** Kill the geckodriver process without closing Firefox */
kill(): void {
/** Kill the geckodriver process without closing Firefox.
* Deletes the session first so Marionette accepts new connections. */
async kill(): Promise<void> {
if (this.bidiConnection) {
(this.bidiConnection.socket as unknown as WebSocket).close();
this.bidiConnection = null;
}
try {
await this.cmd('DELETE', '');
} catch {
// ignore
}
this.gdProcess.kill();
}

getBidi(): Promise<IBiDi> {
throw new Error('BiDi not available in connect-existing mode');
/**
* Return a BiDi handle. Opens a WebSocket to Firefox's Remote Agent on
* first call, using the webSocketUrl returned in the session capabilities.
*/
async getBidi(): Promise<IBiDi> {
if (this.bidiConnection) return this.bidiConnection;
if (!this.webSocketUrl) {
throw new Error(
'BiDi is not available: no webSocketUrl in session capabilities. ' +
'Ensure Firefox was started with --remote-debugging-port.'
);
}

const ws = new WebSocket(this.webSocketUrl);
await new Promise<void>((resolve, reject) => {
ws.on('open', resolve);
ws.on('error', (e: any) => {
const msg = e?.message || e?.error?.message || e?.error || e?.type || JSON.stringify(e) || String(e);
reject(new Error(`BiDi WS to ${this.webSocketUrl}: ${msg}`));
});
});

let cmdId = 0;
const subscribe = async (event: string, contexts?: string[]): Promise<void> => {
const msg: Record<string, unknown> = {
id: ++cmdId,
method: 'session.subscribe',
params: { events: [event] },
};
if (contexts) msg.params = { events: [event], contexts };
ws.send(JSON.stringify(msg));
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error(`BiDi subscribe timeout for ${event}`)), 5000);
const onMsg = (data: WebSocket.Data) => {
try {
const payload = JSON.parse(data.toString());
if (payload.id === cmdId) {
clearTimeout(timeout);
ws.off('message', onMsg);
if (payload.error) {
reject(new Error(`BiDi subscribe error: ${payload.error}`));
} else {
resolve();
}
}
} catch { /* ignore parse errors from event messages */ }
};
ws.on('message', onMsg);
});
logDebug(`BiDi subscribed to ${event}`);
};

this.bidiConnection = { subscribe, socket: ws as unknown as IBiDiSocket } as any;
return this.bidiConnection;
}
}

Expand DownExpand Up@@ -503,7 +589,8 @@ export class FirefoxCore {
// We bypass selenium-webdriver because its BiDi auto-upgrade hangs
// when used with geckodriver's --connect-existing mode.
const port = this.options.marionettePort ?? 2828;
this.driver = await GeckodriverHttpDriver.connect(port);
const host = this.options.marionetteHost ?? '127.0.0.1';
this.driver = await GeckodriverHttpDriver.connect(port, host);
} else {
// Set up output file for capturing Firefox stdout/stderr
if (this.options.logFile) {
Expand DownExpand Up@@ -640,7 +727,7 @@ export class FirefoxCore {
*/
reset(): void {
if (this.driver && this.options.connectExisting && 'kill' in this.driver) {
(this.driver as { kill(): void }).kill();
(this.driver as { kill(): Promise<void> }).kill();
}
this.driver = null;
this.currentContextId = null;
Expand DownExpand Up@@ -762,7 +849,7 @@ export class FirefoxCore {
async close(): Promise<void> {
if (this.driver) {
if (this.options.connectExisting && 'kill' in this.driver) {
(this.driver as { kill(): void }).kill();
await (this.driver as { kill(): Promise<void> }).kill();
} else if ('quit' in this.driver) {
await (this.driver as { quit(): Promise<void> }).quit();
}
Expand Down
1 change: 1 addition & 0 deletions src/firefox/types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,6 +60,7 @@ export interface FirefoxLaunchOptions {
acceptInsecureCerts?: boolean | undefined;
connectExisting?: boolean | undefined;
marionettePort?: number | undefined;
marionetteHost?: string | undefined;
env?: Record<string, string> | undefined;
logFile?: string | undefined;
/** Firefox preferences to set at startup via moz:firefoxOptions */
Expand Down
26 changes: 23 additions & 3 deletions src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,11 +98,11 @@ export async function getFirefox(): Promise<FirefoxDevTools> {
if (firefox) {
const isConnected = await firefox.isConnected();
if (!isConnected) {
log('Firefox connection lost - browser was closed or disconnected');
log('Firefox connection lost, reconnecting...');
resetFirefox();
throw new FirefoxDisconnectedError('Browser was closed');
} else {
return firefox;
}
return firefox;
}

// No existing instance - create new connection
Expand DownExpand Up@@ -142,6 +142,7 @@ export async function getFirefox(): Promise<FirefoxDevTools> {
acceptInsecureCerts: args.acceptInsecureCerts,
connectExisting: args.connectExisting,
marionettePort: args.marionettePort,
marionetteHost: args.marionetteHost,
env: envVars,
logFile: args.outputFile ?? undefined,
prefs,
Expand DownExpand Up@@ -358,6 +359,25 @@ async function main() {

log('Firefox DevTools MCP server running on stdio');
log('Ready to accept tool requests');

// Clean up the Marionette session so Firefox accepts new connections.
// Without this, the session stays locked after the MCP client disconnects.
const cleanup = async () => {
if (firefox) {
try {
await firefox.close();
} catch {
// ignore
}
}
await server.close();
process.exit(0);
};
process.on('SIGTERM', cleanup);
process.on('SIGINT', cleanup);
// StdioServerTransport does not fire onclose on stdin EOF.
process.stdin.on('end', cleanup);
process.stdin.on('close', cleanup);
}

// Only run main() if this file is executed directly (not imported)
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/cli.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,6 +110,11 @@ export const cliOptions = {
description: 'Marionette port to connect to when using --connect-existing (default: 2828)',
default: Number(process.env.MARIONETTE_PORT ?? '2828'),
},
marionetteHost: {
type: 'string',
description: 'Marionette host to connect to when using --connect-existing (default: 127.0.0.1). Also used as the BiDi WebSocket connect address when different from 127.0.0.1.',
default: process.env.MARIONETTE_HOST ?? '127.0.0.1',
},
env: {
type: 'array',
description:
Expand Down
117 changes: 102 additions & 15 deletions src/firefox/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,7 @@ import { spawn, type ChildProcess } from 'node:child_process';
import { mkdirSync, openSync, closeSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import WebSocket from 'ws';
import type { FirefoxLaunchOptions } from './types.js';
import { log, logDebug } from '../utils/logger.js';

Expand DownExpand Up@@ -129,21 +130,26 @@ class GeckodriverHttpDriver implements IDriver {
private baseUrl: string;
private sessionId: string;
private gdProcess: ChildProcess;
private webSocketUrl: string | null;
private bidiConnection: IBiDi | null = null;

constructor(baseUrl: string, sessionId: string, gdProcess: ChildProcess) {
constructor(baseUrl: string, sessionId: string, gdProcess: ChildProcess, webSocketUrl: string | null) {
this.baseUrl = baseUrl;
this.sessionId = sessionId;
this.gdProcess = gdProcess;
this.webSocketUrl = webSocketUrl;
}

static async connect(marionettePort: number): Promise<GeckodriverHttpDriver> {
static async connect(marionettePort: number, marionetteHost = '127.0.0.1'): Promise<GeckodriverHttpDriver> {
// Find geckodriver binary via selenium-manager
const path = await import('node:path');
const { execFileSync } = await import('node:child_process');

let geckodriverPath: string;
try {
// selenium-manager ships with selenium-webdriver and resolves/downloads geckodriver
// selenium-manager ships with selenium-webdriver and resolves/downloads geckodriver.
// Use --driver instead of --browser to skip downloading Firefox, which is
// already running externally in connect-existing mode.
const { createRequire } = await import('node:module');
const require = createRequire(import.meta.url);
const swPkg = require.resolve('selenium-webdriver/package.json');
Expand All@@ -157,7 +163,7 @@ class GeckodriverHttpDriver implements IDriver {
const ext = process.platform === 'win32' ? '.exe' : '';
const smBin = path.join(swDir, 'bin', platform, `selenium-manager${ext}`);
const result = JSON.parse(
execFileSync(smBin, ['--browser', 'firefox', '--output', 'json'], { encoding: 'utf-8' })
execFileSync(smBin, ['--driver', 'geckodriver', '--output', 'json'], { encoding: 'utf-8' })
);
geckodriverPath = result.result.driver_path;
} catch {
Expand All@@ -175,7 +181,7 @@ class GeckodriverHttpDriver implements IDriver {
// Use --port=0 to let the OS assign a free port atomically (geckodriver ≥0.34.0)
const gd = spawn(
geckodriverPath,
['--connect-existing', '--marionette-port', String(marionettePort), '--port', '0'],
['--connect-existing', '--marionette-host', marionetteHost, '--marionette-port', String(marionettePort), '--port', '0'],
{ stdio: ['ignore', 'pipe', 'pipe'] }
);

Expand DownExpand Up@@ -206,11 +212,11 @@ class GeckodriverHttpDriver implements IDriver {

const baseUrl = `http://127.0.0.1:${port}`;

// Create a WebDriver session
// Create a WebDriver session with BiDi opt-in
const resp = await fetch(`${baseUrl}/session`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ capabilities: { alwaysMatch: {} } }),
body: JSON.stringify({ capabilities: { alwaysMatch: { webSocketUrl: true } } }),
});
const json = (await resp.json()) as {
value: { sessionId: string; capabilities: Record<string, unknown> };
Expand All@@ -219,7 +225,21 @@ class GeckodriverHttpDriver implements IDriver {
throw new Error(`Failed to create session: ${JSON.stringify(json)}`);
}

return new GeckodriverHttpDriver(baseUrl, json.value.sessionId, gd);
let wsUrl = json.value.capabilities.webSocketUrl as string | undefined;
logDebug(`Session capabilities webSocketUrl: ${wsUrl ?? 'not present'}, marionetteHost: ${marionetteHost}`);
if (wsUrl && marionetteHost !== '127.0.0.1') {
// Rewrite the URL to connect through the remote host / tunnel.
const parsed = new URL(wsUrl);
parsed.hostname = marionetteHost;
wsUrl = parsed.toString();
}
if (wsUrl) {
logDebug(`BiDi WebSocket URL: ${wsUrl}`);
} else {
logDebug('BiDi WebSocket URL not available (Firefox may not support it or Remote Agent is not running)');
}

return new GeckodriverHttpDriver(baseUrl, json.value.sessionId, gd, wsUrl ?? null);
}

private async cmd(method: string, path: string, body?: unknown): Promise<unknown> {
Expand DownExpand Up@@ -422,6 +442,10 @@ class GeckodriverHttpDriver implements IDriver {
}

async quit(): Promise<void> {
if (this.bidiConnection) {
(this.bidiConnection.socket as unknown as WebSocket).close();
this.bidiConnection = null;
}
try {
await this.cmd('DELETE', '');
} catch {
Expand All@@ -430,13 +454,75 @@ class GeckodriverHttpDriver implements IDriver {
this.gdProcess.kill();
}

/** Kill the geckodriver process without closing Firefox */
kill(): void {
/** Kill the geckodriver process without closing Firefox.
* Deletes the session first so Marionette accepts new connections. */
async kill(): Promise<void> {
if (this.bidiConnection) {
(this.bidiConnection.socket as unknown as WebSocket).close();
this.bidiConnection = null;
}
try {
await this.cmd('DELETE', '');
} catch {
// ignore
}
this.gdProcess.kill();
}

getBidi(): Promise<IBiDi> {
throw new Error('BiDi not available in connect-existing mode');
/**
* Return a BiDi handle. Opens a WebSocket to Firefox's Remote Agent on
* first call, using the webSocketUrl returned in the session capabilities.
*/
async getBidi(): Promise<IBiDi> {
if (this.bidiConnection) return this.bidiConnection;
if (!this.webSocketUrl) {
throw new Error(
'BiDi is not available: no webSocketUrl in session capabilities. ' +
'Ensure Firefox was started with --remote-debugging-port.'
);
}

const ws = new WebSocket(this.webSocketUrl);
await new Promise<void>((resolve, reject) => {
ws.on('open', resolve);
ws.on('error', (e: any) => {
const msg = e?.message || e?.error?.message || e?.error || e?.type || JSON.stringify(e) || String(e);
reject(new Error(`BiDi WS to ${this.webSocketUrl}: ${msg}`));
});
});

let cmdId = 0;
const subscribe = async (event: string, contexts?: string[]): Promise<void> => {
const msg: Record<string, unknown> = {
id: ++cmdId,
method: 'session.subscribe',
params: { events: [event] },
};
if (contexts) msg.params = { events: [event], contexts };
ws.send(JSON.stringify(msg));
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error(`BiDi subscribe timeout for ${event}`)), 5000);
const onMsg = (data: WebSocket.Data) => {
try {
const payload = JSON.parse(data.toString());
if (payload.id === cmdId) {
clearTimeout(timeout);
ws.off('message', onMsg);
if (payload.error) {
reject(new Error(`BiDi subscribe error: ${payload.error}`));
} else {
resolve();
}
}
} catch { /* ignore parse errors from event messages */ }
};
ws.on('message', onMsg);
});
logDebug(`BiDi subscribed to ${event}`);
};

this.bidiConnection = { subscribe, socket: ws as unknown as IBiDiSocket } as any;
return this.bidiConnection;
}
}

Expand DownExpand Up@@ -503,7 +589,8 @@ export class FirefoxCore {
// We bypass selenium-webdriver because its BiDi auto-upgrade hangs
// when used with geckodriver's --connect-existing mode.
const port = this.options.marionettePort ?? 2828;
this.driver = await GeckodriverHttpDriver.connect(port);
const host = this.options.marionetteHost ?? '127.0.0.1';
this.driver = await GeckodriverHttpDriver.connect(port, host);
} else {
// Set up output file for capturing Firefox stdout/stderr
if (this.options.logFile) {
Expand DownExpand Up@@ -640,7 +727,7 @@ export class FirefoxCore {
*/
reset(): void {
if (this.driver && this.options.connectExisting && 'kill' in this.driver) {
(this.driver as { kill(): void }).kill();
(this.driver as { kill(): Promise<void> }).kill();
}
this.driver = null;
this.currentContextId = null;
Expand DownExpand Up@@ -762,7 +849,7 @@ export class FirefoxCore {
async close(): Promise<void> {
if (this.driver) {
if (this.options.connectExisting && 'kill' in this.driver) {
(this.driver as { kill(): void }).kill();
await (this.driver as { kill(): Promise<void> }).kill();
} else if ('quit' in this.driver) {
await (this.driver as { quit(): Promise<void> }).quit();
}
Expand Down
1 change: 1 addition & 0 deletions src/firefox/types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,6 +60,7 @@ export interface FirefoxLaunchOptions {
acceptInsecureCerts?: boolean | undefined;
connectExisting?: boolean | undefined;
marionettePort?: number | undefined;
marionetteHost?: string | undefined;
env?: Record<string, string> | undefined;
logFile?: string | undefined;
/** Firefox preferences to set at startup via moz:firefoxOptions */
Expand Down
26 changes: 23 additions & 3 deletions src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,11 +98,11 @@ export async function getFirefox(): Promise<FirefoxDevTools> {
if (firefox) {
const isConnected = await firefox.isConnected();
if (!isConnected) {
log('Firefox connection lost - browser was closed or disconnected');
log('Firefox connection lost, reconnecting...');
resetFirefox();
throw new FirefoxDisconnectedError('Browser was closed');
} else {
return firefox;
}
return firefox;
}

// No existing instance - create new connection
Expand DownExpand Up@@ -142,6 +142,7 @@ export async function getFirefox(): Promise<FirefoxDevTools> {
acceptInsecureCerts: args.acceptInsecureCerts,
connectExisting: args.connectExisting,
marionettePort: args.marionettePort,
marionetteHost: args.marionetteHost,
env: envVars,
logFile: args.outputFile ?? undefined,
prefs,
Expand DownExpand Up@@ -358,6 +359,25 @@ async function main() {

log('Firefox DevTools MCP server running on stdio');
log('Ready to accept tool requests');

// Clean up the Marionette session so Firefox accepts new connections.
// Without this, the session stays locked after the MCP client disconnects.
const cleanup = async () => {
if (firefox) {
try {
await firefox.close();
} catch {
// ignore
}
}
await server.close();
process.exit(0);
};
process.on('SIGTERM', cleanup);
process.on('SIGINT', cleanup);
// StdioServerTransport does not fire onclose on stdin EOF.
process.stdin.on('end', cleanup);
process.stdin.on('close', cleanup);
}

// Only run main() if this file is executed directly (not imported)
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/cli.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,6 +110,11 @@ export const cliOptions = {
description: 'Marionette port to connect to when using --connect-existing (default: 2828)',
default: Number(process.env.MARIONETTE_PORT ?? '2828'),
},
marionetteHost: {
type: 'string',
description: 'Marionette host to connect to when using --connect-existing (default: 127.0.0.1). Also used as the BiDi WebSocket connect address when different from 127.0.0.1.',
default: process.env.MARIONETTE_HOST ?? '127.0.0.1',
},
env: {
type: 'array',
description:
Expand Down
117 changes: 102 additions & 15 deletions src/firefox/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,7 @@ import { spawn, type ChildProcess } from 'node:child_process';
import { mkdirSync, openSync, closeSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import WebSocket from 'ws';
import type { FirefoxLaunchOptions } from './types.js';
import { log, logDebug } from '../utils/logger.js';

Expand DownExpand Up@@ -129,21 +130,26 @@ class GeckodriverHttpDriver implements IDriver {
private baseUrl: string;
private sessionId: string;
private gdProcess: ChildProcess;
private webSocketUrl: string | null;
private bidiConnection: IBiDi | null = null;

constructor(baseUrl: string, sessionId: string, gdProcess: ChildProcess) {
constructor(baseUrl: string, sessionId: string, gdProcess: ChildProcess, webSocketUrl: string | null) {
this.baseUrl = baseUrl;
this.sessionId = sessionId;
this.gdProcess = gdProcess;
this.webSocketUrl = webSocketUrl;
}

static async connect(marionettePort: number): Promise<GeckodriverHttpDriver> {
static async connect(marionettePort: number, marionetteHost = '127.0.0.1'): Promise<GeckodriverHttpDriver> {
// Find geckodriver binary via selenium-manager
const path = await import('node:path');
const { execFileSync } = await import('node:child_process');

let geckodriverPath: string;
try {
// selenium-manager ships with selenium-webdriver and resolves/downloads geckodriver
// selenium-manager ships with selenium-webdriver and resolves/downloads geckodriver.
// Use --driver instead of --browser to skip downloading Firefox, which is
// already running externally in connect-existing mode.
const { createRequire } = await import('node:module');
const require = createRequire(import.meta.url);
const swPkg = require.resolve('selenium-webdriver/package.json');
Expand All@@ -157,7 +163,7 @@ class GeckodriverHttpDriver implements IDriver {
const ext = process.platform === 'win32' ? '.exe' : '';
const smBin = path.join(swDir, 'bin', platform, `selenium-manager${ext}`);
const result = JSON.parse(
execFileSync(smBin, ['--browser', 'firefox', '--output', 'json'], { encoding: 'utf-8' })
execFileSync(smBin, ['--driver', 'geckodriver', '--output', 'json'], { encoding: 'utf-8' })
);
geckodriverPath = result.result.driver_path;
} catch {
Expand All@@ -175,7 +181,7 @@ class GeckodriverHttpDriver implements IDriver {
// Use --port=0 to let the OS assign a free port atomically (geckodriver ≥0.34.0)
const gd = spawn(
geckodriverPath,
['--connect-existing', '--marionette-port', String(marionettePort), '--port', '0'],
['--connect-existing', '--marionette-host', marionetteHost, '--marionette-port', String(marionettePort), '--port', '0'],
{ stdio: ['ignore', 'pipe', 'pipe'] }
);

Expand DownExpand Up@@ -206,11 +212,11 @@ class GeckodriverHttpDriver implements IDriver {

const baseUrl = `http://127.0.0.1:${port}`;

// Create a WebDriver session
// Create a WebDriver session with BiDi opt-in
const resp = await fetch(`${baseUrl}/session`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ capabilities: { alwaysMatch: {} } }),
body: JSON.stringify({ capabilities: { alwaysMatch: { webSocketUrl: true } } }),
});
const json = (await resp.json()) as {
value: { sessionId: string; capabilities: Record<string, unknown> };
Expand All@@ -219,7 +225,21 @@ class GeckodriverHttpDriver implements IDriver {
throw new Error(`Failed to create session: ${JSON.stringify(json)}`);
}

return new GeckodriverHttpDriver(baseUrl, json.value.sessionId, gd);
let wsUrl = json.value.capabilities.webSocketUrl as string | undefined;
logDebug(`Session capabilities webSocketUrl: ${wsUrl ?? 'not present'}, marionetteHost: ${marionetteHost}`);
if (wsUrl && marionetteHost !== '127.0.0.1') {
// Rewrite the URL to connect through the remote host / tunnel.
const parsed = new URL(wsUrl);
parsed.hostname = marionetteHost;
wsUrl = parsed.toString();
}
if (wsUrl) {
logDebug(`BiDi WebSocket URL: ${wsUrl}`);
} else {
logDebug('BiDi WebSocket URL not available (Firefox may not support it or Remote Agent is not running)');
}

return new GeckodriverHttpDriver(baseUrl, json.value.sessionId, gd, wsUrl ?? null);
}

private async cmd(method: string, path: string, body?: unknown): Promise<unknown> {
Expand DownExpand Up@@ -422,6 +442,10 @@ class GeckodriverHttpDriver implements IDriver {
}

async quit(): Promise<void> {
if (this.bidiConnection) {
(this.bidiConnection.socket as unknown as WebSocket).close();
this.bidiConnection = null;
}
try {
await this.cmd('DELETE', '');
} catch {
Expand All@@ -430,13 +454,75 @@ class GeckodriverHttpDriver implements IDriver {
this.gdProcess.kill();
}

/** Kill the geckodriver process without closing Firefox */
kill(): void {
/** Kill the geckodriver process without closing Firefox.
* Deletes the session first so Marionette accepts new connections. */
async kill(): Promise<void> {
if (this.bidiConnection) {
(this.bidiConnection.socket as unknown as WebSocket).close();
this.bidiConnection = null;
}
try {
await this.cmd('DELETE', '');
} catch {
// ignore
}
this.gdProcess.kill();
}

getBidi(): Promise<IBiDi> {
throw new Error('BiDi not available in connect-existing mode');
/**
* Return a BiDi handle. Opens a WebSocket to Firefox's Remote Agent on
* first call, using the webSocketUrl returned in the session capabilities.
*/
async getBidi(): Promise<IBiDi> {
if (this.bidiConnection) return this.bidiConnection;
if (!this.webSocketUrl) {
throw new Error(
'BiDi is not available: no webSocketUrl in session capabilities. ' +
'Ensure Firefox was started with --remote-debugging-port.'
);
}

const ws = new WebSocket(this.webSocketUrl);
await new Promise<void>((resolve, reject) => {
ws.on('open', resolve);
ws.on('error', (e: any) => {
const msg = e?.message || e?.error?.message || e?.error || e?.type || JSON.stringify(e) || String(e);
reject(new Error(`BiDi WS to ${this.webSocketUrl}: ${msg}`));
});
});

let cmdId = 0;
const subscribe = async (event: string, contexts?: string[]): Promise<void> => {
const msg: Record<string, unknown> = {
id: ++cmdId,
method: 'session.subscribe',
params: { events: [event] },
};
if (contexts) msg.params = { events: [event], contexts };
ws.send(JSON.stringify(msg));
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error(`BiDi subscribe timeout for ${event}`)), 5000);
const onMsg = (data: WebSocket.Data) => {
try {
const payload = JSON.parse(data.toString());
if (payload.id === cmdId) {
clearTimeout(timeout);
ws.off('message', onMsg);
if (payload.error) {
reject(new Error(`BiDi subscribe error: ${payload.error}`));
} else {
resolve();
}
}
} catch { /* ignore parse errors from event messages */ }
};
ws.on('message', onMsg);
});
logDebug(`BiDi subscribed to ${event}`);
};

this.bidiConnection = { subscribe, socket: ws as unknown as IBiDiSocket } as any;
return this.bidiConnection;
}
}

Expand DownExpand Up@@ -503,7 +589,8 @@ export class FirefoxCore {
// We bypass selenium-webdriver because its BiDi auto-upgrade hangs
// when used with geckodriver's --connect-existing mode.
const port = this.options.marionettePort ?? 2828;
this.driver = await GeckodriverHttpDriver.connect(port);
const host = this.options.marionetteHost ?? '127.0.0.1';
this.driver = await GeckodriverHttpDriver.connect(port, host);
} else {
// Set up output file for capturing Firefox stdout/stderr
if (this.options.logFile) {
Expand DownExpand Up@@ -640,7 +727,7 @@ export class FirefoxCore {
*/
reset(): void {
if (this.driver && this.options.connectExisting && 'kill' in this.driver) {
(this.driver as { kill(): void }).kill();
(this.driver as { kill(): Promise<void> }).kill();
}
this.driver = null;
this.currentContextId = null;
Expand DownExpand Up@@ -762,7 +849,7 @@ export class FirefoxCore {
async close(): Promise<void> {
if (this.driver) {
if (this.options.connectExisting && 'kill' in this.driver) {
(this.driver as { kill(): void }).kill();
await (this.driver as { kill(): Promise<void> }).kill();
} else if ('quit' in this.driver) {
await (this.driver as { quit(): Promise<void> }).quit();
}
Expand Down
1 change: 1 addition & 0 deletions src/firefox/types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,6 +60,7 @@ export interface FirefoxLaunchOptions {
acceptInsecureCerts?: boolean | undefined;
connectExisting?: boolean | undefined;
marionettePort?: number | undefined;
marionetteHost?: string | undefined;
env?: Record<string, string> | undefined;
logFile?: string | undefined;
/** Firefox preferences to set at startup via moz:firefoxOptions */
Expand Down
26 changes: 23 additions & 3 deletions src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,11 +98,11 @@ export async function getFirefox(): Promise<FirefoxDevTools> {
if (firefox) {
const isConnected = await firefox.isConnected();
if (!isConnected) {
log('Firefox connection lost - browser was closed or disconnected');
log('Firefox connection lost, reconnecting...');
resetFirefox();
throw new FirefoxDisconnectedError('Browser was closed');
} else {
return firefox;
}
return firefox;
}

// No existing instance - create new connection
Expand DownExpand Up@@ -142,6 +142,7 @@ export async function getFirefox(): Promise<FirefoxDevTools> {
acceptInsecureCerts: args.acceptInsecureCerts,
connectExisting: args.connectExisting,
marionettePort: args.marionettePort,
marionetteHost: args.marionetteHost,
env: envVars,
logFile: args.outputFile ?? undefined,
prefs,
Expand DownExpand Up@@ -358,6 +359,25 @@ async function main() {

log('Firefox DevTools MCP server running on stdio');
log('Ready to accept tool requests');

// Clean up the Marionette session so Firefox accepts new connections.
// Without this, the session stays locked after the MCP client disconnects.
const cleanup = async () => {
if (firefox) {
try {
await firefox.close();
} catch {
// ignore
}
}
await server.close();
process.exit(0);
};
process.on('SIGTERM', cleanup);
process.on('SIGINT', cleanup);
// StdioServerTransport does not fire onclose on stdin EOF.
process.stdin.on('end', cleanup);
process.stdin.on('close', cleanup);
}

// Only run main() if this file is executed directly (not imported)
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/cli.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,6 +110,11 @@ export const cliOptions = {
description: 'Marionette port to connect to when using --connect-existing (default: 2828)',
default: Number(process.env.MARIONETTE_PORT ?? '2828'),
},
marionetteHost: {
type: 'string',
description: 'Marionette host to connect to when using --connect-existing (default: 127.0.0.1). Also used as the BiDi WebSocket connect address when different from 127.0.0.1.',
default: process.env.MARIONETTE_HOST ?? '127.0.0.1',
},
env: {
type: 'array',
description:
Expand Down
117 changes: 102 additions & 15 deletions src/firefox/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,7 @@ import { spawn, type ChildProcess } from 'node:child_process';
import { mkdirSync, openSync, closeSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import WebSocket from 'ws';
import type { FirefoxLaunchOptions } from './types.js';
import { log, logDebug } from '../utils/logger.js';

Expand DownExpand Up@@ -129,21 +130,26 @@ class GeckodriverHttpDriver implements IDriver {
private baseUrl: string;
private sessionId: string;
private gdProcess: ChildProcess;
private webSocketUrl: string | null;
private bidiConnection: IBiDi | null = null;

constructor(baseUrl: string, sessionId: string, gdProcess: ChildProcess) {
constructor(baseUrl: string, sessionId: string, gdProcess: ChildProcess, webSocketUrl: string | null) {
this.baseUrl = baseUrl;
this.sessionId = sessionId;
this.gdProcess = gdProcess;
this.webSocketUrl = webSocketUrl;
}

static async connect(marionettePort: number): Promise<GeckodriverHttpDriver> {
static async connect(marionettePort: number, marionetteHost = '127.0.0.1'): Promise<GeckodriverHttpDriver> {
// Find geckodriver binary via selenium-manager
const path = await import('node:path');
const { execFileSync } = await import('node:child_process');

let geckodriverPath: string;
try {
// selenium-manager ships with selenium-webdriver and resolves/downloads geckodriver
// selenium-manager ships with selenium-webdriver and resolves/downloads geckodriver.
// Use --driver instead of --browser to skip downloading Firefox, which is
// already running externally in connect-existing mode.
const { createRequire } = await import('node:module');
const require = createRequire(import.meta.url);
const swPkg = require.resolve('selenium-webdriver/package.json');
Expand All@@ -157,7 +163,7 @@ class GeckodriverHttpDriver implements IDriver {
const ext = process.platform === 'win32' ? '.exe' : '';
const smBin = path.join(swDir, 'bin', platform, `selenium-manager${ext}`);
const result = JSON.parse(
execFileSync(smBin, ['--browser', 'firefox', '--output', 'json'], { encoding: 'utf-8' })
execFileSync(smBin, ['--driver', 'geckodriver', '--output', 'json'], { encoding: 'utf-8' })
);
geckodriverPath = result.result.driver_path;
} catch {
Expand All@@ -175,7 +181,7 @@ class GeckodriverHttpDriver implements IDriver {
// Use --port=0 to let the OS assign a free port atomically (geckodriver ≥0.34.0)
const gd = spawn(
geckodriverPath,
['--connect-existing', '--marionette-port', String(marionettePort), '--port', '0'],
['--connect-existing', '--marionette-host', marionetteHost, '--marionette-port', String(marionettePort), '--port', '0'],
{ stdio: ['ignore', 'pipe', 'pipe'] }
);

Expand DownExpand Up@@ -206,11 +212,11 @@ class GeckodriverHttpDriver implements IDriver {

const baseUrl = `http://127.0.0.1:${port}`;

// Create a WebDriver session
// Create a WebDriver session with BiDi opt-in
const resp = await fetch(`${baseUrl}/session`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ capabilities: { alwaysMatch: {} } }),
body: JSON.stringify({ capabilities: { alwaysMatch: { webSocketUrl: true } } }),
});
const json = (await resp.json()) as {
value: { sessionId: string; capabilities: Record<string, unknown> };
Expand All@@ -219,7 +225,21 @@ class GeckodriverHttpDriver implements IDriver {
throw new Error(`Failed to create session: ${JSON.stringify(json)}`);
}

return new GeckodriverHttpDriver(baseUrl, json.value.sessionId, gd);
let wsUrl = json.value.capabilities.webSocketUrl as string | undefined;
logDebug(`Session capabilities webSocketUrl: ${wsUrl ?? 'not present'}, marionetteHost: ${marionetteHost}`);
if (wsUrl && marionetteHost !== '127.0.0.1') {
// Rewrite the URL to connect through the remote host / tunnel.
const parsed = new URL(wsUrl);
parsed.hostname = marionetteHost;
wsUrl = parsed.toString();
}
if (wsUrl) {
logDebug(`BiDi WebSocket URL: ${wsUrl}`);
} else {
logDebug('BiDi WebSocket URL not available (Firefox may not support it or Remote Agent is not running)');
}

return new GeckodriverHttpDriver(baseUrl, json.value.sessionId, gd, wsUrl ?? null);
}

private async cmd(method: string, path: string, body?: unknown): Promise<unknown> {
Expand DownExpand Up@@ -422,6 +442,10 @@ class GeckodriverHttpDriver implements IDriver {
}

async quit(): Promise<void> {
if (this.bidiConnection) {
(this.bidiConnection.socket as unknown as WebSocket).close();
this.bidiConnection = null;
}
try {
await this.cmd('DELETE', '');
} catch {
Expand All@@ -430,13 +454,75 @@ class GeckodriverHttpDriver implements IDriver {
this.gdProcess.kill();
}

/** Kill the geckodriver process without closing Firefox */
kill(): void {
/** Kill the geckodriver process without closing Firefox.
* Deletes the session first so Marionette accepts new connections. */
async kill(): Promise<void> {
if (this.bidiConnection) {
(this.bidiConnection.socket as unknown as WebSocket).close();
this.bidiConnection = null;
}
try {
await this.cmd('DELETE', '');
} catch {
// ignore
}
this.gdProcess.kill();
}

getBidi(): Promise<IBiDi> {
throw new Error('BiDi not available in connect-existing mode');
/**
* Return a BiDi handle. Opens a WebSocket to Firefox's Remote Agent on
* first call, using the webSocketUrl returned in the session capabilities.
*/
async getBidi(): Promise<IBiDi> {
if (this.bidiConnection) return this.bidiConnection;
if (!this.webSocketUrl) {
throw new Error(
'BiDi is not available: no webSocketUrl in session capabilities. ' +
'Ensure Firefox was started with --remote-debugging-port.'
);
}

const ws = new WebSocket(this.webSocketUrl);
await new Promise<void>((resolve, reject) => {
ws.on('open', resolve);
ws.on('error', (e: any) => {
const msg = e?.message || e?.error?.message || e?.error || e?.type || JSON.stringify(e) || String(e);
reject(new Error(`BiDi WS to ${this.webSocketUrl}: ${msg}`));
});
});

let cmdId = 0;
const subscribe = async (event: string, contexts?: string[]): Promise<void> => {
const msg: Record<string, unknown> = {
id: ++cmdId,
method: 'session.subscribe',
params: { events: [event] },
};
if (contexts) msg.params = { events: [event], contexts };
ws.send(JSON.stringify(msg));
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error(`BiDi subscribe timeout for ${event}`)), 5000);
const onMsg = (data: WebSocket.Data) => {
try {
const payload = JSON.parse(data.toString());
if (payload.id === cmdId) {
clearTimeout(timeout);
ws.off('message', onMsg);
if (payload.error) {
reject(new Error(`BiDi subscribe error: ${payload.error}`));
} else {
resolve();
}
}
} catch { /* ignore parse errors from event messages */ }
};
ws.on('message', onMsg);
});
logDebug(`BiDi subscribed to ${event}`);
};

this.bidiConnection = { subscribe, socket: ws as unknown as IBiDiSocket } as any;
return this.bidiConnection;
}
}

Expand DownExpand Up@@ -503,7 +589,8 @@ export class FirefoxCore {
// We bypass selenium-webdriver because its BiDi auto-upgrade hangs
// when used with geckodriver's --connect-existing mode.
const port = this.options.marionettePort ?? 2828;
this.driver = await GeckodriverHttpDriver.connect(port);
const host = this.options.marionetteHost ?? '127.0.0.1';
this.driver = await GeckodriverHttpDriver.connect(port, host);
} else {
// Set up output file for capturing Firefox stdout/stderr
if (this.options.logFile) {
Expand DownExpand Up@@ -640,7 +727,7 @@ export class FirefoxCore {
*/
reset(): void {
if (this.driver && this.options.connectExisting && 'kill' in this.driver) {
(this.driver as { kill(): void }).kill();
(this.driver as { kill(): Promise<void> }).kill();
}
this.driver = null;
this.currentContextId = null;
Expand DownExpand Up@@ -762,7 +849,7 @@ export class FirefoxCore {
async close(): Promise<void> {
if (this.driver) {
if (this.options.connectExisting && 'kill' in this.driver) {
(this.driver as { kill(): void }).kill();
await (this.driver as { kill(): Promise<void> }).kill();
} else if ('quit' in this.driver) {
await (this.driver as { quit(): Promise<void> }).quit();
}
Expand Down
1 change: 1 addition & 0 deletions src/firefox/types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,6 +60,7 @@ export interface FirefoxLaunchOptions {
acceptInsecureCerts?: boolean | undefined;
connectExisting?: boolean | undefined;
marionettePort?: number | undefined;
marionetteHost?: string | undefined;
env?: Record<string, string> | undefined;
logFile?: string | undefined;
/** Firefox preferences to set at startup via moz:firefoxOptions */
Expand Down
26 changes: 23 additions & 3 deletions src/index.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -98,11 +98,11 @@ export async function getFirefox(): Promise<FirefoxDevTools> {
if (firefox) {
const isConnected = await firefox.isConnected();
if (!isConnected) {
log('Firefox connection lost - browser was closed or disconnected');
log('Firefox connection lost, reconnecting...');
resetFirefox();
throw new FirefoxDisconnectedError('Browser was closed');
} else {
return firefox;
}
return firefox;
}

// No existing instance - create new connection
Expand DownExpand Up@@ -142,6 +142,7 @@ export async function getFirefox(): Promise<FirefoxDevTools> {
acceptInsecureCerts: args.acceptInsecureCerts,
connectExisting: args.connectExisting,
marionettePort: args.marionettePort,
marionetteHost: args.marionetteHost,
env: envVars,
logFile: args.outputFile ?? undefined,
prefs,
Expand DownExpand Up@@ -358,6 +359,25 @@ async function main() {

log('Firefox DevTools MCP server running on stdio');
log('Ready to accept tool requests');

// Clean up the Marionette session so Firefox accepts new connections.
// Without this, the session stays locked after the MCP client disconnects.
const cleanup = async () => {
if (firefox) {
try {
await firefox.close();
} catch {
// ignore
}
}
await server.close();
process.exit(0);
};
process.on('SIGTERM', cleanup);
process.on('SIGINT', cleanup);
// StdioServerTransport does not fire onclose on stdin EOF.
process.stdin.on('end', cleanup);
process.stdin.on('close', cleanup);
}

// Only run main() if this file is executed directly (not imported)
Expand Down