Skip to content

[MCP] backendPromise not cleared in onClose causes stale backend after disconnect #40018

@mlugo-apx

Description

@mlugo-apx

Bug Description

When the MCP server's onClose handler fires (e.g., due to browser disconnect or extension disconnect), it disposes the backend but does not clear backendPromise. This causes subsequent tool calls to await the stale promise and receive a disposed backend, resulting in "Not connected" errors.

Affected File

packages/playwright-core/src/tools/utils/mcp/server.ts — Line 80

Current Code (Buggy)

let backendPromise: Promise<ServerBackend> | undefined;

const onClose = () => backendPromise?.then(b => backendManager.disposeBackend(b)).catch(serverDebug);

The onClose handler disposes the backend but leaves backendPromise pointing to the (now disposed) backend. The next tool call checks if (!backendPromise) on line 97, finds it truthy, awaits it, and gets a dead backend.

Expected Behavior

After onClose fires, the next tool call should create a new backend, not reuse the disposed one.

Proposed Fix

const onClose = () => {
  const p = backendPromise;
  backendPromise = undefined;  // Clear FIRST to allow recreation on next tool call
  p?.then(b => backendManager.disposeBackend(b)).catch(serverDebug);
};

Reproduction

  1. Start MCP server connected to Chrome browser
  2. Wait for browser idle timeout or trigger extension disconnect
  3. onClose fires, backend disposed but backendPromise still set
  4. Next tool call (e.g., browser_tabs) awaits stale backendPromise
  5. Returns disposed backend → "Not connected" error
  6. Only fix is MCP server restart

Impact

Users experience random "Not connected" errors during long MCP sessions. The connection appears to work initially but fails after any disconnect event, with no automatic recovery.

Environment

  • Playwright version: 1.52.0+
  • MCP mode: stdio and HTTP
  • Affects: All MCP backends (browser, etc.)

Validation

Tested this fix locally for 6+ hours with instrumentation logging. Zero issues, connection remains stable or recovers automatically after disconnect.

Happy to submit a PR with the fix.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions