Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
87 changes: 64 additions & 23 deletions src/McpResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,18 @@ export class McpResponse implements Response {
#includePages = false;
#includeSnapshot = false;
#attachedNetworkRequestData?: NetworkRequestData;
#includeConsoleData = false;
#textResponseLines: string[] = [];
#formattedConsoleData?: string[];
#images: ImageContentData[] = [];
#networkRequestsOptions?: {
include: boolean;
pagination?: PaginationOptions;
resourceTypes?: ResourceType[];
};
#consoleDataOptions?: {
include: boolean;
pagination?: PaginationOptions;
types?: string[];
};

setIncludePages(value: boolean): void {
this.#includePages = value;
Expand Down Expand Up @@ -77,8 +80,30 @@ export class McpResponse implements Response {
};
}

setIncludeConsoleData(value: boolean): void {
this.#includeConsoleData = value;
setIncludeConsoleData(
value: boolean,
options?: {
pageSize?: number;
pageIdx?: number;
types?: string[];
},
): void {
if (!value) {
this.#consoleDataOptions = undefined;
return;
}

this.#consoleDataOptions = {
include: value,
pagination:
options?.pageSize || options?.pageIdx
? {
pageSize: options.pageSize,
pageIdx: options.pageIdx,
}
: undefined,
types: options?.types,
};
}

