Skip to content

Commit e65229f

Browse files
authored
fix(mcp): drop the backend after browser_close with a shared browser (#42365)
Fixes #42363 ### What happens With the HTTP transport and `--shared-browser-context`, `browser_close` disposes the calling client's `BrowserBackend`: the `Context` is cleared and the dispose callback only decrements the client count, because another client keeps the shared browser alive. `server.ts` caches `backendPromise` per session and clears it only on the backend's `disconnected` event, which `BrowserBackend` emits only when the browser context closes or the browser disconnects. Neither happens here, so the next tool call from that client reuses the disposed backend: `ensureBrowserContext` returns the already resolved promise without re registering the page listener, `newTab` finds no tab, and `browser_tabs` (new) or `browser_navigate` fail with ``` TypeError: Cannot read properties of undefined (reading 'checkUrlAndNavigate') TypeError: Cannot read properties of undefined (reading 'waitForInitialized') ``` until the server restarts. In the CLI server, non shared and isolated modes are unaffected because they close the context or the browser and the event fires. ### The change `BrowserBackend.dispose()` now emits `disconnected` (guarded so it fires once) after the context and the dispose callback have run. `server.ts` already drops the cached backend in its existing `once('disconnected')` listener, so the next call creates a fresh backend through the factory. The listener also calls `backend.dispose()` again, which is a no op through the existing `_disposed` guard. This was chosen over special casing the close result in `server.ts`: `callTool` already strips `isClose` from the result before returning it, so the server cannot see a close without widening the `ServerBackend` contract, and the event approach makes every disposal path invalidate the cache, not only `browser_close`. No debug line is logged from `dispose`, so the tests that count `browser disconnected` lines are unaffected. The library entry point (`createConnection` in `mcp/index.ts`) goes through the same `createServer`, so it picks up the same behaviour: after `browser_close` the next call now drops the disposed backend and asks the factory for a new one (a fresh `BrowserBackend` on the context the getter returns when a `contextGetter` is supplied), instead of failing with the TypeError. Without a getter the factory launches a second browser while the first stays open, because `createConnection` passes no dispose callback and `browser_close` never closed the browser in library mode before or after this change; that is pre existing. The other `BrowserBackend` consumers (`cli-daemon`, `traceSnapshot`, the test backend under `playwright/src/mcp`) register no `disconnected` listener, and an emit with no listener is harmless. ### Test New `http transport shared context survives browser_close` in `tests/mcp/http.spec.ts`, modelled on the neighbouring shared context test: two HTTP clients with `--shared-browser-context`, both navigate, client 1 calls `browser_close` then `browser_tabs` (new) and must get a snapshot, client 2's `browser_snapshot` must still work, and the log counts must match (`create context 3`, `close browser 1`). ``` # chromium project, tests/mcp/http.spec.ts with the change: 20 passed, 1 failed source reverted, test kept: the new test fails with TypeError ... 'checkUrlAndNavigate' at the browser_tabs assertion # chromium project, tests/mcp/launch.spec.ts and cdp.spec.ts (the tests that count browser disconnected lines) with the change: 19 passed ``` The one failure in `http.spec.ts` is `should close session when heartbeat ping is not answered`, and it fails identically with the source reverted, so it is unrelated to this change: on the machine used here the default `chrome` channel takes 7 to 8 seconds to launch a fresh persistent profile, and the heartbeat only starts once the backend exists, so the session delete lands after `expect.poll`'s default 5 second timeout. With `--browser=chromium` the same scenario reaps the session in under 3 seconds. The issue's three step scenario was also run end to end against a built `mcp.js` with two streamable HTTP clients before and after the change; before, step 3 returns the TypeError above and the second client keeps working; after, all steps succeed. `eslint`, `tsc`, `lint-tests` and `check-deps` pass. Only the chromium project was run locally; chrome, firefox and webkit were not.
1 parent eca9e03 commit e65229f

4 files changed

Lines changed: 240 additions & 7 deletions

File tree

‎packages/playwright-core/src/tools/backend/browserBackend.ts‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,22 +38,23 @@ export class BrowserBackend extends EventEmitter<{ disconnected: [] }> implement
3838
private _disposed = false;
3939
private _browserContext: playwright.BrowserContext;
4040
private _disposeCallback: (() => Promise<void>) | undefined;
41+
private _markDisconnected: () => void;
4142

4243
constructor(config: ContextConfig, browserContext: playwright.BrowserContext, tools: Tool[], disposeCallback?: () => Promise<void>) {
4344
super();
4445
this._config = config;
4546
this._tools = tools;
4647
this._browserContext = browserContext;
4748
this._disposeCallback = disposeCallback;
48-
const markDisconnected = () => {
49+
this._markDisconnected = () => {
4950
if (this._disconnected)
5051
return;
5152
backendDebug('browser disconnected');
5253
this._disconnected = true;
5354
this.emit('disconnected');
5455
};
55-
this._browserContext.once('close', markDisconnected);
56-
this._browserContext.browser()?.once('disconnected', markDisconnected);
56+
this._browserContext.once('close', this._markDisconnected);
57+
this._browserContext.browser()?.once('disconnected', this._markDisconnected);
5758
}
5859

5960
async initialize(clientInfo: ClientInfo): Promise<void> {
@@ -69,8 +70,18 @@ export class BrowserBackend extends EventEmitter<{ disconnected: [] }> implement
6970
if (this._disposed)
7071
return;
7172
this._disposed = true;
73+
// These listeners would otherwise keep every disposed backend reachable for
74+
// as long as the context and the browser live.
75+
this._browserContext.off('close', this._markDisconnected);
76+
this._browserContext.browser()?.off('disconnected', this._markDisconnected);
7277
await this._context?.dispose().catch(e => debug('pw:tools:error')(e));
7378
await this._disposeCallback?.().catch(e => debug('pw:tools:error')(e));
79+
// The browser may outlive this backend, e.g. when other clients share it,
80+
// so tell the server to stop handing out the disposed backend.
81+
if (!this._disconnected) {
82+
this._disconnected = true;
83+
this.emit('disconnected');
84+
}
7485
}
7586

7687
async callTool(name: string, rawArguments: mcpServer.CallToolRequest['params']['arguments'] & { _meta?: Record<string, any> } = {}, signal?: AbortSignal): Promise<mcpServer.CallToolResult> {

‎packages/playwright-core/src/tools/mcp/index.ts‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,24 @@ export async function createConnection(userConfig: Config = {}, contextGetter?:
3535
version: packageJSON.version,
3636
toolSchemas: tools.map(tool => tool.schema),
3737
create: async (clientInfo: ClientInfo) => {
38-
const browser = contextGetter
39-
? new SimpleBrowser(await contextGetter())
40-
: (await createBrowserWithInfo(config, clientInfo, {})).browser;
38+
if (contextGetter) {
39+
const browser = new SimpleBrowser(await contextGetter());
40+
const context = config.browser.isolated ? await browser.newContext() : browser.contexts()[0];
41+
// The caller owns the context it handed us, so it closes it too.
42+
return new BrowserBackend(config, context, tools);
43+
}
44+
45+
const { browser } = await createBrowserWithInfo(config, clientInfo, {});
4146
const context = config.browser.isolated ? await browser.newContext(config.browser.contextOptions) : browser.contexts()[0];
42-
return new BrowserBackend(config, context, tools);
47+
// Close the browser in both ownership modes. A browser this factory
48+
// launched shuts down here. For an attached one (a CDP or remote
49+
// endpoint, or the extension) close() only drops the connection this
50+
// factory made while the external browser keeps running, so skipping it
51+
// would leak that connection. The next call attaches again.
52+
return new BrowserBackend(config, context, tools, async () => {
53+
await context.close().catch(() => {});
54+
await browser.close().catch(() => {});
55+
});
4356
},
4457
};
4558
return createServer('api', packageJSON.version, backendFactory, Promise.resolve(), false);

‎tests/mcp/http.spec.ts‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -438,6 +438,62 @@ test('http transport shared context', async ({ serverEndpoint, server }) => {
438438
});
439439
});
440440

441+
test('http transport shared context survives browser_close', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/42363' } }, async ({ serverEndpoint, server }) => {
442+
const { url, stderr } = await serverEndpoint({ args: ['--shared-browser-context'] });
443+
444+
const transport1 = new StreamableHTTPClientTransport(new URL('/mcp', url));
445+
const client1 = new Client({ name: 'test1', version: '1.0.0' });
446+
await client1.connect(transport1);
447+
await client1.callTool({
448+
name: 'browser_navigate',
449+
arguments: { url: server.HELLO_WORLD },
450+
});
451+
452+
const transport2 = new StreamableHTTPClientTransport(new URL('/mcp', url));
453+
const client2 = new Client({ name: 'test2', version: '1.0.0' });
454+
await client2.connect(transport2);
455+
await client2.callTool({
456+
name: 'browser_navigate',
457+
arguments: { url: server.HELLO_WORLD },
458+
});
459+
460+
// The second client keeps the shared browser alive, so closing only
461+
// disposes the first client's backend.
462+
await client1.callTool({
463+
name: 'browser_close',
464+
arguments: {},
465+
});
466+
467+
// The next call from the first client must get a fresh backend.
468+
expect(await client1.callTool({
469+
name: 'browser_tabs',
470+
arguments: { action: 'new', url: server.HELLO_WORLD },
471+
})).toHaveResponse({
472+
snapshot: expect.stringContaining(`Hello, world!`),
473+
});
474+
475+
// The second client is unaffected.
476+
expect(await client2.callTool({
477+
name: 'browser_snapshot',
478+
arguments: {},
479+
})).toHaveResponse({
480+
inlineSnapshot: expect.stringContaining(`Hello, world!`),
481+
});
482+
483+
await transport1.terminateSession();
484+
await client1.close();
485+
await transport2.terminateSession();
486+
await client2.close();
487+
488+
await expect.poll(() => formatLog(stderr())).toEqual({
489+
'create browser (persistent)': 1,
490+
'create http session': 2,
491+
'delete http session': 2,
492+
'create context': 3,
493+
'close browser': 1,
494+
});
495+
});
496+
441497
test('http transport (default)', async ({ serverEndpoint }) => {
442498
const { url } = await serverEndpoint();
443499
const transport = new StreamableHTTPClientTransport(url);

‎tests/mcp/library.spec.ts‎

Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,17 @@
1515
*/
1616
import child_process from 'child_process';
1717
import fs from 'fs/promises';
18+
import net from 'net';
19+
20+
import * as playwright from 'playwright';
21+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
22+
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
1823
import { test, expect } from './fixtures';
24+
import { tools } from '../../packages/playwright-core/lib/coreBundle';
25+
26+
import type { Server } from '@modelcontextprotocol/sdk/server/index.js';
27+
28+
const { createConnection } = tools;
1929

2030
test('library can be used from CommonJS', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright-mcp/issues/456' } }, async ({}, testInfo) => {
2131
const file = testInfo.outputPath('main.cjs');
@@ -26,3 +36,146 @@ test('library can be used from CommonJS', { annotation: { type: 'issue', descrip
2636
`);
2737
expect(child_process.execSync(`node ${file}`, { encoding: 'utf-8' })).toContain('OK');
2838
});
39+
40+
test('createConnection detaches backend listeners from a caller owned context', async ({ mcpBrowser, mcpHeadless, server }, testInfo) => {
41+
const { browserName, channel } = browserForProject(mcpBrowser);
42+
const browser = await playwright[browserName].launch({ channel, headless: mcpHeadless });
43+
const browserContext = await browser.newContext();
44+
45+
const client = await connectClient(await createConnection({
46+
outputDir: testInfo.outputPath('output'),
47+
}, async () => browserContext));
48+
49+
const contextListeners = listenerCount(browserContext, 'close');
50+
const browserListeners = listenerCount(browser, 'disconnected');
51+
52+
// browser_close disposes the backend while the caller keeps the context, so
53+
// the next tool call builds another backend over the same two objects.
54+
for (let i = 0; i < 3; i++) {
55+
await client.callTool({ name: 'browser_navigate', arguments: { url: server.HELLO_WORLD } });
56+
// A live backend listens on both objects.
57+
expect(listenerCount(browserContext, 'close')).toBe(contextListeners + 1);
58+
expect(listenerCount(browser, 'disconnected')).toBe(browserListeners + 1);
59+
60+
await client.callTool({ name: 'browser_close', arguments: {} });
61+
// A disposed one gives both back, so they do not pile up.
62+
expect(listenerCount(browserContext, 'close')).toBe(contextListeners);
63+
expect(listenerCount(browser, 'disconnected')).toBe(browserListeners);
64+
}
65+
66+
await client.close();
67+
await browser.close();
68+
});
69+
70+
test('createConnection closes the browser it launched when the backend is disposed', async ({ mcpBrowser, mcpHeadless, server }, testInfo) => {
71+
test.skip(!['chrome', 'msedge', 'chromium'].includes(mcpBrowser!), 'Profile locking is a Chromium behavior');
72+
73+
const { browserName, channel } = browserForProject(mcpBrowser);
74+
const userDataDir = testInfo.outputPath('user-data-dir');
75+
76+
const client = await connectClient(await createConnection({
77+
// Match what BrowserType.launch does by default. Resolving this config
78+
// turns the sandbox on for a chromium without a channel, and the bundled
79+
// build cannot sandbox on a linux runner.
80+
browser: { browserName, userDataDir, launchOptions: { channel, chromiumSandbox: false, headless: mcpHeadless } },
81+
outputDir: testInfo.outputPath('output'),
82+
}));
83+
84+
expect(await client.callTool({
85+
name: 'browser_navigate',
86+
arguments: { url: server.HELLO_WORLD },
87+
})).toHaveResponse({
88+
page: expect.stringContaining(`Page URL: ${server.HELLO_WORLD}`),
89+
});
90+
91+
// Nothing else holds this browser, so disposing the backend has to close it.
92+
// A leaked browser keeps the profile, and nothing else can open it. Claiming
93+
// the profile from the test rather than through another tool call keeps this
94+
// about the browser process and not about how the server rebuilds a backend.
95+
await client.callTool({ name: 'browser_close', arguments: {} });
96+
await client.close();
97+
98+
await expect.poll(async () => {
99+
try {
100+
const context = await playwright[browserName].launchPersistentContext(userDataDir, { channel, headless: mcpHeadless });
101+
await context.close();
102+
return 'free';
103+
} catch (e: any) {
104+
return String(e.message);
105+
}
106+
}, { timeout: 15000 }).toBe('free');
107+
});
108+
109+
test('createConnection drops its connection to an attached browser when the backend is disposed', async ({ mcpBrowser, mcpHeadless, server }, testInfo) => {
110+
const { browserName, channel } = browserForProject(mcpBrowser);
111+
const browserServer = await playwright[browserName].launchServer({ channel, headless: mcpHeadless });
112+
const wsUrl = new URL(browserServer.wsEndpoint());
113+
// URL keeps the brackets around an IPv6 host, net.connect does not take them.
114+
const wsHost = wsUrl.hostname.replace(/^\[|\]$/g, '');
115+
116+
// A counting TCP proxy in front of the browser server makes the connection
117+
// the factory holds observable from the outside.
118+
let openConnections = 0;
119+
const proxy = net.createServer(socket => {
120+
openConnections++;
121+
const upstream = net.connect(Number(wsUrl.port), wsHost);
122+
socket.pipe(upstream);
123+
upstream.pipe(socket);
124+
socket.once('close', () => {
125+
openConnections--;
126+
upstream.destroy();
127+
});
128+
upstream.once('close', () => socket.destroy());
129+
socket.on('error', () => socket.destroy());
130+
upstream.on('error', () => upstream.destroy());
131+
});
132+
await new Promise<void>(resolve => proxy.listen(0, '127.0.0.1', resolve));
133+
const proxyPort = (proxy.address() as net.AddressInfo).port;
134+
135+
const client = await connectClient(await createConnection({
136+
browser: { remoteEndpoint: `ws://127.0.0.1:${proxyPort}${wsUrl.pathname}` },
137+
outputDir: testInfo.outputPath('output'),
138+
}));
139+
140+
expect(await client.callTool({
141+
name: 'browser_navigate',
142+
arguments: { url: server.HELLO_WORLD },
143+
})).toHaveResponse({
144+
page: expect.stringContaining(`Page URL: ${server.HELLO_WORLD}`),
145+
});
146+
expect(openConnections).toBe(1);
147+
148+
// The factory attached to this browser instead of launching it, so closing
149+
// the browser on dispose only drops the connection the factory made while
150+
// the browser server keeps running. Skipping the close would leak that
151+
// connection for as long as the server stays up.
152+
await client.callTool({ name: 'browser_close', arguments: {} });
153+
await expect.poll(() => openConnections).toBe(0);
154+
155+
// The external browser survived the disconnect.
156+
const probe = await playwright[browserName].connect(browserServer.wsEndpoint());
157+
expect(probe.isConnected()).toBe(true);
158+
await probe.close();
159+
160+
await client.close();
161+
await new Promise<void>(resolve => proxy.close(() => resolve()));
162+
await browserServer.close();
163+
});
164+
165+
function browserForProject(mcpBrowser: string | undefined): { browserName: 'chromium' | 'firefox' | 'webkit', channel: string | undefined } {
166+
const channel = mcpBrowser === 'chrome' || mcpBrowser === 'msedge' ? mcpBrowser : undefined;
167+
const browserName = channel || mcpBrowser === 'chromium' ? 'chromium' : mcpBrowser as 'firefox' | 'webkit';
168+
return { browserName, channel };
169+
}
170+
171+
function listenerCount(emitter: object, event: string): number {
172+
return (emitter as unknown as { listenerCount(event: string): number }).listenerCount(event);
173+
}
174+
175+
async function connectClient(server: Server): Promise<Client> {
176+
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
177+
await server.connect(serverTransport);
178+
const client = new Client({ name: 'test', version: '1.0.0' });
179+
await client.connect(clientTransport);
180+
return client;
181+
}

0 commit comments

Comments
 (0)