Skip to content
Merged
Show file tree
Hide file tree
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
13 changes: 13 additions & 0 deletions src/McpPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -832,6 +832,19 @@ export class McpPage implements ContextPage {
return this.consoleCollector.getById(id);
}

getLatestConsoleMessageId(): number {
const latest = this.consoleCollector.getData(true).at(-1);
return latest ? this.consoleCollector.getIdForResource(latest) : 0;
}

getConsoleDataAfter(
id: number,
): Array<ConsoleMessage | Error | DevTools.AggregatedIssue | UncaughtError> {
return this.consoleCollector
.getData(true)
.filter(item => this.consoleCollector.getIdForResource(item) > id);
}

getNetworkRequestById(reqid: number): HTTPRequest {
return this.networkCollector.getById(reqid);
}
Expand Down
74 changes: 71 additions & 3 deletions src/McpResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ import type {
SnapshotParams,
WebAuthnAuthenticatorState,
} from './tools/ToolDefinition.js';
import {LIST_CONSOLE_MESSAGES_TOOL_NAME} from './tools/toolNames.js';
import {
type InsightName,
type TraceResult,
Expand All @@ -82,6 +83,9 @@ import type {WaitForEventsResult} from './utils/WaitForHelper.js';

const {formatBytesToKb} = DevTools.I18n.ByteUtilities;

/** How many errors raised during a call the response lists. */
const MAX_CONSOLE_ERRORS = 10;

export type DataFormat = 'default' | 'toon' | 'gcf';

interface TraceInsightData {
Expand Down Expand Up @@ -156,6 +160,7 @@ export class McpResponse implements Response {
#page?: McpPage;
#error?: Error;
#attachedWaitForResult?: WaitForEventsResult;
#consoleErrorsFrom?: {page: McpPage; lastMessageId: number};
#reconnectNotice = false;
#devToolsComments?: CD4ACommentThread[];
#webAuthnFormatter?: WebAuthnFormatter;
Expand Down Expand Up @@ -277,6 +282,13 @@ export class McpResponse implements Response {
};
}

includeConsoleErrorsFrom(page: McpPage): void {
this.#consoleErrorsFrom = {
page,
lastMessageId: page.getLatestConsoleMessageId(),
};
}

setIncludeCssStyles(
matchedStyles: MatchedStyles,
options: CssFormatterOptions & PaginationOptions,
Expand Down Expand Up @@ -671,8 +683,42 @@ export class McpResponse implements Response {
);
}

if (this.#consoleDataOptions.types?.length) {
const normalizedTypes = new Set(this.#consoleDataOptions.types);
return await this.#formatConsoleData(
messages,
page,
this.#consoleDataOptions,
);
}

async #handleConsoleErrors(): Promise<
Array<ConsoleFormatter | IssueFormatter> | undefined
> {
const errorsFrom = this.#consoleErrorsFrom;
// A tool that lists or shows console messages itself already covers these.
if (
!errorsFrom ||
this.#consoleDataOptions?.include ||
this.#attachedConsoleMessageId !== undefined ||
errorsFrom.page.isClosed()
) {
return undefined;
}
return await this.#formatConsoleData(
errorsFrom.page.getConsoleDataAfter(errorsFrom.lastMessageId),
errorsFrom.page,
{types: ['error']},
);
}

