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
3 changes: 2 additions & 1 deletion docs/tool-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -411,8 +411,9 @@

**Parameters:**

- **msgid** (number) **(required)**: The msgid of a console message on the page from the listed console messages
- **msgid** (number) **(required)**: The msgid of a console message from [`list_console_messages`](#list_console_messages): for the page, or for the service worker when serviceWorkerId is set.
- **pageId** (number) **(required)**: Targets a specific page by ID.
- **serviceWorkerId** (string) _(optional)_: Get the message from the service worker with this ID shown by [`list_pages`](#list_pages) (sw-N) instead of the page. pageId is ignored when set. Stack traces are not available for service worker messages.

---

Expand Down
27 changes: 22 additions & 5 deletions src/McpContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -847,17 +847,34 @@ export class McpContext implements Context, BrowserlessContext {
return Array.from(this.#workers.values());
}

getServiceWorkerConsoleData(
serviceWorkerId: string,
): Array<ConsoleMessage | UncaughtError> {
#getServiceWorkerExtensionId(serviceWorkerId: string): string {
const worker = this.getWorkerById(serviceWorkerId);
if (worker?.type !== 'service_worker') {
throw new Error('Service worker not found.');
throw new Error(
`Service worker ${serviceWorkerId} not found. Call list_pages to get the current sw-N IDs.`,
);
}
const extensionId = new URL(worker.url).hostname;
return new URL(worker.url).hostname;
}

getServiceWorkerConsoleData(
serviceWorkerId: string,
): Array<ConsoleMessage | UncaughtError> {
const extensionId = this.#getServiceWorkerExtensionId(serviceWorkerId);
return this.#serviceWorkerConsoleCollector?.getData(extensionId) ?? [];
}

getServiceWorkerConsoleMessageById(
serviceWorkerId: string,
msgid: number,
): ConsoleMessage | UncaughtError {
const extensionId = this.#getServiceWorkerExtensionId(serviceWorkerId);
if (!this.#serviceWorkerConsoleCollector) {
throw new Error('Service worker console data is not available.');
}
return this.#serviceWorkerConsoleCollector.getById(extensionId, msgid);
}

#getBrowserContextToNameMap(): Map<BrowserContext, string> {
// Build a reverse lookup from BrowserContext instance → name.
const contextToName = new Map<BrowserContext, string>();
Expand Down
31 changes: 22 additions & 9 deletions src/McpResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ export class McpResponse implements Response {
responseFilePath?: string;
};
#attachedConsoleMessageId?: number;
#attachedConsoleMessageServiceWorkerId?: string;
#attachedTraceSummary?: TraceResult;
#attachedTraceInsight?: TraceInsightData;
#attachedLighthouseResult?: LighthouseData;
Expand Down Expand Up @@ -313,8 +314,12 @@ export class McpResponse implements Response {
this.#attachedNetworkRequestOptions = options;
}

attachConsoleMessage(msgid: number): void {
attachConsoleMessage(
msgid: number,
options?: {serviceWorkerId?: string},
): void {
this.#attachedConsoleMessageId = msgid;
this.#attachedConsoleMessageServiceWorkerId = options?.serviceWorkerId;
}

attachWebAuthnAuthenticator(
Expand Down Expand Up @@ -600,19 +605,27 @@ export class McpResponse implements Response {
});
}

async #handleAttachedConsoleMessage(): Promise<
ConsoleFormatter | IssueFormatter | undefined
> {
async #handleAttachedConsoleMessage(
context: McpContext,
): Promise<ConsoleFormatter | IssueFormatter | undefined> {
if (!this.#attachedConsoleMessageId) {
return undefined;
}
const consoleMessageStableId = this.#attachedConsoleMessageId;
if (this.#attachedConsoleMessageServiceWorkerId) {
// Service workers have no DevTools universe, so no stack trace is resolved.
return await ConsoleFormatter.from(
context.getServiceWorkerConsoleMessageById(
this.#attachedConsoleMessageServiceWorkerId,
consoleMessageStableId,
),
{id: consoleMessageStableId, fetchDetailedData: true},
);
}
if (!this.#page) {
throw new Error(`Response must have an McpPage`);
}
const message = this.#page.getConsoleMessageById(
this.#attachedConsoleMessageId,
);
const consoleMessageStableId = this.#attachedConsoleMessageId;
const message = this.#page.getConsoleMessageById(consoleMessageStableId);
if ('args' in message || message instanceof UncaughtError) {
const consoleMessage = message as ConsoleMessage | UncaughtError;
return await ConsoleFormatter.from(consoleMessage, {
Expand Down Expand Up @@ -862,7 +875,7 @@ export class McpResponse implements Response {
] = await Promise.all([
this.#handleSnapshot(context),
this.#handleAttachedNetworkRequest(context),
this.#handleAttachedConsoleMessage(),
this.#handleAttachedConsoleMessage(context),
this.#handleThirdPartyDeveloperTools(),
this.#handleWebMCP(),
this.#handleConsoleList(context),
Expand Down
8 changes: 6 additions & 2 deletions src/collectors/ServiceWorkerCollector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,13 +183,17 @@ export class ServiceWorkerConsoleCollector {
): WithSymbolId<ConsoleMessage | UncaughtError> {
const logs = this.#storage.get(extensionId);
if (!logs) {
throw new Error('No logs found for selected extension');
throw new Error(
`No console messages found for extension ${extensionId}.`,
);
}
const item = logs.find(item => item[stableIdSymbol] === stableId);
if (item) {
return item;
}
throw new Error('Log not found for selected extension');
throw new Error(
`Console message ${stableId} not found for extension ${extensionId}.`,
);
}

find(
Expand Down
10 changes: 9 additions & 1 deletion src/config/cli-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -637,10 +637,18 @@ export const commands: Commands = {
name: 'msgid',
type: 'number',
description:
'The msgid of a console message on the page from the listed console messages',
'The msgid of a console message from list_console_messages: for the page, or for the service worker when serviceWorkerId is set.',
required: true,
positional: true,
},
serviceWorkerId: {
name: 'serviceWorkerId',
type: 'string',
description:
'Get the message from the service worker with this ID shown by list_pages (sw-N) instead of the page. pageId is ignored when set. Stack traces are not available for service worker messages.',
required: false,
positional: false,
},
},
},
get_css_styles: {
Expand Down
3 changes: 2 additions & 1 deletion src/telemetry/tool_call_metrics.json
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,8 @@
},
{
"name": "service_worker_id_length",
"argType": "number"
"argType": "number",
"isDeprecated": true
},
{
"name": "include_stack_traces",
Expand Down
5 changes: 4 additions & 1 deletion src/tools/ToolDefinition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,10 @@ export interface Response {
reqId: number,
options?: {requestFilePath?: string; responseFilePath?: string},
): void;
attachConsoleMessage(msgid: number): void;
attachConsoleMessage(
msgid: number,
options?: {serviceWorkerId?: string},
): void;
attachWebAuthnAuthenticator(
authenticator: WebAuthnAuthenticatorState | undefined,
): void;
Expand Down
74 changes: 47 additions & 27 deletions src/tools/console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,12 +88,16 @@ export const listConsoleMessages: PageToolFactory = definePageTool(
.describe(
'Set to true to include the stack trace for each message when available. Increases the response size.',
),
serviceWorkerId: zod
.string()
.optional()
.describe(
'Filter messages by the service worker ID shown by list_pages (sw-N).',
),
...(cliArgs.categoryExtensions
? {
serviceWorkerId: zod
.string()
.optional()
.describe(
'Filter messages by the service worker ID shown by list_pages (sw-N).',
),
}
: {}),
},
blockedByDialog: false,
concurrency: 'page',
Expand All @@ -112,24 +116,40 @@ export const listConsoleMessages: PageToolFactory = definePageTool(
},
);

export const getConsoleMessage: PageToolFactory = definePageTool(() => ({
name: GET_CONSOLE_MESSAGE_TOOL_NAME,
description: `Gets a console message by its ID. You can get all messages by calling ${LIST_CONSOLE_MESSAGES_TOOL_NAME}.`,
annotations: {
category: ToolCategory.DEBUGGING,
readOnlyHint: true,
},
schema: {
msgid: zod
.number()
.describe(
'The msgid of a console message on the page from the listed console messages',
),
},
blockedByDialog: false,
concurrency: 'page',
verifyFilesSchema: {},
handler: async (request, response) => {
response.attachConsoleMessage(request.params.msgid);
},
}));
export const getConsoleMessage: PageToolFactory = definePageTool(
(cliArgs: ParsedArguments) => ({
name: GET_CONSOLE_MESSAGE_TOOL_NAME,
description: `Gets a console message by its ID. You can get all messages by calling ${LIST_CONSOLE_MESSAGES_TOOL_NAME}.`,
annotations: {
category: ToolCategory.DEBUGGING,
readOnlyHint: true,
},
schema: {
msgid: zod
.number()
.describe(
cliArgs.categoryExtensions
? 'The msgid of a console message from list_console_messages: for the page, or for the service worker when serviceWorkerId is set.'
: 'The msgid of a console message on the page from the listed console messages',
),
...(cliArgs.categoryExtensions
? {
serviceWorkerId: zod
.string()
.optional()
.describe(
'Get the message from the service worker with this ID shown by list_pages (sw-N) instead of the page. pageId is ignored when set. Stack traces are not available for service worker messages.',
),
}
: {}),
},
blockedByDialog: false,
concurrency: 'page',
verifyFilesSchema: {},
handler: async (request, response) => {
response.attachConsoleMessage(request.params.msgid, {
serviceWorkerId: request.params.serviceWorkerId,
});
},
}),
);
50 changes: 49 additions & 1 deletion tests/McpContext.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,9 @@ describe('McpContext', () => {

assert.throws(
() => context.getServiceWorkerConsoleData(serviceWorkerId),
/Service worker not found\./,
new RegExp(
`Service worker ${serviceWorkerId} not found\\. Call list_pages to get the current sw-N IDs\\.`,
),
);

sinon.assert.calledOnceWithExactly(getWorkerById, serviceWorkerId);
Expand All @@ -207,6 +209,52 @@ describe('McpContext', () => {
});
}
});

describe('getServiceWorkerConsoleMessageById', () => {
it('resolves the service worker ID to the collector extension ID', async () => {
const browser = createMockPuppeteerBrowser();
browser.targets.returns([]);
const context = await createConnectedMcpContext(
browser,
{
config: createMockServerConfig({
performanceCrux: false,
}),
heapSnapshotManager: new HeapSnapshotManager(new TaskRunner()),
},
Locator,
);
const worker = createMockMcpWorker({
id: 'sw-3',
url: 'chrome-extension://extension-id/background.js',
});
const getWorkerById = sinon
.stub(context, 'getWorkerById')
.returns(worker);
const message = Object.assign(
new UncaughtError(
{
exceptionId: 1,
text: 'Service worker error',
lineNumber: 0,
columnNumber: 0,
},
'extension-id',
),
{[stableIdSymbol]: 2},
);
const getById = sinon
.stub(ServiceWorkerConsoleCollector.prototype, 'getById')
.returns(message);

const result = context.getServiceWorkerConsoleMessageById('sw-3', 2);

sinon.assert.calledOnceWithExactly(getWorkerById, 'sw-3');
sinon.assert.calledOnceWithExactly(getById, 'extension-id', 2);
assert.strictEqual(result, message);
context.dispose();
});
});
it('list pages', async () => {
await withMcpContext(async (_response, context) => {
const page = context.getSelectedMcpPage();
Expand Down
25 changes: 25 additions & 0 deletions tests/McpResponse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -896,6 +896,31 @@ describe('McpResponse', () => {
});
});

it('reads an attached message from the service worker when serviceWorkerId is set', async () => {
const page = createMockMcpPage();
const context = createMockMcpContext({selectedPage: page});
const message = createMockConsoleMessage({
type: 'log',
text: 'logged by the service worker',
});
context.getServiceWorkerConsoleMessageById.returns(message);
const response = new McpResponse(createMockServerConfig());
response.setPage(page);
response.attachConsoleMessage(2, {serviceWorkerId: 'sw-1'});

const {content} = await response.handle(context);

sinon.assert.calledOnceWithExactly(
context.getServiceWorkerConsoleMessageById,
'sw-1',
2,
);
sinon.assert.notCalled(page.getConsoleMessageById);
assert.ok(
getTextContent(content[0]).includes('logged by the service worker'),
);
});

it("doesn't list the issue message if mapping returns null", async t => {
await withMcpContext(async (response, context) => {
const mockAggregatedIssue = getMockAggregatedIssue();
Expand Down
Loading