WebMCP completion can be lost when toolResponded arrives before invokeTool resolves
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-188ignores events whose invocation ID is not already present.packages/extension/understudy/page.ts:665-702sendsWebMCP.invokeToolfirst and registers the returned ID afterward.- Existing coverage in
packages/extension/tests/page-webmcp-invocations.test.ts:140-188emits completion only afterinvokeWebMCPTool()has resolved, so it does not exercise event-before-response ordering.
Reproduction
A deterministic unit reproduction can use the existing fake CDP session:
- In the fake handler for
WebMCP.invokeTool, synchronously emitWebMCP.toolRespondedwithinvocationId: "invocation-1". - Return
{ invocationId: "invocation-1" }from the handler. - Await
page.invokeWebMCPTool(...). - 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.
Source: browserbase/stagehand