Skip to content

Commit aec5074

Browse files
authored
feat: fetch performance log entries in browser session logs resource (#176)
* feat: fetch performance log entries in browser session logs resource * feat: add opt-in networkLogs mode and failure filtering for performance logs * fix: validate WDIO_MCP_NETWORK_LOGS at startup and note unsupported sessions * test: update start_session networkLogs assertions for session options
1 parent 1345a7d commit aec5074

9 files changed

Lines changed: 331 additions & 53 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -712,6 +712,8 @@ Both tools require a `provider` parameter (`'browserstack'`, `'saucelabs'`, `'te
712712

713713
The server lists only the tools that fit the current session: browser sessions get the page tools below, mobile sessions the gestures and device tools, Electron sessions the Electron tools. Rarely used groups (mocks, cookies, device emulation, extensions, attaching, the raw element list, cloud app uploads) are listed after the agent calls `enable_tools`, so their definitions aren't sent with every request. With several live sessions, tools are listed for the union of their platforms. Set `WDIO_MCP_TOOLS=all` to list everything up front.
714714

715+
Set `WDIO_MCP_NETWORK_LOGS` to configure the default Chromium network/performance log capture mode for `start_session`: `none` (default, off), `failures` (`Network.loadingFailed` and `Network.responseReceived` entries with HTTP status `>= 400`), or `all` (every Chromium `performance` log entry). Individual sessions can override this default via `start_session({ networkLogs: 'none' | 'failures' | 'all' })`.
716+
715717
| Tool | Description |
716718
|----------------|-------------------------------------------------------------------------------------------------------------------|
717719
| `enable_tools` | Add a group of tools: `mocks`, `cookies`, `device`, `extensions`, `attach`, `elements`, `cloud-apps` |

‎src/providers/local-browser.provider.ts‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { SessionProvider, ConnectionConfig } from './types';
2+
import type { NetworkLogsMode } from '../session/state';
23

34
const BIDI_RESPONSE_TIMEOUT_MS = 30_000;
45
// Aborts hung classic commands natively and never replays a timed-out command; longer than the 30s action/BiDi timeouts.
@@ -11,6 +12,7 @@ export type LocalBrowserOptions = {
1112
windowWidth?: number;
1213
windowHeight?: number;
1314
capabilities?: Record<string, unknown>;
15+
networkLogs?: NetworkLogsMode;
1416
};
1517

1618
export class LocalBrowserProvider implements SessionProvider {
@@ -24,12 +26,13 @@ export class LocalBrowserProvider implements SessionProvider {
2426
};
2527
}
2628

27-
buildCapabilities(options: Record<string, unknown>): Record<string, unknown> {
28-
const selectedBrowser = (options.browser as string | undefined) ?? 'chrome';
29-
const headless = (options.headless as boolean | undefined) ?? true;
30-
const windowWidth = (options.windowWidth as number | undefined) ?? 1280;
31-
const windowHeight = (options.windowHeight as number | undefined) ?? 800;
32-
const userCapabilities = (options.capabilities as Record<string, unknown> | undefined) ?? {};
29+
buildCapabilities(options: LocalBrowserOptions): Record<string, unknown> {
30+
const selectedBrowser = options.browser ?? 'chrome';
31+
const headless = options.headless ?? true;
32+
const windowWidth = options.windowWidth ?? 1280;
33+
const windowHeight = options.windowHeight ?? 800;
34+
const userCapabilities = options.capabilities ?? {};
35+
const networkLogs = options.networkLogs ?? 'none';
3336

3437
const headlessSupported = selectedBrowser !== 'safari';
3538
const effectiveHeadless = headless && headlessSupported;
@@ -71,10 +74,16 @@ export class LocalBrowserProvider implements SessionProvider {
7174
case 'chrome':
7275
capabilities.browserName = 'chrome';
7376
capabilities['goog:chromeOptions'] = { args: chromiumArgs };
77+
if (networkLogs !== 'none') {
78+
capabilities['goog:loggingPrefs'] = { performance: 'ALL' };
79+
}
7480
break;
7581
case 'edge':
7682
capabilities.browserName = 'msedge';
7783
capabilities['ms:edgeOptions'] = { args: chromiumArgs };
84+
if (networkLogs !== 'none') {
85+
capabilities['ms:loggingPrefs'] = { performance: 'ALL' };
86+
}
7887
break;
7988
case 'firefox':
8089
capabilities.browserName = 'firefox';
@@ -91,7 +100,9 @@ export class LocalBrowserProvider implements SessionProvider {
91100
...capabilities,
92101
...userCapabilities,
93102
'goog:chromeOptions': this.mergeCapabilityOptions(capabilities['goog:chromeOptions'], userCapabilities['goog:chromeOptions']),
103+
'goog:loggingPrefs': this.mergeCapabilityOptions(capabilities['goog:loggingPrefs'], userCapabilities['goog:loggingPrefs']),
94104
'ms:edgeOptions': this.mergeCapabilityOptions(capabilities['ms:edgeOptions'], userCapabilities['ms:edgeOptions']),
105+
'ms:loggingPrefs': this.mergeCapabilityOptions(capabilities['ms:loggingPrefs'], userCapabilities['ms:loggingPrefs']),
95106
'moz:firefoxOptions': this.mergeCapabilityOptions(capabilities['moz:firefoxOptions'], userCapabilities['moz:firefoxOptions']),
96107
};
97108

‎src/resources/session-logs.resource.ts‎

Lines changed: 64 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { ResourceDefinition } from '../types/resource';
2-
import { getBrowser, getState } from '../session/state';
2+
import { getBrowser, getState, type NetworkLogsMode } from '../session/state';
33
import { activeSessionId } from '../session/context';
44

55
interface LogEntry {
@@ -14,15 +14,43 @@ interface SessionLogsResult {
1414
sessionType: string;
1515
logTypes: string[];
1616
entries: LogEntry[];
17+
errors?: string[];
18+
}
19+
20+
function isPerformanceFailureEntry(rawMessage: string): boolean {
21+
try {
22+
const parsed = JSON.parse(rawMessage) as {
23+
message?: { method?: string; params?: { response?: { status?: number } } };
24+
method?: string;
25+
params?: { response?: { status?: number } };
26+
};
27+
const cdpMessage = parsed?.message ?? parsed;
28+
if (cdpMessage?.method === 'Network.loadingFailed') {
29+
return true;
30+
}
31+
if (
32+
cdpMessage?.method === 'Network.responseReceived' &&
33+
typeof cdpMessage.params?.response?.status === 'number' &&
34+
cdpMessage.params.response.status >= 400
35+
) {
36+
return true;
37+
}
38+
return false;
39+
} catch {
40+
return false;
41+
}
1742
}
1843

1944
/**
2045
* Fetch logs appropriate to the current session type:
21-
* - browser: console logs + JS exceptions via getLogs('browser')
46+
* - browser: console logs + JS exceptions via getLogs('browser') and network/CDP events via getLogs('performance') (local Chromium only)
2247
* - android: system/crash logs via getLogs('logcat')
2348
* - ios: crash logs via getLogs('crashlog') + system logs via getLogs('syslog')
2449
*/
25-
async function fetchLogsForSession(sessionType: string): Promise<{ logTypes: string[]; entries: LogEntry[] }> {
50+
async function fetchLogsForSession(
51+
sessionType: string,
52+
networkLogs?: NetworkLogsMode,
53+
): Promise<{ logTypes: string[]; entries: LogEntry[]; errors?: string[] }> {
2654
const browser = getBrowser();
2755
const b = browser as unknown as Record<string, unknown>;
2856

@@ -34,19 +62,36 @@ async function fetchLogsForSession(sessionType: string): Promise<{ logTypes: str
3462

3563
switch (sessionType) {
3664
case 'browser': {
37-
// Console output + uncaught JS exceptions
38-
const logType = 'browser';
39-
if (availableTypes.includes(logType)) {
40-
const raw: Array<{ level: string; message: string; timestamp: number }> =
41-
await (b.getLogs as (t: string) => Promise<Array<{ level: string; message: string; timestamp: number }>>)(logType);
42-
entries.push(...raw.map((e) => ({
43-
level: e.level,
44-
message: e.message,
45-
timestamp: e.timestamp,
46-
timestampISO: new Date(e.timestamp).toISOString(),
47-
})));
65+
// Console output + uncaught JS exceptions + network/performance events
66+
const errors: string[] = [];
67+
let attempted = 0;
68+
let succeeded = 0;
69+
for (const logType of ['browser', 'performance']) {
70+
if (availableTypes.includes(logType)) {
71+
attempted++;
72+
try {
73+
const raw: Array<{ level: string; message: string; timestamp: number }> =
74+
await (b.getLogs as (t: string) => Promise<Array<{ level: string; message: string; timestamp: number }>>)(logType);
75+
const filtered = logType === 'performance' && networkLogs === 'failures'
76+
? raw.filter((e) => isPerformanceFailureEntry(e.message))
77+
: raw;
78+
entries.push(...filtered.map((e) => ({
79+
level: e.level,
80+
message: e.message,
81+
timestamp: e.timestamp,
82+
timestampISO: new Date(e.timestamp).toISOString(),
83+
source: logType,
84+
})));
85+
succeeded++;
86+
} catch (err) {
87+
errors.push(`${logType}: ${err instanceof Error ? err.message : String(err)}`);
88+
}
89+
}
4890
}
49-
return { logTypes: availableTypes, entries };
91+
if (attempted > 0 && succeeded === 0) {
92+
throw new Error(`All browser log types failed: ${errors.join('; ')}`);
93+
}
94+
return { logTypes: availableTypes, entries, ...(errors.length > 0 ? { errors } : {}) };
5095
}
5196

5297
case 'android': {
@@ -94,7 +139,7 @@ async function fetchLogsForSession(sessionType: string): Promise<{ logTypes: str
94139
if (attempted > 0 && succeeded === 0) {
95140
throw new Error(`All iOS log types failed: ${errors.join('; ')}`);
96141
}
97-
return { logTypes: availableTypes, entries };
142+
return { logTypes: availableTypes, entries, ...(errors.length > 0 ? { errors } : {}) };
98143
}
99144

100145
default:
@@ -108,12 +153,13 @@ export async function readSessionLogs(): Promise<{ mimeType: string; text: strin
108153
const metadata = state.sessionMetadata.get(activeSessionId() ?? '');
109154
const sessionType = metadata?.type ?? 'browser';
110155

111-
const { logTypes, entries } = await fetchLogsForSession(sessionType);
156+
const { logTypes, entries, errors } = await fetchLogsForSession(sessionType, metadata?.networkLogs);
112157

113158
const result: SessionLogsResult = {
114159
sessionType,
115160
logTypes,
116161
entries,
162+
...(errors ? { errors } : {}),
117163
};
118164

119165
return { mimeType: 'application/json', text: JSON.stringify(result) };
@@ -134,7 +180,7 @@ export async function readSessionLogs(): Promise<{ mimeType: string; text: strin
134180
export const sessionLogsResource: ResourceDefinition = {
135181
name: 'session-current-logs',
136182
uri: 'wdio://session/current/logs',
137-
description: 'Session logs, console errors, and crash reports for the current session. Auto-detects session type — browser: console logs + JS exceptions via getLogs(\'browser\'); Android: system/crash logs via getLogs(\'logcat\'); iOS: crash/panic + system logs via getLogs(\'crashlog\') and getLogs(\'syslog\'). NOTE: Reading this resource clears the log buffer per protocol spec — subsequent reads return only entries accumulated since the last read. Browser logs require Chromium (Chrome/Edge).',
183+
description: 'Session logs, console errors, network performance events, and crash reports for the current session. Auto-detects session type — browser: console logs + JS exceptions via getLogs(\'browser\') and network/performance events via getLogs(\'performance\') (local Chromium only); Android: system/crash logs via getLogs(\'logcat\'); iOS: crash/panic + system logs via getLogs(\'crashlog\') and getLogs(\'syslog\'). NOTE: Reading this resource clears the log buffer per protocol spec — subsequent reads return only entries accumulated since the last read. Browser logs require Chromium (Chrome/Edge).',
138184
handler: async () => {
139185
const result = await readSessionLogs();
140186
return {

‎src/server.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,8 @@ import {
7575
attachSessionToolDefinition,
7676
closeSessionTool,
7777
closeSessionToolDefinition,
78-
startSessionTool,
78+
createStartSessionTool,
79+
parseNetworkLogsMode,
7980
startSessionToolDefinition
8081
} from './tools/session.tool';
8182
import { switchTabTool, switchTabToolDefinition } from './tools/tabs.tool';
@@ -101,6 +102,7 @@ console.info = (...args) => console.error('[INFO]', ...args);
101102
console.warn = (...args) => console.error('[WARN]', ...args);
102103
console.debug = (...args) => console.error('[DEBUG]', ...args);
103104

105+
const defaultNetworkLogs = parseNetworkLogsMode(process.env.WDIO_MCP_NETWORK_LOGS);
104106
const SESSION_TARGET_SCHEMA = z.string().optional().describe('Target session: map name or sessionId. Omit to use the default session.');
105107

106108
function createServer(): McpServer {
@@ -157,7 +159,7 @@ function createServer(): McpServer {
157159
const instrument = (name: string, cb: ToolCallback): ToolCallback =>
158160
withTrace(name, withRecording(name, cb));
159161

160-
registerTool(startSessionToolDefinition, withRecording('start_session', startSessionTool));
162+
registerTool(startSessionToolDefinition, withRecording('start_session', createStartSessionTool(defaultNetworkLogs)));
161163
registerTool(attachSessionToolDefinition, attachSessionRecorded);
162164
registerTool(closeSessionToolDefinition, closeSessionTool);
163165
registerTool(launchChromeToolDefinition, instrument('launch_chrome', launchChromeTool));

‎src/session/state.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import { activeSessionId } from './context';
22
import type { SessionHistory } from '../types/recording';
33
import type { ToolGroup, ToolPlatform } from '../toolsets';
44

5+
export type NetworkLogsMode = 'none' | 'failures' | 'all';
6+
57
export interface SessionMetadata {
68
type: 'browser' | 'ios' | 'android';
79
/** Browser sessions can have a specialised lifecycle while retaining renderer semantics. */
@@ -15,6 +17,7 @@ export interface SessionMetadata {
1517
tunnelName?: string;
1618
tunnelHandle?: unknown;
1719
trace?: boolean;
20+
networkLogs?: NetworkLogsMode;
1821
/** The remote session lifecycle is owned outside this MCP process. */
1922
externallyManaged?: boolean;
2023
name?: string;

0 commit comments

Comments
 (0)