Skip to content
Closed
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
12 changes: 9 additions & 3 deletions packages/playwright-core/src/tools/mcp/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,14 +132,20 @@ export function decorateMCPCommand(command: Command) {
},
disposed: async backend => {
clientCount--;
if (sharedBrowserPromise && clientCount > 0)
const browserContext = (backend as BrowserBackend).browserContext;
const browser = browserContext.browser();
// Decide before awaiting context closure, since client disposals can run concurrently.
const shouldKeepBrowser = !!sharedBrowserPromise && clientCount > 0;
if (shouldKeepBrowser) {
if (config.browser.isolated)
await browserContext.close().catch(() => { });
return;
}

testDebug('close browser');
sharedBrowserPromise = undefined;
const browserContext = (backend as BrowserBackend).browserContext;
await browserContext.close().catch(() => { });
await browserContext.browser()?.close().catch(() => { });
await browser?.close().catch(() => { });
}
};
await mcpServer.start(factory, config.server);
Expand Down
10 changes: 9 additions & 1 deletion tests/mcp/http.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import dns from 'dns';
import { ChildProcess, spawn } from 'child_process';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { test as baseTest, expect, mcpServerPath, formatLog } from './fixtures';
import { test as baseTest, expect, mcpServerPath, formatLog, parseResponse } from './fixtures';
import { inheritAndCleanEnv } from '../config/utils';

import type { Config } from '../../packages/playwright-core/src/tools/mcp/config.d';
Expand Down Expand Up @@ -182,6 +182,14 @@ test('http transport browser lifecycle (isolated, multiclient)', async ({ server
await transport1.terminateSession();
await client1.close();

await expect.poll(async () => {
const response = parseResponse(await client2.callTool({
name: 'browser_run_code_unsafe',
arguments: { code: 'page => page.context().browser().contexts().length' },
}));
return response.result;
}).toBe('1');

const transport3 = new StreamableHTTPClientTransport(new URL('/mcp', url));
const client3 = new Client({ name: 'test', version: '1.0.0' });
await client3.connect(transport3);
Expand Down