#2724·stagehand

WebMCP completion can be lost when toolResponded arrives before invokeTool resolves

Author: abhinavkr26104Created Aug 15, 2026Updated Sep 24, 2026

Description

Page.invokeWebMCPTool() installs the WebMCP.toolResponded listener before sending WebMCP.invokeTool, but it does not add the invocation record to webMCPInvocations until after the command response arrives.

CDP events can be delivered before the response to the command that triggered them. If a fast WebMCP tool emits WebMCP.toolResponded before mainSession.send() resolves, onWebMCPToolResponded sees no record and drops the terminal result. The invocation is registered only afterward, so waitForWebMCPInvocationResult() then waits forever unless the caller supplied a timeout.

Code reference

  • packages/extension/understudy/page.ts:176-188 ignores events whose invocation ID is not already present.
  • packages/extension/understudy/page.ts:665-702 sends WebMCP.invokeTool first and registers the returned ID afterward.
  • Existing coverage in packages/extension/tests/page-webmcp-invocations.test.ts:140-188 emits completion only after invokeWebMCPTool() has resolved, so it does not exercise event-before-response ordering.

Reproduction

A deterministic unit reproduction can use the existing fake CDP session:

  1. In the fake handler for WebMCP.invokeTool, synchronously emit WebMCP.toolResponded with invocationId: "invocation-1".
  2. Return { invocationId: "invocation-1" } from the handler.
  3. Await page.invokeWebMCPTool(...).
  4. Call page.waitForWebMCPInvocationResult("invocation-1", { timeout: 10 }).

The wait times out because the event was delivered at step 1 and discarded before the map entry was created.

Expected behavior

A terminal WebMCP.toolResponded event is retained regardless of whether it arrives just before or just after the WebMCP.invokeTool command response.

Actual behavior

An event delivered before command resolution is silently dropped, leaving the invocation permanently pending.

Why it matters

Fast tools can intermittently hang a workflow even though Chrome reported successful completion. The race is timing-dependent, and callers that omit the optional result timeout have no recovery other than closing the page/session.

Duplicate/history check

I searched open and closed issues and PRs for WebMCP, toolResponded, invocation races, and event-before-response handling. Existing WebMCP work and tests cover invocation lifecycle after registration, but I found no report or fix for this ordering race.