async #formatConsoleData(
messages: Array<
ConsoleMessage | Error | DevTools.AggregatedIssue | UncaughtError
>,
page: McpPage | undefined,
options: {types?: string[]; includeStackTraces?: boolean},
): Promise<Array<ConsoleFormatter | IssueFormatter>> {
if (options.types?.length) {
const normalizedTypes = new Set(options.types);
messages = messages.filter(message => {
if ('type' in message) {
return normalizedTypes.has(message.type());
Expand All @@ -694,7 +740,7 @@ export class McpResponse implements Response {
return await ConsoleFormatter.from(consoleMessage, {
id: consoleMessageStableId,
fetchDetailedData: false,
fetchStackTrace: this.#consoleDataOptions?.includeStackTraces,
fetchStackTrace: options.includeStackTraces,
devTools: page ? page.devtoolsUniverse : undefined,
});
}
Expand Down Expand Up @@ -808,6 +854,7 @@ export class McpResponse implements Response {
thirdPartyDeveloperTools,
webmcpTools,
consoleMessages,
consoleErrors,
networkRequests,
commentsResult,
] = await Promise.all([
Expand All @@ -817,6 +864,7 @@ export class McpResponse implements Response {
this.#handleThirdPartyDeveloperTools(),
this.#handleWebMCP(),
this.#handleConsoleList(context),
this.#handleConsoleErrors(),
this.#handleNetworkRequestList(context),
this.#handleComments(),
]);
Expand All @@ -835,6 +883,7 @@ export class McpResponse implements Response {
{
detailedConsoleMessage,
consoleMessages,
consoleErrors,
snapshot,
detailedNetworkRequest,
networkRequests,
Expand Down Expand Up @@ -868,6 +917,7 @@ export class McpResponse implements Response {
data: {
detailedConsoleMessage: ConsoleFormatter | IssueFormatter | undefined;
consoleMessages: Array<ConsoleFormatter | IssueFormatter> | undefined;
consoleErrors?: Array<ConsoleFormatter | IssueFormatter>;
snapshot: SnapshotFormatter | string | undefined;
detailedNetworkRequest?: NetworkFormatter;
networkRequests?: NetworkFormatter[];
Expand All @@ -894,6 +944,7 @@ export class McpResponse implements Response {
networkRequests?: object[];
consoleMessage?: object;
consoleMessages?: object[];
consoleErrors?: object[];
traceSummary?: string;
traceInsights?: Array<{
insightName: string;
Expand Down Expand Up @@ -1735,6 +1786,23 @@ Call ${handleDialog(this.#config.resolved).name} to handle it before continuing.
}
}

if (data.consoleErrors?.length) {
const grouped = ConsoleFormatter.groupConsecutive(data.consoleErrors);
const shown = grouped.slice(0, MAX_CONSOLE_ERRORS);
structuredContent.consoleErrors = shown.map(item => item.toJSON());
response.push('## Console errors during this call');
if (compactEncode) {
response.push(compactEncode(structuredContent.consoleErrors));
} else {
response.push(...shown.map(item => item.toString()));
}
if (grouped.length > shown.length) {
response.push(
`${grouped.length - shown.length} more not shown. Call ${LIST_CONSOLE_MESSAGES_TOOL_NAME} to list them.`,
);
}
}

if (data.comments) {
const commentsJson = data.comments.toJSON();
structuredContent.comments = commentsJson;
Expand Down
4 changes: 4 additions & 0 deletions src/ToolHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,10 @@ export class ToolHandler {
: context.getSelectedMcpPage();
await page?.init({emulateFocus: true});
response.setPage(page);
// A call that runs beside others can't tell its own errors apart.
if (tool.concurrency !== 'none') {
response.includeConsoleErrorsFrom(page);
}
if (tool.blockedByDialog) {
page.throwIfDialogOpen();
}
Expand Down
5 changes: 5 additions & 0 deletions src/tools/ToolDefinition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,11 @@ export interface Response {
serviceWorkerId?: string;
},
): void;
/**
* Lists the console errors and uncaught exceptions that the page raises from
* now until the response is handled.
*/
includeConsoleErrorsFrom(page: ContextPage): void;
setIncludeCssStyles(
matchedStyles: MatchedStyles,
options: CssFormatterOptions & PaginationOptions,
Expand Down
1 change: 1 addition & 0 deletions src/tools/pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ export const newPage: ToolFactory = defineTool((args: ParsedArguments) => {
request.params.background,
request.params.isolatedContext,
);
response.includeConsoleErrorsFrom(page);

try {
await page.waitForEventsAfterAction(
Expand Down
2 changes: 2 additions & 0 deletions src/tools/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,8 @@ Example with arguments: \`(el) => el.innerText\`

const evaluatable = await getPageOrFrame(page, frames);

// ToolHandler hands over the page of page-scoped tools only.
response.includeConsoleErrorsFrom(mcpPage);
const result = await mcpPage.waitForEventsAfterAction(
async () => {
await performEvaluation(
Expand Down
49 changes: 49 additions & 0 deletions tests/McpPage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,55 @@ describe('McpPage', () => {
});
});

describe('getLatestConsoleMessageId() and getConsoleDataAfter()', () => {
function createUncaughtError(exceptionId: number): UncaughtError {
return new UncaughtError(
{
exceptionId,
text: `error-${exceptionId}`,
lineNumber: 0,
columnNumber: 0,
},
'<mock>',
);
}

it('getLatestConsoleMessageId() returns 0 and getConsoleDataAfter() nothing for an empty collector', async () => {
const {mcpPage} = await createMcpPage();

assert.strictEqual(mcpPage.getLatestConsoleMessageId(), 0);
assert.deepStrictEqual(mcpPage.getConsoleDataAfter(0), []);
});

it('getLatestConsoleMessageId() includes messages from an earlier navigation', async () => {
const {mcpPage, pptrPage} = await createMcpPage();
const error = createUncaughtError(1);
pptrPage.emit('uncaughtError', error);
pptrPage.emit('framenavigated', pptrPage.mainFrame());

const id = mcpPage.getLatestConsoleMessageId();

assert.strictEqual(id, mcpPage.consoleCollector.getIdForResource(error));
assert.deepStrictEqual(mcpPage.getConsoleDataAfter(id), []);
});

it('getConsoleDataAfter() returns the messages after the id, from an earlier navigation too', async () => {
const {mcpPage, pptrPage} = await createMcpPage();
pptrPage.emit('uncaughtError', createUncaughtError(1));
const id = mcpPage.getLatestConsoleMessageId();
const beforeNavigation = createUncaughtError(2);
pptrPage.emit('uncaughtError', beforeNavigation);
pptrPage.emit('framenavigated', pptrPage.mainFrame());
const afterNavigation = createUncaughtError(3);
pptrPage.emit('uncaughtError', afterNavigation);

assert.deepStrictEqual(mcpPage.getConsoleDataAfter(id), [
beforeNavigation,
afterNavigation,
]);
});
});

describe('getTitle()', () => {
function createPage(url: string, title: string): McpPage {
const target = createMockPuppeteerTarget({url, title});
Expand Down
Loading
Loading