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
6 changes: 5 additions & 1 deletion docs/tool-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,11 @@ so returned values have to JSON-serializable.

**Description:** List all console messages for the currently selected page since the last navigation.

**Parameters:** None
**Parameters:**

- **pageIdx** (integer) _(optional)_: Page number to return (0-based). When omitted, returns the first page.
- **pageSize** (integer) _(optional)_: Maximum number of messages to return. When omitted, returns all requests.
- **types** (array) _(optional)_: Filter messages to only return messages of the specified resource types. When omitted or empty, returns all messages.

---

Expand Down
104 changes: 85 additions & 19 deletions src/McpResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import type {
ImageContent,
TextContent,
} from '@modelcontextprotocol/sdk/types.js';
import type {ResourceType} from 'puppeteer-core';
import type {ConsoleMessage, ResourceType} from 'puppeteer-core';

import {formatConsoleEvent} from './formatters/consoleFormatter.js';
import {
Expand All @@ -29,20 +29,30 @@ interface NetworkRequestData {
responseBody?: string;
}

export interface ConsoleMessageData {
type: string;
message: string;
args: string[];
}

export class McpResponse implements Response {
#includePages = false;
#includeSnapshot = false;
#includeVerboseSnapshot = false;
#attachedNetworkRequestData?: NetworkRequestData;
#includeConsoleData = false;
#consoleMessagesData?: ConsoleMessageData[];
#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 @@ -79,8 +89,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 @@ -98,14 +130,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 @@ -142,8 +180,6 @@ export class McpResponse implements Response {
await context.createTextSnapshot(this.#includeVerboseSnapshot);
}

let formattedConsoleMessages: string[];

if (this.#attachedNetworkRequestData?.networkRequestStableId) {
const request = context.getNetworkRequestById(
this.#attachedNetworkRequestData.networkRequestStableId,
Expand All @@ -159,14 +195,35 @@ 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;
}
if (this.#consoleDataOptions?.include) {
const messages = context.getConsoleData();

this.#consoleMessagesData = await Promise.all(
messages.map(async (item): Promise<ConsoleMessageData> => {
if ('args' in item) {
const consoleMessage = item as ConsoleMessage;
return {
type: consoleMessage.type(),
message: consoleMessage.text(),
args: await Promise.all(
consoleMessage.args().map(async arg => {
const stringArg = await arg.jsonValue().catch(() => {
// Ignore errors.
});
return typeof stringArg === 'object'
? JSON.stringify(stringArg)
: String(stringArg);
}),
),
};
}
return {
type: 'error',
message: (item as Error).message,
args: [],
};
}),
);
}

return this.format(toolName, context);
Expand Down Expand Up @@ -264,10 +321,19 @@ Call ${handleDialog.name} to handle it before continuing.`);
}
}

if (this.#includeConsoleData && this.#formattedConsoleData) {
if (this.#consoleDataOptions?.include) {
const messages = this.#consoleMessagesData ?? [];

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(
...data.items.map(message => formatConsoleEvent(message)),
);
} else {
response.push('<no console messages found>');
}
Expand Down
95 changes: 23 additions & 72 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 {ConsoleMessageData} from '../McpResponse.js';

const logLevels: Record<string, string> = {
log: 'Log',
Expand All @@ -19,78 +15,33 @@ const logLevels: Record<string, string> = {
assert: 'Assert',
};

export async function formatConsoleEvent(
event: ConsoleMessage | Error,
): Promise<string> {
// Check if the event object has the .type() method, which is unique to ConsoleMessage
if ('type' in event) {
return await formatConsoleMessage(event);
}
return `Error: ${event.message}`;
}

async function formatConsoleMessage(msg: ConsoleMessage): Promise<string> {
const logLevel = logLevels[msg.type()];
const args = msg.args();
export function formatConsoleEvent(msg: ConsoleMessageData): string {
const logLevel = logLevels[msg.type] ?? 'Log';
const text = msg.message;

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 = formatArgs(msg.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
function formatArgs(args: string[], messageText: string): 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 = args[0];

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;
}
6 changes: 5 additions & 1 deletion src/tools/ToolDefinition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,11 @@ 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;
setIncludeSnapshot(value: boolean, verbose?: boolean): void;
attachImage(value: ImageContentData): void;
attachNetworkRequest(reqid: number): void;
Expand Down
61 changes: 58 additions & 3 deletions src/tools/console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,37 @@
* 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:
Expand All @@ -15,8 +43,35 @@ export const consoleTool = defineTool({
category: ToolCategories.DEBUGGING,
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 @@ -341,8 +341,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