Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions packages/extension/understudy/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ export class Page {
readonly initScripts: string[] = [];
extraHTTPHeaders: Record<string, string> = {};
private readonly webMCPInvocations = new Map<string, WebMCPInvocationRecord>();
private readonly earlyWebMCPResponses = new Map<string, Protocol.WebMCP.ToolRespondedEvent>();
private readonly webMCPResponseSessions = new Map<CDPSessionLike, WebMCPResponseSessionState>();
private readonly cdpEventSubscriptions = new Set<CDPEventSubscription>();

Expand All @@ -193,7 +194,11 @@ export class Page {
event: Protocol.WebMCP.ToolRespondedEvent,
): void {
const record = this.webMCPInvocations.get(event.invocationId);
if (!record || record.session !== session || record.result !== undefined) return;
if (!record) {
this.earlyWebMCPResponses.set(event.invocationId, event);
return;
}
if (record.session !== session || record.result !== undefined) return;

const result = webMCPToolResponse(event);
record.result = result;
Expand Down Expand Up @@ -747,12 +752,25 @@ export class Page {
this.removeWebMCPResponseListenerIfIdle(session);
throw error;
}
this.webMCPInvocations.set(response.invocationId, {
const invocationRecord: WebMCPInvocationRecord = {
descriptor,
session,
deferred: createDeferred<WebMCPToolResponse>(),
});
};
this.webMCPInvocations.set(response.invocationId, invocationRecord);
responseState.invocationIds.add(response.invocationId);

const earlyEvent = this.earlyWebMCPResponses.get(response.invocationId);
if (earlyEvent !== undefined) {
this.earlyWebMCPResponses.delete(response.invocationId);
const result = webMCPToolResponse(earlyEvent);
invocationRecord.result = result;
invocationRecord.deferred.resolve(result);
invocationRecord.retentionTimer = setTimeout(() => {
this.removeWebMCPInvocation(response.invocationId, invocationRecord);
}, WEBMCP_SETTLED_INVOCATION_RETENTION_MS);
}

return descriptor;
}

Expand Down
Loading