Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

chore(mcp): own the idle timer in the browser factory (#42678)

Yury Semikhatsky6750deccd13b
diff --git a/docs/src/getting-started-mcp.md b/docs/src/getting-started-mcp.md
index 11a51bc62f..63c5ae04e6 100644
--- a/docs/src/getting-started-mcp.md
+++ b/docs/src/getting-started-mcp.md
@@ -212,10 +212,10 @@ The browser is launched by the first tool call and stays open until the MCP serv
}
```
-When no tool call has completed for that long, the browser is closed the same way `browser_close` closes it, headed or not. The next tool call relaunches the browser, and its response starts with a note about the idle close, so the agent checks the open tabs or navigates again instead of assuming the old page is still open. The timer never fires while a tool call is running.
+When 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 `--cdp-endpoint` or `--extension`, the browser is not owned by the server, so an idle close only disconnects from it: the pages stay open, and the note tells the agent to check the open tabs instead. With `--extension`, the next tool call goes through the connect flow again.
+- With `--cdp-endpoint` or `--extension`, the browser is not owned by the server, so an idle close only disconnects from it and its pages stay 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.
### Configuration file
diff --git a/packages/playwright-core/src/tools/backend/browserBackend.ts b/packages/playwright-core/src/tools/backend/browserBackend.ts
index 40b1d4855b..1c7b3dbeeb 100644
--- a/packages/playwright-core/src/tools/backend/browserBackend.ts
+++ b/packages/playwright-core/src/tools/backend/browserBackend.ts
@@ -22,6 +22,7 @@ import { Context } from './context';
import { Response } from './response';
import { SessionLog } from './sessionLog';
import type { ContextConfig } from './context';
+import type { IdleTimer } from './idleTimer';
import type * as playwright from '../../..';
import type { Tool } from './tool';
import type * as mcpServer from '../utils/mcp/server';
@@ -29,14 +30,12 @@ import type { ClientInfo, ServerBackend } from '../utils/mcp/server';
const backendDebug = debug('pw:mcp:backend');
-export type BrowserBackendCallbacks = {
+export type BrowserBackendOptions = {
dispose?: () => Promise<void>;
- // Bracket every tool call, for example to drive an idle timer.
- callStarted?: () => void;
- callFinished?: () => void;
+ idleTimer?: IdleTimer;
};
-export class BrowserBackend extends EventEmitter<{ disconnected: [notice?: string] }> implements ServerBackend {
+export class BrowserBackend extends EventEmitter<{ disconnected: [] }> implements ServerBackend {
private _tools: Tool[];
private _context: Context | undefined;
private _sessionLog: SessionLog | undefined;
@@ -44,16 +43,25 @@ export class BrowserBackend extends EventEmitter<{ disconnected: [notice?: strin
private _disconnected = false;
private _disposed = false;
private _browserContext: playwright.BrowserContext;
- private _callbacks: BrowserBackendCallbacks;
+ private _disposeCallback: (() => Promise<void>) | undefined;
+ private _idleTimer: IdleTimer | undefined;
- constructor(config: ContextConfig, browserContext: playwright.BrowserContext, tools: Tool[], callbacks: BrowserBackendCallbacks = {}) {
+ constructor(config: ContextConfig, browserContext: playwright.BrowserContext, tools: Tool[], options: BrowserBackendOptions = {}) {
super();
this._config = config;
this._tools = tools;
this._browserContext = browserContext;
- this._callbacks = callbacks;
- this._browserContext.once('close', () => this.markDisconnected());
- this._browserContext.browser()?.once('disconnected', () => this.markDisconnected());
+ this._disposeCallback = options.dispose;
+ this._idleTimer = options.idleTimer;
+ const markDisconnected = () => {
+ if (this._disconnected)
+ return;
+ backendDebug('browser disconnected');
+ this._disconnected = true;
+ this.emit('disconnected');
+ };
+ this._browserContext.once('close', markDisconnected);
+ this._browserContext.browser()?.once('disconnected', markDisconnected);
}
async initialize(clientInfo: ClientInfo): Promise<void> {
@@ -65,29 +73,20 @@ export class BrowserBackend extends EventEmitter<{ disconnected: [notice?: strin
});
}
- // Detaches the backend from its session, the notice is delivered with the session's next response.
- markDisconnected(notice?: string) {
- if (this._disconnected)
- return;
- backendDebug('browser disconnected');
- this._disconnected = true;
- this.emit('disconnected', notice);
- }
-
async dispose() {
if (this._disposed)
return;
this._disposed = true;
await this._context?.dispose().catch(e => debug('pw:tools:error')(e));
- await this._callbacks.dispose?.().catch(e => debug('pw:tools:error')(e));
+ await this._disposeCallback?.().catch(e => debug('pw:tools:error')(e));
}
async callTool(name: string, rawArguments: mcpServer.CallToolRequest['params']['arguments'] & { _meta?: Record<string, any> } = {}, signal?: AbortSignal): Promise<mcpServer.CallToolResult> {
- this._callbacks.callStarted?.();
+ this._idleTimer?.callStarted();
try {
return await this._callTool(name, rawArguments, signal);
} finally {
- this._callbacks.callFinished?.();
+ this._idleTimer?.callFinished();
}
}
diff --git a/packages/playwright-core/src/tools/backend/idleTimer.ts b/packages/playwright-core/src/tools/backend/idleTimer.ts
new file mode 100644
index 0000000000..4bde60d601
--- /dev/null
+++ b/packages/playwright-core/src/tools/backend/idleTimer.ts
@@ -0,0 +1,42 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export class IdleTimer {
+ private _timeout: number;
+ private _onIdle: () => void;
+ private _running = 0;
+ private _timer: NodeJS.Timeout | undefined;
+
+ constructor(timeout: number, onIdle: () => void) {
+ this._timeout = timeout;
+ this._onIdle = onIdle;
+ }
+
+ callStarted() {
+ ++this._running;
+ this.dispose();
+ }
+
+ callFinished() {
+ if (!--this._running)
+ this._timer = setTimeout(this._onIdle, this._timeout).unref();
+ }
+
+ dispose() {
+ clearTimeout(this._timer);
+ this._timer = undefined;
+ }
+}
diff --git a/packages/playwright-core/src/tools/mcp/browserFactory.ts b/packages/playwright-core/src/tools/mcp/browserFactory.ts
index c03b4caa21..3783eea93a 100644
--- a/packages/playwright-core/src/tools/mcp/browserFactory.ts
+++ b/packages/playwright-core/src/tools/mcp/browserFactory.ts
@@ -22,6 +22,7 @@ import { playwright } from '../../inprocess';
import { defaultCacheDirectory } from '../../server/registry/index';
import { testDebug } from './log';
import { outputDir } from '../backend/context';
+import { IdleTimer } from '../backend/idleTimer';
import { createExtensionBrowser } from './extensionContextFactory';
import { connectToBrowserAcrossVersions, descriptorEndpoint } from '../utils/connect';
import { serverRegistry } from '../../serverRegistry';
@@ -41,6 +42,7 @@ export type BrowserWithInfo = {
browserInfo: BrowserInfo,
endpoint: string,
ownership: 'attached' | 'own',
+ idleTimer?: IdleTimer,
};
export type BindOptions = {
@@ -49,6 +51,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;
+ if (idleTimeout) {
+ info.idleTimer = new IdleTimer(idleTimeout, () => info.browser.close().catch(() => {}));
+ info.browser.once('disconnected', () => info.idleTimer?.dispose());
+ }
+ return info;
+}
+
+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.ts
index 258920a300..811ecd6021 100644
--- a/packages/playwright-core/src/tools/mcp/program.ts
+++ b/packages/playwright-core/src/tools/mcp/program.ts
@@ -102,14 +102,6 @@ export function decorateMCPCommand(command: Command) {
let sharedBrowserPromise: Promise<BrowserWithInfo> | undefined;
let clientCount = 0;
const clientNameCounters = new Map<string, number>();
- const idleTimeout = config.timeouts?.idle;
- // A shared context has one idle timer for all clients, it closes the browser once none of them has been active for the timeout.
- const backends = new Set<BrowserBackend>();
- let sharedIdleNotice: string | undefined;
- const sharedIdleTimer = config.sharedBrowserContext && idleTimeout ? new IdleTimer(idleTimeout, () => {
- for (const backend of backends)
- backend.markDisconnected(sharedIdleNotice);
- }) : undefined;
const factory: mcpServer.ServerBackendFactory = {
name: 'Playwright',
@@ -165,19 +157,9 @@ export function decorateMCPCommand(command: Command) {
throw error;
}
- // Pages outlive the connection when the browser is not ours, for example over --cdp-endpoint.
- const notice = idleTimeout ? idleNotice(idleTimeout, !config.browser.isolated && info.ownership === 'attached') : undefined;
- if (shared)
- sharedIdleNotice = notice;
- const ownIdleTimer = idleTimeout && !sharedIdleTimer ? new IdleTimer(idleTimeout, () => backend.markDisconnected(notice)) : undefined;
- const idleTimer = sharedIdleTimer ?? ownIdleTimer;
-
- const backend: BrowserBackend = new BrowserBackend(config, browserContext, tools, {
- callStarted: () => idleTimer?.callStarted(),
- callFinished: () => idleTimer?.callFinished(),
+ return new BrowserBackend(config, browserContext, tools, {
+ idleTimer: info.idleTimer,
dispose: async () => {
- backends.delete(backend);
- ownIdleTimer?.dispose();
clientCount--;
const last = !shared || !clientCount;
if (last && sharedBrowserPromise === promise)
@@ -200,44 +182,8 @@ export function decorateMCPCommand(command: Command) {
await shared?.browser.close().catch(() => { });
},
});
- backends.add(backend);
- return backend;
},
};
await mcpServer.start(factory, config.server);
});
}
-
-function idleNotice(timeout: number, pagesSurvive: boolean): string {
- if (pagesSurvive)
- return `Note: the browser connection was closed after ${timeout}ms of inactivity and has been reestablished. Check the open tabs before interacting with the page.`;
- return `Note: the browser was closed after ${timeout}ms of inactivity and has been relaunched. Pages from before the idle close are gone, navigate again before interacting with the page.`;
-}
-
-// Fires once no tool call has been running for the timeout, the next call re-arms it.
-class IdleTimer {
- private _timeout: number;
- private _onIdle: () => void;
- private _running = 0;
- private _timer: NodeJS.Timeout | undefined;
-
- constructor(timeout: number, onIdle: () => void) {
- this._timeout = timeout;
- this._onIdle = onIdle;
- }
-
- callStarted() {
- ++this._running;
- this.dispose();
- }
-
- callFinished() {
- if (!--this._running)
- this._timer = setTimeout(this._onIdle, this._timeout).unref();
- }
-
- dispose() {
- clearTimeout(this._timer);
- this._timer = undefined;
- }
-}
diff --git a/packages/playwright-core/src/tools/utils/mcp/server.ts b/packages/playwright-core/src/tools/utils/mcp/server.ts
index 9c9307f657..4799818189 100644
--- a/packages/playwright-core/src/tools/utils/mcp/server.ts
+++ b/packages/playwright-core/src/tools/utils/mcp/server.ts
@@ -42,8 +42,7 @@ export interface ServerBackend {
initialize?(clientInfo: ClientInfo): Promise<void>;
callTool(name: string, args: CallToolRequest['params']['arguments'], signal: AbortSignal): Promise<CallToolResult>;
dispose?(): Promise<void>;
- // The notice, if any, is prepended to the next tool response, for example after an idle close.
- once(event: 'disconnected', listener: (notice?: string) => void): void;
+ once(event: 'disconnected', listener: () => void): void;
}
export type ServerBackendFactory = {
@@ -73,27 +72,20 @@ export function createServer(name: string, version: string, factory: ServerBacke
let backendPromise: Promise<ServerBackend> | undefined;
let heartbeatStarted = false;
- let disposing: Promise<void> | undefined;
- let pendingNotice: string | undefined;
const onClose = () => backendPromise?.then(b => b.dispose?.()).catch(serverDebug);
addServerListener(server, 'close', onClose);
server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
serverDebug('callTool', request);
- let notice: string | undefined;
- let result: CallToolResult;
try {
if (!backendPromise) {
- // Let the previous backend finish closing before its replacement launches.
- await disposing;
const promise = initializeServer(server, factory, transportInitialized).then(backend => {
- backend.once('disconnected', disconnectNotice => {
+ backend.once('disconnected', () => {
if (backendPromise === promise)
backendPromise = undefined;
- pendingNotice ??= disconnectNotice;
- disposing = backend.dispose?.().catch(serverDebug);
+ void backend.dispose?.().catch(serverDebug);
});
if (runHeartbeat && !heartbeatStarted) {
heartbeatStarted = true;
@@ -109,19 +101,16 @@ export function createServer(name: string, version: string, factory: ServerBacke
}
const backend = await backendPromise;
- // Delivered once, by whichever call first reaches the replacement backend.
- notice = pendingNotice;
- pendingNotice = undefined;
- result = await backend.callTool(request.params.name, request.params.arguments || {}, extra.signal);
+ const toolResult = await backend.callTool(request.params.name, request.params.arguments || {}, extra.signal);
+ const mergedResult = mergeTextParts(toolResult);
+ serverDebugResponse('callResult', mergedResult);
+ return mergedResult;
} catch (error) {
- result = {
+ return {
content: [{ type: 'text', text: '### Error\n' + String(error) }],
isError: true,
};
}
- const mergedResult = mergeTextParts(prependText(result, notice));
- serverDebugResponse('callResult', mergedResult);
- return mergedResult;
});
return server;
}
@@ -238,12 +227,6 @@ export function allRootPaths(roots: Root[]): string[] {
return paths;
}
-function prependText(result: CallToolResult, text: string | undefined): CallToolResult {
- if (!text)
- return result;
- return { ...result, content: [{ type: 'text', text }, ...result.content] };
-}
-
function mergeTextParts(result: CallToolResult): CallToolResult {
const content: CallToolResult['content'] = [];
const testParts: string[] = [];
diff --git a/tests/mcp/http.spec.ts b/tests/mcp/http.spec.ts
index c68d122dc9..9d6e39fe70 100644
--- a/tests/mcp/http.spec.ts
+++ b/tests/mcp/http.spec.ts
@@ -517,7 +517,6 @@ async function connectClient(url: URL, name: string) {
return { client, close };
}
-// Keeps calling tools for the given time, so an idle timer never fires.
async function keepBusy(client: Client, ms: number) {
const deadline = Date.now() + ms;
while (Date.now() < deadline) {
@@ -534,7 +533,6 @@ test('http transport shared context: one idle timer across clients', async ({ se
arguments: { url: server.HELLO_WORLD },
});
- // While the second client keeps working past the timeout, the idle client keeps its state.
const client2 = await connectClient(url, 'test2');
await keepBusy(client2.client, 1200);
expect(formatLog(stderr())).toEqual({
@@ -550,9 +548,7 @@ test('http transport shared context: one idle timer across clients', async ({ se
expect(response).toHaveResponse({
inlineSnapshot: expect.stringContaining(`Hello, world!`),
});
- expect(response.content[0].text).not.toContain('inactivity');
- // Once every client has been idle for the timeout, the shared browser closes.
await expect.poll(() => formatLog(stderr())).toEqual({
'create browser (persistent)': 1,
'connect to shared browser': 2,
@@ -562,24 +558,14 @@ test('http transport shared context: one idle timer across clients', async ({ se
'close browser': 1,
});
- // Each client relaunches on its next call and is told once.
for (const { client } of [client1, client2]) {
- const response = await client.callTool({
+ expect(await client.callTool({
name: 'browser_navigate',
arguments: { url: server.HELLO_WORLD },
- });
- expect(response.content[0].text).toContain('browser was closed after 500ms of inactivity');
- expect(response).toHaveResponse({
+ })).toHaveResponse({
snapshot: expect.stringContaining(`Hello, world!`),
});
}
- for (const { client } of [client1, client2]) {
- const response = await client.callTool({
- name: 'browser_snapshot',
- arguments: {},
- });
- expect(response.content[0].text).not.toContain('inactivity');
- }
expect(formatLog(stderr())).toEqual({
'create browser (persistent)': 2,
'connect to shared browser': 4,
diff --git a/tests/mcp/idle-timeout.spec.ts b/tests/mcp/idle-timeout.spec.ts
index d617e02760..4d9eaae915 100644
--- a/tests/mcp/idle-timeout.spec.ts
+++ b/tests/mcp/idle-timeout.spec.ts
@@ -35,7 +35,6 @@ test('closes the browser after the idle timeout and relaunches it on the next ca
'close browser': 1,
});
- // The next call relaunches the browser and says so, once.
const response = await client.callTool({
name: 'browser_navigate',
arguments: { url: server.HELLO_WORLD },
@@ -43,7 +42,6 @@ test('closes the browser after the idle timeout and relaunches it on the next ca
expect(response).toHaveResponse({
snapshot: expect.stringContaining(`Hello, world!`),
});
- expect(response.content[0].text).toContain('browser was closed after 500ms of inactivity');
const nextResponse = await client.callTool({
name: 'browser_snapshot',
@@ -52,7 +50,6 @@ test('closes the browser after the idle timeout and relaunches it on the next ca
expect(nextResponse).toHaveResponse({
inlineSnapshot: expect.stringContaining(`Hello, world!`),
});
- expect(nextResponse.content[0].text).not.toContain('inactivity');
expect(formatLog(stderr())).toEqual({
'create browser (persistent)': 2,
@@ -80,14 +77,12 @@ test('cdp endpoint only disconnects on idle and reconnects to the same pages', a
'create context': 1,
'close browser': 1,
});
- // The browser is not ours, its page stays open.
expect(browserContext.pages().map(page => page.url())).toContain(server.HELLO_WORLD);
const response = await client.callTool({
name: 'browser_snapshot',
arguments: {},
});
- expect(response.content[0].text).toContain('connection was closed after 500ms of inactivity');
expect(response).toHaveResponse({
inlineSnapshot: expect.stringContaining(`Hello, world!`),
});