-
Notifications
You must be signed in to change notification settings - Fork 5.4k
[MCP] backendPromise not cleared in onClose causes stale backend after disconnect #40018
Description
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
- Start MCP server connected to Chrome browser
- Wait for browser idle timeout or trigger extension disconnect
onClosefires, backend disposed butbackendPromisestill set- Next tool call (e.g.,
browser_tabs) awaits stalebackendPromise - Returns disposed backend → "Not connected" error
- 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.