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): do not run heartbeat for clients without the event stream (#42189)
Yury Semikhatsky43a9121961cb
diff --git a/packages/playwright-core/src/tools/utils/mcp/http.ts b/packages/playwright-core/src/tools/utils/mcp/http.tsindex d6d97ab9e2..78e75b44e1 100644--- a/packages/playwright-core/src/tools/utils/mcp/http.ts+++ b/packages/playwright-core/src/tools/utils/mcp/http.ts@@ -153,9 +153,7 @@ async function handleStreamable(serverBackendFactory: ServerBackendFactory, req:sessionIdGenerator: () => crypto.randomUUID(),onsessioninitialized: async sessionId => {testDebug(`create http session`);- const sessionInfo = { transport, transportInitialized: new ManualPromise() };- // Only give the client 5 seconds to reach for the event stream.- setTimeout(() => sessionInfo.transportInitialized.resolve(), 5000);+ const sessionInfo = { transport, transportInitialized: new ManualPromise<void>() };sessions.set(sessionId, sessionInfo);await mcpServer.connect(serverBackendFactory, sessionInfo.transport, sessionInfo.transportInitialized, true);}diff --git a/packages/playwright-core/src/tools/utils/mcp/server.ts b/packages/playwright-core/src/tools/utils/mcp/server.tsindex 252e7ccb5a..4799818189 100644--- a/packages/playwright-core/src/tools/utils/mcp/server.ts+++ b/packages/playwright-core/src/tools/utils/mcp/server.ts@@ -71,6 +71,7 @@ export function createServer(name: string, version: string, factory: ServerBacke});let backendPromise: Promise<ServerBackend> | undefined;+ let heartbeatStarted = false;const onClose = () => backendPromise?.then(b => b.dispose?.()).catch(serverDebug);addServerListener(server, 'close', onClose);@@ -80,12 +81,16 @@ export function createServer(name: string, version: string, factory: ServerBacketry {if (!backendPromise) {- const promise = initializeServer(server, factory, transportInitialized, runHeartbeat).then(backend => {+ const promise = initializeServer(server, factory, transportInitialized).then(backend => {backend.once('disconnected', () => {if (backendPromise === promise)backendPromise = undefined;void backend.dispose?.().catch(serverDebug);});+ if (runHeartbeat && !heartbeatStarted) {+ heartbeatStarted = true;+ void transportInitialized.then(() => startHeartbeat(server));+ }return backend;}).catch(e => {if (backendPromise === promise)@@ -110,11 +115,11 @@ export function createServer(name: string, version: string, factory: ServerBackereturn server;}-const initializeServer = async (server: ServerType, factory: ServerBackendFactory, transportInitialized: Promise<void>, runHeartbeat: boolean): Promise<ServerBackend> => {+const initializeServer = async (server: ServerType, factory: ServerBackendFactory, transportInitialized: Promise<void>): Promise<ServerBackend> => {const capabilities = server.getClientCapabilities();let clientRoots: Root[] = [];if (capabilities?.roots) {- await transportInitialized;+ await Promise.race([transportInitialized, new Promise<void>(f => setTimeout(f, 5000))]);const { roots } = await server.listRoots().catch(e => {serverDebug(e);return { roots: [] };@@ -129,8 +134,6 @@ const initializeServer = async (server: ServerType, factory: ServerBackendFactorconst backend = await factory.create(clientInfo);await backend.initialize?.(clientInfo);- if (runHeartbeat)- startHeartbeat(server);return backend;};diff --git a/tests/mcp/http.spec.ts b/tests/mcp/http.spec.tsindex 1a81fd49c2..f24b65e28f 100644--- a/tests/mcp/http.spec.ts+++ b/tests/mcp/http.spec.ts@@ -490,6 +490,44 @@ test('should close session when heartbeat ping is not answered', async ({ serverawait expect.poll(() => formatLog(stderr())['delete http session']).toBe(1);});+test('should not reap session of a client without the event stream', async ({ serverEndpoint, server }) => {+ const { url, stderr } = await serverEndpoint({ env: { PLAYWRIGHT_MCP_PING_TIMEOUT_MS: '500' } });++ // A POST-only client that never opens the GET event stream (optional per spec),+ // so server-initiated pings cannot be delivered to it.+ // https://github.com/microsoft/playwright-mcp/issues/1710+ const endpoint = new URL('/mcp', url);+ let lastId = 0;+ const post = async (body: object, sessionId?: string) => {+ const response = await fetch(endpoint, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ 'accept': 'application/json, text/event-stream',+ ...(sessionId ? { 'mcp-session-id': sessionId } : {}),+ },+ body: JSON.stringify(body),+ });+ return { status: response.status, sessionId: response.headers.get('mcp-session-id'), text: await response.text() };+ };++ const init = await post({ jsonrpc: '2.0', id: ++lastId, method: 'initialize', params: { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'post-only', version: '1.0.0' } } });+ expect(init.status).toBe(200);+ const sessionId = init.sessionId!;+ await post({ jsonrpc: '2.0', method: 'notifications/initialized' }, sessionId);++ const navigate = await post({ jsonrpc: '2.0', id: ++lastId, method: 'tools/call', params: { name: 'browser_navigate', arguments: { url: server.HELLO_WORLD } } }, sessionId);+ expect(navigate.status).toBe(200);++ // Wait long past the ping timeout, the heartbeat must not kick in.+ await new Promise(f => setTimeout(f, 1000));++ const snapshot = await post({ jsonrpc: '2.0', id: ++lastId, method: 'tools/call', params: { name: 'browser_snapshot', arguments: {} } }, sessionId);+ expect(snapshot.status).toBe(200);+ expect(snapshot.text).toContain('Hello, world!');+ expect(formatLog(stderr())['delete http session']).toBeUndefined();+});+test('should not run heartbeat when timeout is non-positive', async ({ serverEndpoint, server }) => {const { url, stderr } = await serverEndpoint({ env: { PLAYWRIGHT_MCP_PING_TIMEOUT_MS: '0' } });