attachNetworkRequest(reqid: number): void {
Expand All @@ -96,14 +121,20 @@ export class McpResponse implements Response {
}

get includeConsoleData(): boolean {
return this.#includeConsoleData;
return this.#consoleDataOptions?.include ?? false;
}
get attachedNetworkRequestId(): number | undefined {
return this.#attachedNetworkRequestData?.networkRequestStableId;
}
get networkRequestsPageIdx(): number | undefined {
return this.#networkRequestsOptions?.pagination?.pageIdx;
}
get consoleMessagesPageIdx(): number | undefined {
return this.#consoleDataOptions?.pagination?.pageIdx;
}
get consoleMessagesTypes(): string[] | undefined {
return this.#consoleDataOptions?.types;
}

appendResponseLine(value: string): void {
this.#textResponseLines.push(value);
Expand Down Expand Up @@ -136,8 +167,6 @@ export class McpResponse implements Response {
await context.createTextSnapshot();
}

let formattedConsoleMessages: string[];

if (this.#attachedNetworkRequestData?.networkRequestStableId) {
const request = context.getNetworkRequestById(
this.#attachedNetworkRequestData.networkRequestStableId,
Expand All @@ -153,23 +182,13 @@ export class McpResponse implements Response {
}
}

if (this.#includeConsoleData) {
const consoleMessages = context.getConsoleData();
if (consoleMessages) {
formattedConsoleMessages = await Promise.all(
consoleMessages.map(message => formatConsoleEvent(message)),
);
this.#formattedConsoleData = formattedConsoleMessages;
}
}

return this.format(toolName, context);
return await this.format(toolName, context);
}

format(
async format(
toolName: string,
context: McpContext,
): Array<TextContent | ImageContent> {
): Promise<Array<TextContent | ImageContent>> {
const response = [`# ${toolName} response`];
for (const line of this.#textResponseLines) {
response.push(line);
Expand Down Expand Up @@ -258,10 +277,32 @@ Call ${handleDialog.name} to handle it before continuing.`);
}
}

if (this.#includeConsoleData && this.#formattedConsoleData) {
if (this.#consoleDataOptions?.include) {
let messages = context.getConsoleData();

if (this.#consoleDataOptions.types?.length) {
const normalizedTypes = new Set(this.#consoleDataOptions.types);
messages = messages.filter(message => {
if (!('type' in message)) {
return normalizedTypes.has('error');
}
const type = message.type();
return normalizedTypes.has(type);
});
}

response.push('## Console messages');
if (this.#formattedConsoleData.length) {
response.push(...this.#formattedConsoleData);
if (messages.length) {
const data = this.#dataWithPagination(
messages,
this.#consoleDataOptions.pagination,
);
response.push(...data.info);
response.push(
...(await Promise.all(
data.items.map(message => formatConsoleEvent(message)),
)),
);
} else {
response.push('<no console messages found>');
}
Expand Down
85 changes: 26 additions & 59 deletions src/formatters/consoleFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/

import type {
ConsoleMessage,
JSHandle,
ConsoleMessageLocation,
} from 'puppeteer-core';
import type {ConsoleMessage, JSHandle} from 'puppeteer-core';

const logLevels: Record<string, string> = {
log: 'Log',
Expand All @@ -31,66 +27,37 @@ export async function formatConsoleEvent(

async function formatConsoleMessage(msg: ConsoleMessage): Promise<string> {
const logLevel = logLevels[msg.type()];
const text = msg.text();
const args = msg.args();

if (logLevel === 'Error') {
let message = `${logLevel}> `;
if (msg.text() === 'JSHandle@error') {
const errorHandle = args[0] as JSHandle<Error>;
message += await errorHandle
.evaluate(error => {
return error.toString();
})
.catch(() => {
return 'Error occurred';
});
void errorHandle.dispose().catch();
const formattedArgs = await formatArgs(args, text);
return `${logLevel}> ${text} ${formattedArgs}`.trim();
}

const formattedArgs = await formatArgs(args.slice(1));
if (formattedArgs) {
message += ` ${formattedArgs}`;
}
} else {
message += msg.text();
const formattedArgs = await formatArgs(args);
if (formattedArgs) {
message += ` ${formattedArgs}`;
}
for (const frame of msg.stackTrace()) {
message += '\n' + formatStackFrame(frame);
}
}
return message;
// Only includes the first arg and indicates that there are more args
async function formatArgs(
args: readonly JSHandle[],
messageText: string,
): Promise<string> {
if (args.length === 0) {
return '';
}

const formattedArgs = await formatArgs(args);
const text = msg.text();

return `${logLevel}> ${formatStackFrame(
msg.location(),
)}: ${text} ${formattedArgs}`.trim();
}

async function formatArgs(args: readonly JSHandle[]): Promise<string> {
const argValues = await Promise.all(
args.map(arg =>
arg.jsonValue().catch(() => {
// Ignore errors
}),
),
);
let formattedArgs = '';
const firstArg = await args[0].jsonValue().catch(() => {
// Ignore errors
});

return argValues
.map(value => {
return typeof value === 'object' ? JSON.stringify(value) : String(value);
})
.join(' ');
}
if (firstArg !== messageText) {
formattedArgs +=
typeof firstArg === 'object'
? JSON.stringify(firstArg)
: String(firstArg);
}

function formatStackFrame(stackFrame: ConsoleMessageLocation): string {
if (!stackFrame?.url) {
return '<unknown>';
if (args.length > 1) {
return `${formattedArgs} ...`;
}
const filename = stackFrame.url.replace(/^.*\//, '');
return `${filename}:${stackFrame.lineNumber}:${stackFrame.columnNumber}`;

return formattedArgs;
}
5 changes: 4 additions & 1 deletion src/tools/ToolDefinition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,10 @@ export interface Response {
value: boolean,
options?: {pageSize?: number; pageIdx?: number; resourceTypes?: string[]},
): void;
setIncludeConsoleData(value: boolean): void;
setIncludeConsoleData(
value: boolean,
options?: {pageSize?: number; pageIdx?: number; types?: string[]},
): void;
setIncludeSnapshot(value: boolean): void;
attachImage(value: ImageContentData): void;
attachNetworkRequest(reqid: number): void;
Expand Down
63 changes: 59 additions & 4 deletions src/tools/console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,74 @@
* SPDX-License-Identifier: Apache-2.0
*/

import type {ConsoleMessageType} from 'puppeteer-core';
import z from 'zod';

import {ToolCategories} from './categories.js';
import {defineTool} from './ToolDefinition.js';

const FILTERABLE_MESSAGE_TYPES: readonly [
ConsoleMessageType,
...ConsoleMessageType[],
] = [
'log',
'debug',
'info',
'error',
'warn',
'dir',
'dirxml',
'table',
'trace',
'clear',
'startGroup',
'startGroupCollapsed',
'endGroup',
'assert',
'profile',
'profileEnd',
'count',
'timeEnd',
'verbose',
];

export const consoleTool = defineTool({
name: 'list_console_messages',
description:
'List all console messages for the currently selected page since the last navigation.',
annotations: {
category: ToolCategories.DEBUGGING,
category: ToolCategories.NETWORK,
readOnlyHint: true,
},
schema: {},
handler: async (_request, response) => {
response.setIncludeConsoleData(true);
schema: {
pageSize: z
.number()
.int()
.positive()
.optional()
.describe(
'Maximum number of messages to return. When omitted, returns all requests.',
),
pageIdx: z
.number()
.int()
.min(0)
.optional()
.describe(
'Page number to return (0-based). When omitted, returns the first page.',
),
types: z
.array(z.enum(FILTERABLE_MESSAGE_TYPES))
.optional()
.describe(
'Filter messages to only return messages of the specified resource types. When omitted or empty, returns all messages.',
),
},
handler: async (request, response) => {
response.setIncludeConsoleData(true, {
pageSize: request.params.pageSize,
pageIdx: request.params.pageIdx,
types: request.params.types,
});
},
});
3 changes: 1 addition & 2 deletions tests/McpResponse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,8 +319,7 @@ reqid=1 GET http://example.com [pending]`,
// Cannot check the full text because it contains local file path
assert.ok(
result[0].text.toString().startsWith(`# test response
## Console messages
Log>`),
## Console messages`),
);
assert.ok(result[0].text.toString().includes('Hello from the test'));
});
Expand Down
Loading
Loading