Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
fix(mcp): give each isolated client its own idle timer (#43527)
Pavel Feldman1332f2f99942
diff --git a/docs/src/getting-started-mcp.md b/docs/src/getting-started-mcp.mdindex cd911db6d1..25ff4be397 100644--- a/docs/src/getting-started-mcp.md+++ b/docs/src/getting-started-mcp.md@@ -204,7 +204,7 @@ A page that keeps animating or rendering costs CPU for as long as the browser isWhen no tool call has completed for that long, the browser is closed, headed or not, the same way as if you had closed it by hand. The next tool call launches a new browser, so the agent navigates again. The timer never fires while a tool call is running.-- With `--isolated`, cookies and storage kept in memory are lost on an idle close. Use the persistent profile or `--storage-state` to keep them.+- With `--isolated`, cookies and storage kept in memory are lost on an idle close. Use the persistent profile or `--storage-state` to keep them. Each client has its own timer: the context of an idle client is closed while other clients keep working, and the browser is closed once no client has a context.- With `--cdp-endpoint` or `--extension`, the browser is not owned by the server, so there is no default timeout, and an explicit one only disconnects from it, leaving its pages open. With `--extension`, the next tool call goes through the connect flow again.- With `--shared-browser-context`, the timer spans all clients: a client that is idle while others keep working keeps its tabs and state, and the shared browser is closed only once every client has been idle for the timeout.diff --git a/packages/playwright-core/src/tools/mcp/browserFactory.ts b/packages/playwright-core/src/tools/mcp/browserFactory.tsindex 6efd9ba4ef..e1c8e9246a 100644--- a/packages/playwright-core/src/tools/mcp/browserFactory.ts+++ b/packages/playwright-core/src/tools/mcp/browserFactory.ts@@ -52,14 +52,16 @@ export type BindOptions = {export async function createBrowserWithInfo(config: FullConfig, clientInfo: ClientInfo, cliOptions: CLIOptions, bindOptions: BindOptions): Promise<BrowserWithInfo> {const info = await createBrowser(config, clientInfo, cliOptions, bindOptions);- const idleTimeout = config.timeouts?.idle ?? (info.ownership === 'own' && config.browser.launchOptions.headless ? defaultIdleTimeout : undefined);- if (idleTimeout) {- info.idleTimer = new IdleTimer(idleTimeout, () => info.browser.close().catch(() => {}));- info.browser.once('disconnected', () => info.idleTimer?.dispose());- }+ info.idleTimer = createIdleTimer(config, info.ownership, () => info.browser.close().catch(() => {}));+ info.browser.once('disconnected', () => info.idleTimer?.dispose());return info;}+export function createIdleTimer(config: FullConfig, ownership: BrowserWithInfo['ownership'], onIdle: () => void): IdleTimer | undefined {+ const idleTimeout = config.timeouts?.idle ?? (ownership === 'own' && config.browser.launchOptions.headless ? defaultIdleTimeout : undefined);+ return idleTimeout ? new IdleTimer(idleTimeout, onIdle) : undefined;+}+async function createBrowser(config: FullConfig, clientInfo: ClientInfo, cliOptions: CLIOptions, bindOptions: BindOptions): Promise<BrowserWithInfo> {if (config.browser.remoteEndpoint)return await createRemoteBrowser(config);diff --git a/packages/playwright-core/src/tools/mcp/program.ts b/packages/playwright-core/src/tools/mcp/program.tsindex f3be1a74a8..fdf3212463 100644--- a/packages/playwright-core/src/tools/mcp/program.ts+++ b/packages/playwright-core/src/tools/mcp/program.ts@@ -18,7 +18,7 @@ import { Option as ProgramOption } from 'commander';import * as mcpServer from '../utils/mcp/server';import { commaSeparatedList, defaultCodegenLanguage, dotenvFileLoader, enumParser, headerParser, numberParser, resolutionParser, resolveCLIConfigForMCP, semicolonSeparatedList } from './config';import { setupExitWatchdog } from './watchdog';-import { connectToBrowserEndpoint, createBrowserWithInfo } from './browserFactory';+import { connectToBrowserEndpoint, createBrowserWithInfo, createIdleTimer } from './browserFactory';import { BrowserBackend } from '../backend/browserBackend';import { filteredTools } from '../backend/tools';import { testDebug } from './log';@@ -160,9 +160,14 @@ export function decorateMCPCommand(command: Command) {throw error;}+ // Each isolated client owns a context in the shared browser, so it has its own idle timer.+ // Otherwise an idle client keeps its context open while other clients are active.+ const clientIdleTimer = shared && config.browser.isolated ? createIdleTimer(config, shared.ownership, () => browserContext.close().catch(() => { })) : undefined;+return new BrowserBackend(config, browserContext, tools, {- idleTimer: info.idleTimer,+ idleTimer: clientIdleTimer ?? info.idleTimer,dispose: async () => {+ clientIdleTimer?.dispose();clientCount--;const last = !shared || !clientCount;if (last && sharedBrowserPromise === promise)diff --git a/tests/mcp/http.spec.ts b/tests/mcp/http.spec.tsindex 3bda5da828..83a58593b3 100644--- a/tests/mcp/http.spec.ts+++ b/tests/mcp/http.spec.ts@@ -575,6 +575,45 @@ test('http transport shared context: one idle timer across clients', async ({ se});});+test('http transport isolated: one idle timer per client', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright-mcp/issues/1795' } }, async ({ serverEndpoint, server }) => {+ const { url, stderr } = await serverEndpoint({ args: ['--isolated', '--idle-timeout=1500'] });+ const client1 = await connectClient(url, 'test1');+ await client1.client.callTool({+ name: 'browser_navigate',+ arguments: { url: server.HELLO_WORLD },+ });++ // The idle client loses its context while the other client keeps the browser busy.+ const client2 = await connectClient(url, 'test2');+ await keepBusy(client2.client, 3000);+ expect(formatLog(stderr())).toEqual({+ 'create browser (isolated)': 1,+ 'connect to shared browser': 2,+ 'create http session': 2,+ 'create context': 2,+ 'close context': 1,+ });++ expect(await client1.client.callTool({+ name: 'browser_navigate',+ arguments: { url: server.HELLO_WORLD },+ })).toHaveResponse({+ snapshot: expect.stringContaining(`Hello, world!`),+ });++ await client1.close();+ await client2.close();+ await expect.poll(() => formatLog(stderr())).toEqual({+ 'create browser (isolated)': 1,+ 'connect to shared browser': 3,+ 'create http session': 2,+ 'delete http session': 2,+ 'create context': 3,+ 'close context': 2,+ 'close browser': 1,+ });+});+test('http transport (default)', async ({ serverEndpoint }) => {const { url } = await serverEndpoint();const transport = new StreamableHTTPClientTransport(url);