Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
feat(mcp): refactor network into requests + request commands (#40447)
Yury Semikhatsky78a77a70d99c
diff --git a/docs/src/getting-started-cli.md b/docs/src/getting-started-cli.mdindex 272f93a94a..3b6fb9bf90 100644--- a/docs/src/getting-started-cli.md+++ b/docs/src/getting-started-cli.md@@ -164,7 +164,8 @@ playwright-cli tab-close [index] # close a tab### Network```bash-playwright-cli network # list network requests since page load+playwright-cli requests # list network requests since page load+playwright-cli request <num> # show full details of a single requestplaywright-cli route <pattern> [opts] # mock network requestsplaywright-cli route-list # list active routesplaywright-cli unroute [pattern] # remove routesdiff --git a/packages/isomorphic/mimeType.ts b/packages/isomorphic/mimeType.tsindex b58bd543bb..ebe47d82ea 100644--- a/packages/isomorphic/mimeType.ts+++ b/packages/isomorphic/mimeType.ts@@ -33,6 +33,21 @@ export function getMimeTypeForPath(path: string): string | null {return types.get(extension) || null;}+export function getExtensionForMimeType(contentType: string | undefined): string {+ const subtype = (contentType ?? '').split(';')[0].split('/')[1]?.trim().toLowerCase() ?? '';+ if (!subtype)+ return 'bin';+ // image/svg+xml → xml, application/ld+json → json+ const tail = subtype.includes('+') ? subtype.split('+').pop()! : subtype;+ if (tail === 'plain')+ return 'txt';+ if (tail === 'javascript' || tail === 'ecmascript')+ return 'js';+ if (tail === 'jpeg')+ return 'jpg';+ return tail.replace(/[^a-z0-9]/g, '') || 'bin';+}+const types: Map<string, string> = new Map([['ez', 'application/andrew-inset'],['aw', 'application/applixware'],diff --git a/packages/playwright-core/src/tools/backend/network.ts b/packages/playwright-core/src/tools/backend/network.tsindex 724edbaf51..ab52fde11b 100644--- a/packages/playwright-core/src/tools/backend/network.ts+++ b/packages/playwright-core/src/tools/backend/network.ts@@ -14,9 +14,15 @@* limitations under the License.*/+import fs from 'fs';+import * as z from 'zod';++import { getExtensionForMimeType, isTextualMimeType } from '@isomorphic/mimeType';+import { defineTool, defineTabTool } from './tool';+import type { Response as ToolResponse } from './response';import type * as playwright from '../../..';const requests = defineTabTool({@@ -25,11 +31,9 @@ const requests = defineTabTool({schema: {name: 'browser_network_requests',title: 'List network requests',- description: 'Returns all network requests since loading the page',+ description: 'Returns a numbered list of network requests since loading the page. Use browser_network_request with the number to get full details.',inputSchema: z.object({static: z.boolean().default(false).describe('Whether to include successful static resources like images, fonts, scripts, etc. Defaults to false.'),- requestBody: z.boolean().default(false).describe('Whether to include request body. Defaults to false.'),- requestHeaders: z.boolean().default(false).describe('Whether to include request headers. Defaults to false.'),filter: z.string().optional().describe('Only return requests whose URL matches this regexp (e.g. "/api/.*user").'),filename: z.string().optional().describe('Filename to save the network requests to. If not provided, requests are returned as text.'),}),@@ -37,10 +41,11 @@ const requests = defineTabTool({},handle: async (tab, params, response) => {- const requests = await tab.requests();+ const allRequests = await tab.requests();const filter = params.filter ? new RegExp(params.filter) : undefined;- const text: string[] = [];- for (const request of requests) {+ const lines: string[] = [];+ for (let i = 0; i < allRequests.length; i++) {+ const request = allRequests[i];if (!params.static && !isFetch(request) && isSuccessfulResponse(request))continue;if (filter) {@@ -48,9 +53,44 @@ const requests = defineTabTool({if (!filter.test(request.url()))continue;}- text.push(await renderRequest(request, params.requestBody, params.requestHeaders));+ lines.push(`${i + 1}. ${renderRequestLine(request)}`);}- await response.addResult('Network', text.join('\n'), { prefix: 'network', ext: 'log', suggestedFilename: params.filename });+ await response.addResult('Network', lines.join('\n'), { prefix: 'network', ext: 'log', suggestedFilename: params.filename });+ },+});++const REQUEST_PARTS = ['request-headers', 'request-body', 'response-headers', 'response-body'] as const;+type RequestPart = typeof REQUEST_PARTS[number];++const request = defineTabTool({+ capability: 'core',++ schema: {+ name: 'browser_network_request',+ title: 'Show network request details',+ description: 'Returns full details (headers and body) of a single network request, or a single part if `part` is set. Use the number from browser_network_requests.',+ inputSchema: z.object({+ index: z.number().int().min(1).describe('1-based index of the request, as printed by browser_network_requests.'),+ part: z.enum(REQUEST_PARTS).optional().describe('Return only this part of the request. Omit to return full details.'),+ }),+ type: 'readOnly',+ },++ handle: async (tab, params, response) => {+ const allRequests = await tab.requests();+ const request = allRequests[params.index - 1];+ if (!request) {+ response.addError(`Request #${params.index} not found. Use browser_network_requests to see available indexes.`);+ return;+ }+ if (params.part) {+ const partText = await renderRequestPart(request, params.part, response);+ if (partText !== undefined)+ response.addTextResult(partText);+ return;+ }+ const bodyPath = await saveResponseBody(request, response);+ response.addTextResult(renderRequestDetails(params.index, request, bodyPath));},});@@ -80,27 +120,120 @@ export function isFetch(request: playwright.Request): boolean {return ['fetch', 'xhr'].includes(request.resourceType());}-export async function renderRequest(request: playwright.Request, includeBody = false, includeHeaders = false): Promise<string> {+export function renderRequestLine(request: playwright.Request): string {const response = request.existingResponse();-- const result: string[] = [];- result.push(`[${request.method().toUpperCase()}] ${request.url()}`);+ let line = `[${request.method().toUpperCase()}] ${request.url()}`;if (response)- result.push(` => [${response.status()}] ${response.statusText()}`);+ line += ` => [${response.status()}] ${response.statusText()}`;else if (request.failure())- result.push(` => [FAILED] ${request.failure()?.errorText ?? 'Unknown error'}`);- if (includeHeaders) {- const headers = request.headers();- const headerLines = Object.entries(headers).map(([k, v]) => ` ${k}: ${v}`).join('\n');- if (headerLines)- result.push(`\n Request headers:\n${headerLines}`);+ line += ` => [FAILED] ${request.failure()?.errorText ?? 'Unknown error'}`;+ return line;+}++function renderRequestDetails(index: number, request: playwright.Request, responseBodyPath: string | undefined): string {+ const httpResponse = request.existingResponse();+ const responseHeaders = httpResponse?.headers();+ const lines: string[] = [];+ lines.push(`#${index} [${request.method().toUpperCase()}] ${request.url()}`);++ lines.push('');+ lines.push(' General');+ if (httpResponse)+ lines.push(` status: [${httpResponse.status()}] ${httpResponse.statusText()}`);+ else if (request.failure())+ lines.push(` status: [FAILED] ${request.failure()?.errorText ?? 'Unknown error'}`);+ const duration = computeDurationMs(request);+ if (duration !== undefined)+ lines.push(` duration: ${duration}ms`);+ lines.push(` type: ${request.resourceType()}`);+ const contentType = responseHeaders?.['content-type'];+ if (contentType)+ lines.push(` mimeType: ${contentType.split(';')[0].trim()}`);++ appendHeaderSection(lines, 'Request headers', request.headers());++ const postData = request.postData();+ if (postData) {+ lines.push('');+ lines.push(' Request body');+ lines.push(` ${postData}`);+ }++ if (responseHeaders)+ appendHeaderSection(lines, 'Response headers', responseHeaders);++ if (responseBodyPath) {+ lines.push('');+ lines.push(' Response body');+ lines.push(` ${responseBodyPath}`);+ }++ return lines.join('\n');+}++function appendHeaderSection(lines: string[], title: string, headers: Record<string, string>): void {+ const entries = Object.entries(headers);+ if (!entries.length)+ return;+ lines.push('');+ lines.push(` ${title}`);+ for (const [k, v] of entries)+ lines.push(` ${k}: ${v}`);+}++function computeDurationMs(request: playwright.Request): number | undefined {+ const timing = request.timing();+ if (!timing || timing.responseEnd < 0)+ return undefined;+ return Math.round(timing.responseEnd);+}++async function renderRequestPart(request: playwright.Request, part: RequestPart, response: ToolResponse): Promise<string | undefined> {+ if (part === 'request-headers')+ return renderHeaders(request.headers());+ if (part === 'request-body')+ return request.postData() ?? undefined;+ const httpResponse = request.existingResponse();+ if (!httpResponse)+ return undefined;+ if (part === 'response-headers')+ return renderHeaders(httpResponse.headers());+ // response-body+ const contentType = httpResponse.headers()['content-type'];+ if (isTextualMimeType(contentType ?? '')) {+ try {+ return await httpResponse.text();+ } catch {+ return undefined;+ }}- if (includeBody) {- const postData = request.postData();- if (postData)- result.push(`\n Request body: ${postData}`);+ return await saveResponseBody(request, response);+}++function renderHeaders(headers: Record<string, string>): string {+ return Object.entries(headers).map(([k, v]) => `${k}: ${v}`).join('\n');+}++async function saveResponseBody(request: playwright.Request, response: ToolResponse): Promise<string | undefined> {+ const httpResponse = request.existingResponse();+ if (!httpResponse)+ return undefined;+ const status = httpResponse.status();+ // Status codes that cannot have a response body per RFC 7230.+ if (status === 204 || status === 304 || (status >= 100 && status < 200))+ return undefined;+ let body: Buffer;+ try {+ body = await httpResponse.body();+ } catch {+ return undefined;}- return result.join('');+ if (!body.length)+ return undefined;+ const ext = getExtensionForMimeType(httpResponse.headers()['content-type']);+ const resolved = await response.resolveClientFile({ prefix: 'response', ext }, 'Response body');+ await fs.promises.writeFile(resolved.fileName, body);+ return resolved.relativeName;}const networkStateSet = defineTool({@@ -127,6 +260,7 @@ const networkStateSet = defineTool({export default [requests,+ request,networkClear,networkStateSet,];diff --git a/packages/playwright-core/src/tools/cli-client/skill/SKILL.md b/packages/playwright-core/src/tools/cli-client/skill/SKILL.mdindex bde0b60004..6640c860d1 100644--- a/packages/playwright-core/src/tools/cli-client/skill/SKILL.md+++ b/packages/playwright-core/src/tools/cli-client/skill/SKILL.md@@ -153,7 +153,8 @@ playwright-cli unroute```bashplaywright-cli consoleplaywright-cli console warning-playwright-cli network+playwright-cli requests+playwright-cli request 5playwright-cli run-code "async page => await page.context().grantPermissions(['geolocation'])"playwright-cli run-code --filename=script.jsplaywright-cli tracing-start@@ -351,7 +352,7 @@ playwright-cli open https://example.complaywright-cli click e4playwright-cli fill e7 "test"playwright-cli console-playwright-cli network+playwright-cli requestsplaywright-cli close```diff --git a/packages/playwright-core/src/tools/cli-daemon/commands.ts b/packages/playwright-core/src/tools/cli-daemon/commands.tsindex a83d53ddf2..bff12ee430 100644--- a/packages/playwright-core/src/tools/cli-daemon/commands.ts+++ b/packages/playwright-core/src/tools/cli-daemon/commands.ts@@ -815,19 +815,72 @@ const consoleList = declareCommand({});const networkRequests = declareCommand({- name: 'network',- description: 'List all network requests since loading the page',- category: 'devtools',+ name: 'requests',+ description: 'List all network requests since loading the page. Each request is numbered for use with the `request` command.',+ category: 'network',args: z.object({}),options: z.object({static: z.boolean().optional().describe('Whether to include successful static resources like images, fonts, scripts, etc. Defaults to false.'),- ['request-body']: z.boolean().optional().describe('Whether to include request body. Defaults to false.'),- ['request-headers']: z.boolean().optional().describe('Whether to include request headers. Defaults to false.'),filter: z.string().optional().describe('Only return requests whose URL matches this regexp (e.g. "/api/.*user").'),clear: z.boolean().optional().describe('Whether to clear the network list'),}),toolName: ({ clear }) => clear ? 'browser_network_clear' : 'browser_network_requests',- toolParams: ({ static: s, 'request-body': requestBody, 'request-headers': requestHeaders, filter, clear }) => clear ? ({}) : ({ static: s, requestBody, requestHeaders, filter }),+ toolParams: ({ static: s, filter, clear }) => clear ? ({}) : ({ static: s, filter }),+});++const networkRequest = declareCommand({+ name: 'request',+ description: 'Show full details (headers, body, response) of a single network request by its number from the `requests` command.',+ category: 'network',+ args: z.object({+ index: numberArg.describe('1-based number of the request as listed by `requests`'),+ }),+ toolName: 'browser_network_request',+ toolParams: ({ index }) => ({ index }),+});++const networkRequestHeaders = declareCommand({+ name: 'request-headers',+ description: 'Print only the request headers for a single network request by its number from the `requests` command.',+ category: 'network',+ args: z.object({+ index: numberArg.describe('1-based number of the request as listed by `requests`'),+ }),+ toolName: 'browser_network_request',+ toolParams: ({ index }) => ({ index, part: 'request-headers' }),+});++const networkRequestBody = declareCommand({+ name: 'request-body',+ description: 'Print only the request body for a single network request by its number from the `requests` command.',+ category: 'network',+ args: z.object({+ index: numberArg.describe('1-based number of the request as listed by `requests`'),+ }),+ toolName: 'browser_network_request',+ toolParams: ({ index }) => ({ index, part: 'request-body' }),+});++const networkResponseHeaders = declareCommand({+ name: 'response-headers',+ description: 'Print only the response headers for a single network request by its number from the `requests` command.',+ category: 'network',+ args: z.object({+ index: numberArg.describe('1-based number of the request as listed by `requests`'),+ }),+ toolName: 'browser_network_request',+ toolParams: ({ index }) => ({ index, part: 'response-headers' }),+});++const networkResponseBody = declareCommand({+ name: 'response-body',+ description: 'Print the response body for a single network request by its number from the `requests` command. Textual bodies are inlined; binary bodies are saved to a file and the path is printed.',+ category: 'network',+ args: z.object({+ index: numberArg.describe('1-based number of the request as listed by `requests`'),+ }),+ toolName: 'browser_network_request',+ toolParams: ({ index }) => ({ index, part: 'response-body' }),});const tracingStart = declareCommand({@@ -1092,6 +1145,12 @@ const commandsArray: AnyCommandSchema[] = [sessionStorageClear,// network category+ networkRequests,+ networkRequest,+ networkRequestHeaders,+ networkRequestBody,+ networkResponseHeaders,+ networkResponseBody,routeMock,routeList,unroute,@@ -1105,7 +1164,6 @@ const commandsArray: AnyCommandSchema[] = [installBrowser,// devtools category- networkRequests,tracingStart,tracingStop,videoStart,diff --git a/packages/playwright/src/agents/playwright-test-healer.agent.md b/packages/playwright/src/agents/playwright-test-healer.agent.mdindex 97acadceae..79d5a94b05 100644--- a/packages/playwright/src/agents/playwright-test-healer.agent.md+++ b/packages/playwright/src/agents/playwright-test-healer.agent.md@@ -9,6 +9,7 @@ tools:- playwright-test/browser_console_messages- playwright-test/browser_evaluate- playwright-test/browser_generate_locator+ - playwright-test/browser_network_request- playwright-test/browser_network_requests- playwright-test/browser_snapshot- playwright-test/test_debugdiff --git a/packages/playwright/src/agents/playwright-test-planner.agent.md b/packages/playwright/src/agents/playwright-test-planner.agent.mdindex 4ff02c115a..801dda573d 100644--- a/packages/playwright/src/agents/playwright-test-planner.agent.md+++ b/packages/playwright/src/agents/playwright-test-planner.agent.md@@ -15,6 +15,7 @@ tools:- playwright-test/browser_hover- playwright-test/browser_navigate- playwright-test/browser_navigate_back+ - playwright-test/browser_network_request- playwright-test/browser_network_requests- playwright-test/browser_press_key- playwright-test/browser_run_codediff --git a/tests/mcp/capabilities.spec.ts b/tests/mcp/capabilities.spec.tsindex 6f5442bb61..d99d401e2a 100644--- a/tests/mcp/capabilities.spec.ts+++ b/tests/mcp/capabilities.spec.ts@@ -33,6 +33,7 @@ test('test snapshot tool list', async ({ client }) => {'browser_close','browser_navigate_back','browser_navigate',+ 'browser_network_request','browser_network_requests','browser_press_key','browser_resize',diff --git a/tests/mcp/cli-devtools.spec.ts b/tests/mcp/cli-devtools.spec.tsindex fdd40636d7..06118a49bf 100644--- a/tests/mcp/cli-devtools.spec.ts+++ b/tests/mcp/cli-devtools.spec.ts@@ -45,81 +45,144 @@ test('console --clear', async ({ cli, server }) => {expect(output).not.toContain('log-level');});-test('network', async ({ cli, server }) => {+test('requests', async ({ cli, server }) => {await cli('open', server.PREFIX);await cli('eval', '() => fetch("/hello-world")');- const { output } = await cli('network');+ const { output } = await cli('requests');expect(output).not.toContain(`[GET] ${`${server.PREFIX}/`} => [200] OK`);- expect(output).toContain(`[GET] ${`${server.PREFIX}/hello-world`} => [200] OK`);+ expect(output).toMatch(new RegExp(String.raw`^\d+\. \[GET\] ${escapeRegExp(`${server.PREFIX}/hello-world`)} => \[200\] OK$`, 'm'));});-test('network --static', async ({ cli, server }) => {+test('requests --static', async ({ cli, server }) => {await cli('open', server.PREFIX);- const { output } = await cli('network', '--static');- expect(output).toContain(`[GET] ${`${server.PREFIX}/`} => [200] OK`);+ const { output } = await cli('requests', '--static');+ expect(output).toMatch(new RegExp(String.raw`^\d+\. \[GET\] ${escapeRegExp(`${server.PREFIX}/`)} => \[200\] OK$`, 'm'));});-test('network --filter', async ({ cli, server }) => {+test('requests --filter', async ({ cli, server }) => {server.setContent('/', `<script>Promise.all([fetch('/api/users'), fetch('/api/orders'), fetch('/static/image.png')]);</script>`, 'text/html');await cli('open', server.PREFIX);- const { output } = await cli('network', '--filter=/api/', '--static');+ const { output } = await cli('requests', '--filter=/api/', '--static');expect(output).toContain(`${server.PREFIX}/api/users`);expect(output).toContain(`${server.PREFIX}/api/orders`);expect(output).not.toContain(`${server.PREFIX}/static/image.png`);});-test('network --request-body', async ({ cli, server }) => {+test('requests --clear', async ({ cli, server }) => {+ await cli('open', server.PREFIX);+ await cli('eval', '() => fetch("/hello-world")');+ await cli('requests', '--clear');+ const { output } = await cli('requests');+ expect(output).not.toContain(`${server.PREFIX}/hello-world`);+});++test('request shows full request and response details', async ({ cli, server }) => {+ server.setContent('/', `+ <button onclick="fetch('/api', { method: 'POST', headers: { 'X-Custom-Header': 'test-value' }, body: JSON.stringify({ key: 'value' }) })">Click me</button>+ `, 'text/html');+ server.setRoute('/api', (_req, res) => {+ res.setHeader('X-Custom-Response', 'response-value');+ res.setHeader('Content-Type', 'application/json');+ res.end(JSON.stringify({ name: 'John Doe' }));+ });+ await cli('open', server.PREFIX);+ await cli('click', 'e2');++ const { output: list } = await cli('requests');+ const match = list.match(/^(\d+)\. \[POST\] [^ ]+\/api =>/m);+ expect(match).not.toBeNull();++ const { output } = await cli('request', match![1]);+ expect(output).toContain(`#${match![1]} [POST] ${server.PREFIX}/api`);+ expect(output).toContain('General');+ expect(output).toContain('status: [200] OK');+ expect(output).toContain('Request headers');+ expect(output).toContain('x-custom-header: test-value');+ expect(output).toContain('Request body');+ expect(output).toContain('{"key":"value"}');+ expect(output).toContain('Response headers');+ expect(output).toContain('x-custom-response: response-value');+ const bodyMatch = output.match(/Response body\n\s+(\S+\.json)/);+ expect(bodyMatch).not.toBeNull();+ const bodyPath = path.resolve(test.info().outputPath(), bodyMatch![1]);+ expect(fs.readFileSync(bodyPath, 'utf-8')).toBe('{"name":"John Doe"}');+});++test('request saves binary response body to a file', async ({ cli, server }) => {+ const pngBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);server.setContent('/', `- <button onclick="fetch('/api', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'value' }) })">Click me</button>+ <button onclick="fetch('/image.png')">Click me</button>`, 'text/html');- server.setContent('/api', '{}', 'application/json');+ server.setRoute('/image.png', (_req, res) => {+ res.setHeader('Content-Type', 'image/png');+ res.end(pngBytes);+ });await cli('open', server.PREFIX);await cli('click', 'e2');- {- const { output } = await cli('network');- expect(output).not.toContain('Request body:');- }+ const { output: list } = await cli('requests', '--static');+ const match = list.match(/^(\d+)\. \[GET\] [^ ]+\/image\.png =>/m);+ expect(match).not.toBeNull();- {- const { output } = await cli('network', '--request-body');- expect(output).toContain(`[POST] ${server.PREFIX}/api => [200] OK`);- expect(output).toContain('Request body: {"key":"value"}');- }+ const { output } = await cli('request', match![1]);+ const bodyMatch = output.match(/Response body\n\s+(\S+\.png)/);+ expect(bodyMatch).not.toBeNull();+ const bodyPath = path.resolve(test.info().outputPath(), bodyMatch![1]);+ expect(fs.readFileSync(bodyPath)).toEqual(pngBytes);});-test('network --request-headers', async ({ cli, server }) => {+test('per-part commands extract individual parts', async ({ cli, server }) => {server.setContent('/', `- <button onclick="fetch('/api', { headers: { 'X-Custom-Header': 'test-value' } })">Click me</button>+ <button onclick="fetch('/api', { method: 'POST', headers: { 'X-Custom-Header': 'test-value' }, body: JSON.stringify({ key: 'value' }) })">Click me</button>`, 'text/html');- server.setContent('/api', '{}', 'application/json');+ server.setRoute('/api', (_req, res) => {+ res.setHeader('X-Custom-Response', 'response-value');+ res.setHeader('Content-Type', 'application/json');+ res.end(JSON.stringify({ name: 'John Doe' }));+ });await cli('open', server.PREFIX);await cli('click', 'e2');- {- const { output } = await cli('network');- expect(output).not.toContain('Request headers:');- }+ const { output: list } = await cli('requests');+ const match = list.match(/^(\d+)\. \[POST\] [^ ]+\/api =>/m);+ expect(match).not.toBeNull();+ const num = match![1];- {- const { output } = await cli('network', '--request-headers');- expect(output).toContain(`[GET] ${server.PREFIX}/api => [200] OK`);- expect(output).toContain('Request headers:');- expect(output).toContain('x-custom-header: test-value');- }+ expect((await cli('request-headers', num)).output).toContain('x-custom-header: test-value');+ expect((await cli('request-body', num)).output).toContain('{"key":"value"}');+ expect((await cli('response-headers', num)).output).toContain('x-custom-response: response-value');+ expect((await cli('response-body', num)).output).toContain('{"name":"John Doe"}');});-test('network --clear', async ({ cli, server }) => {+test('--raw response-body returns just the body', async ({ cli, server }) => {+ server.setContent('/', `+ <button onclick="fetch('/api')">Click me</button>+ `, 'text/html');+ server.setContent('/api', JSON.stringify({ name: 'John Doe' }), 'application/json');await cli('open', server.PREFIX);- await cli('eval', '() => fetch("/hello-world")');- await cli('network', '--clear');- const { output } = await cli('network');- expect(output).not.toContain(`[GET] ${`${server.PREFIX}/hello-world`} => [200] OK`);+ await cli('click', 'e2');++ const { output: list } = await cli('requests');+ const match = list.match(/^(\d+)\. \[GET\] [^ ]+\/api =>/m);+ expect(match).not.toBeNull();++ const { output } = await cli('--raw', 'response-body', match![1]);+ expect(output.trim()).toBe('{"name":"John Doe"}');+});++test('request with out-of-range index', async ({ cli, server }) => {+ await cli('open', server.PREFIX);+ const { output } = await cli('request', '999');+ expect(output).toContain('Request #999 not found');});+function escapeRegExp(text: string): string {+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}+test('tracing-start-stop', async ({ cli, server }, testInfo) => {await cli('open', server.HELLO_WORLD);const { output } = await cli('tracing-start');diff --git a/tests/mcp/cli-json.spec.ts b/tests/mcp/cli-json.spec.tsindex c6bdfab3f7..10a19be048 100644--- a/tests/mcp/cli-json.spec.ts+++ b/tests/mcp/cli-json.spec.ts@@ -179,3 +179,47 @@ test('close-all after open returns closed sessions', async ({ cli, server }) =>const { output } = await cli('--json', 'close-all');expect(JSON.parse(output)).toEqual({ closed: ['default'] });});++test('requests returns numbered list as JSON result', async ({ cli, server }) => {+ await cli('open', server.PREFIX);+ await cli('eval', '() => fetch("/hello-world")');+ const { output } = await cli('--json', 'requests');+ const parsed = JSON.parse(output);+ expect(typeof parsed.result).toBe('string');+ expect(parsed.result).toMatch(new RegExp(String.raw`^\d+\. \[GET\] [^ ]+/hello-world => \[200\] OK$`, 'm'));+});++test('request and per-part commands return JSON result', async ({ cli, server }) => {+ server.setContent('/', `+ <button onclick="fetch('/api', { method: 'POST', headers: { 'X-Custom-Header': 'test-value' }, body: JSON.stringify({ key: 'value' }) })">Click me</button>+ `, 'text/html');+ server.setRoute('/api', (_req, res) => {+ res.setHeader('X-Custom-Response', 'response-value');+ res.setHeader('Content-Type', 'application/json');+ res.end(JSON.stringify({ name: 'John Doe' }));+ });+ await cli('open', server.PREFIX);+ await cli('click', 'e2');++ const { output: list } = await cli('requests');+ const num = list.match(/^(\d+)\. \[POST\] [^ ]+\/api =>/m)![1];++ console.error(list);++ expect(JSON.parse((await cli('--json', 'request-headers', num)).output).result).toContain('x-custom-header: test-value');+ expect(JSON.parse((await cli('--json', 'request-body', num)).output)).toEqual({ result: '{"key":"value"}' });+ expect(JSON.parse((await cli('--json', 'response-headers', num)).output).result).toContain('x-custom-response: response-value');+ expect(JSON.parse((await cli('--json', 'response-body', num)).output)).toEqual({ result: '{"name":"John Doe"}' });++ const detail = JSON.parse((await cli('--json', 'request', num)).output);+ expect(detail.result).toContain(`#${num} [POST] ${server.PREFIX}/api`);+ expect(detail.result).toContain('Response body');+});++test('request with out-of-range index returns JSON error', async ({ cli, server }) => {+ await cli('open', server.PREFIX);+ const { output } = await cli('--json', 'request', '999');+ const parsed = JSON.parse(output);+ expect(parsed.isError).toBe(true);+ expect(parsed.error).toContain('Request #999 not found');+});diff --git a/tests/mcp/network.spec.ts b/tests/mcp/network.spec.tsindex 00a0129694..a215232538 100644--- a/tests/mcp/network.spec.ts+++ b/tests/mcp/network.spec.ts@@ -14,6 +14,9 @@* limitations under the License.*/+import fs from 'fs';+import path from 'path';+import { test, expect, parseResponse } from './fixtures';test('browser_network_requests', async ({ client, server }) => {@@ -44,8 +47,8 @@ test('browser_network_requests', async ({ client, server }) => {name: 'browser_network_requests',}));expect(response.result).not.toContain(`[GET] ${`${server.PREFIX}/`} => [200] OK`);- expect(response.result).toContain(`[GET] ${`${server.PREFIX}/json`} => [200] OK`);- expect(response.result).toContain(`[GET] ${`${server.PREFIX}/image.png`} => [404]`);+ expect(response.result).toMatch(new RegExp(String.raw`^\d+\. \[GET\] ${escapeRegExp(`${server.PREFIX}/json`)} => \[200\] OK$`, 'm'));+ expect(response.result).toMatch(new RegExp(String.raw`^\d+\. \[GET\] ${escapeRegExp(`${server.PREFIX}/image.png`)} => \[404\]`, 'm'));}{@@ -55,9 +58,9 @@ test('browser_network_requests', async ({ client, server }) => {static: true,},}));- expect(response.result).toContain(`[GET] ${`${server.PREFIX}/`} => [200] OK`);- expect(response.result).toContain(`[GET] ${`${server.PREFIX}/json`} => [200] OK`);- expect(response.result).toContain(`[GET] ${`${server.PREFIX}/image.png`} => [404]`);+ expect(response.result).toMatch(new RegExp(String.raw`^\d+\. \[GET\] ${escapeRegExp(`${server.PREFIX}/`)} => \[200\] OK$`, 'm'));+ expect(response.result).toMatch(new RegExp(String.raw`^\d+\. \[GET\] ${escapeRegExp(`${server.PREFIX}/json`)} => \[200\] OK$`, 'm'));+ expect(response.result).toMatch(new RegExp(String.raw`^\d+\. \[GET\] ${escapeRegExp(`${server.PREFIX}/image.png`)} => \[404\]`, 'm'));}});@@ -82,11 +85,38 @@ test('browser_network_requests filter', async ({ client, server }) => {}});-test('browser_network_requests includes request headers', async ({ client, server }) => {+test('browser_network_requests numbers requests with stable indexes', async ({ client, server }) => {+ server.setContent('/', `<script>+ (async () => {+ await fetch('/api/users');+ await fetch('/api/orders');+ })();+ </script>`, 'text/html');++ await client.callTool({+ name: 'browser_navigate',+ arguments: { url: server.PREFIX },+ });++ // Index assignment is stable across calls — the same request keeps the same number.+ const response = parseResponse(await client.callTool({+ name: 'browser_network_requests',+ arguments: { static: true },+ }));+ const lines = response.result.split('\n').filter(Boolean);+ expect(lines[0]).toMatch(/^1\. \[GET\] /);+ expect(lines).toHaveLength(3);+});++test('browser_network_request shows full request and response details', async ({ client, server }) => {server.setContent('/', `- <button onclick="fetch('/api', { headers: { 'X-Custom-Header': 'test-value' } })">Click me</button>+ <button onclick="fetch('/api', { method: 'POST', headers: { 'X-Custom-Header': 'test-value' }, body: JSON.stringify({ key: 'value' }) })">Click me</button>`, 'text/html');- server.setContent('/api', '{}', 'application/json');+ server.setRoute('/api', (_req, res) => {+ res.setHeader('X-Custom-Response', 'response-value');+ res.setHeader('Content-Type', 'application/json');+ res.end(JSON.stringify({ name: 'John Doe' }));+ });await client.callTool({name: 'browser_navigate',@@ -98,60 +128,197 @@ test('browser_network_requests includes request headers', async ({ client, servearguments: { element: 'Click me button', target: 'e2' },});- {- const response = parseResponse(await client.callTool({- name: 'browser_network_requests',- }));- expect(response.result).not.toContain('Request headers:');- }+ // Find the index of the /api request from the listing.+ const list = parseResponse(await client.callTool({+ name: 'browser_network_requests',+ }));+ const match = list.result.match(/^(\d+)\. \[POST\] [^ ]+\/api =>/m);+ expect(match).not.toBeNull();+ const index = Number(match![1]);- {- const response = parseResponse(await client.callTool({- name: 'browser_network_requests',- arguments: { requestHeaders: true },- }));- expect(response.result).toContain(`[GET] ${server.PREFIX}/api => [200] OK`);- expect(response.result).toContain('Request headers:');- expect(response.result).toContain('x-custom-header: test-value');- }+ const detail = parseResponse(await client.callTool({+ name: 'browser_network_request',+ arguments: { index },+ }));+ expect(detail.result).toContain(`#${index} [POST] ${server.PREFIX}/api`);+ expect(detail.result).toContain('General');+ expect(detail.result).toContain('status: [200] OK');+ expect(detail.result).toContain('mimeType: application/json');+ expect(detail.result).toContain('Request headers');+ expect(detail.result).toContain('x-custom-header: test-value');+ expect(detail.result).toContain('Request body');+ expect(detail.result).toContain('{"key":"value"}');+ expect(detail.result).toContain('Response headers');+ expect(detail.result).toContain('x-custom-response: response-value');++ const bodyMatch = detail.result.match(/Response body\n\s+(\S+\.json)/);+ expect(bodyMatch).not.toBeNull();+ const bodyPath = path.resolve(test.info().outputPath(), bodyMatch![1]);+ expect(fs.readFileSync(bodyPath, 'utf-8')).toBe('{"name":"John Doe"}');});-test('browser_network_requests includes request payload', async ({ client, server }) => {+test('browser_network_request saves binary response body to a file', async ({ client, server }) => {+ const pngBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);server.setContent('/', `- <button onclick="fetch('/api', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'value' }) })">Click me</button>+ <button onclick="fetch('/image.png')">Click me</button>`, 'text/html');+ server.setRoute('/image.png', (_req, res) => {+ res.setHeader('Content-Type', 'image/png');+ res.end(pngBytes);+ });- server.setContent('/api', '{}', 'application/json');+ await client.callTool({+ name: 'browser_navigate',+ arguments: { url: server.PREFIX },+ });++ await client.callTool({+ name: 'browser_click',+ arguments: { element: 'Click me button', target: 'e2' },+ });++ const list = parseResponse(await client.callTool({+ name: 'browser_network_requests',+ arguments: { static: true },+ }));+ const match = list.result.match(/^(\d+)\. \[GET\] [^ ]+\/image\.png =>/m);+ expect(match).not.toBeNull();++ const detail = parseResponse(await client.callTool({+ name: 'browser_network_request',+ arguments: { index: Number(match![1]) },+ }));+ const bodyMatch = detail.result.match(/Response body\n\s+(\S+\.png)/);+ expect(bodyMatch).not.toBeNull();+ const bodyPath = path.resolve(test.info().outputPath(), bodyMatch![1]);+ expect(fs.readFileSync(bodyPath)).toEqual(pngBytes);+});++test('browser_network_request reports failed requests', async ({ client, server }) => {+ server.setContent('/', `<img src="/missing.png" />`, 'text/html');await client.callTool({name: 'browser_navigate',- arguments: {- url: server.PREFIX,- },+ arguments: { url: server.PREFIX },+ });++ const list = parseResponse(await client.callTool({+ name: 'browser_network_requests',+ arguments: { static: true },+ }));+ const match = list!.result!.match(/^(\d+)\. \[GET\] [^ ]+\/missing\.png =>/m);+ expect(match).not.toBeNull();++ const detail = parseResponse(await client.callTool({+ name: 'browser_network_request',+ arguments: { index: Number(match![1]) },+ }));+ expect(detail!.result).toContain(`#${match![1]} [GET] ${server.PREFIX}/missing.png`);+ expect(detail!.result).toContain('status: [404]');+});++test('browser_network_request returns individual parts', async ({ client, server }) => {+ server.setContent('/', `+ <button onclick="fetch('/api', { method: 'POST', headers: { 'X-Custom-Header': 'test-value' }, body: JSON.stringify({ key: 'value' }) })">Click me</button>+ `, 'text/html');+ server.setRoute('/api', (_req, res) => {+ res.setHeader('X-Custom-Response', 'response-value');+ res.setHeader('Content-Type', 'application/json');+ res.end(JSON.stringify({ name: 'John Doe' }));+ });++ await client.callTool({+ name: 'browser_navigate',+ arguments: { url: server.PREFIX },});await client.callTool({name: 'browser_click',- arguments: {- element: 'Click me button',- target: 'e2',- },+ arguments: { element: 'Click me button', target: 'e2' },});- {- const response = parseResponse(await client.callTool({- name: 'browser_network_requests',- }));- expect(response.result).toContain(`[POST] ${server.PREFIX}/api => [200] OK`);- expect(response.result).not.toContain(`Request body:`);- }+ const list = parseResponse(await client.callTool({+ name: 'browser_network_requests',+ }));+ const match = list!.result!.match(/^(\d+)\. \[POST\] [^ ]+\/api =>/m);+ expect(match).not.toBeNull();+ const index = Number(match![1]);- {- const response = parseResponse(await client.callTool({- name: 'browser_network_requests',- arguments: { requestBody: true },- }));- expect(response.result).toContain(`[POST] ${server.PREFIX}/api => [200] OK`);- expect(response.result).toContain(`Request body: {"key":"value"}`);- }+ const requestHeaders = parseResponse(await client.callTool({+ name: 'browser_network_request',+ arguments: { index, part: 'request-headers' },+ }));+ expect(requestHeaders!.result).toContain('x-custom-header: test-value');+ expect(requestHeaders!.result).not.toContain('General');++ const requestBody = parseResponse(await client.callTool({+ name: 'browser_network_request',+ arguments: { index, part: 'request-body' },+ }));+ expect(requestBody!.result).toBe('{"key":"value"}');++ const responseHeaders = parseResponse(await client.callTool({+ name: 'browser_network_request',+ arguments: { index, part: 'response-headers' },+ }));+ expect(responseHeaders!.result).toContain('x-custom-response: response-value');++ const responseBody = parseResponse(await client.callTool({+ name: 'browser_network_request',+ arguments: { index, part: 'response-body' },+ }));+ expect(responseBody!.result).toBe('{"name":"John Doe"}');+});++test('browser_network_request response-body part saves binary to a file', async ({ client, server }) => {+ const pngBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);+ server.setContent('/', `+ <button onclick="fetch('/image.png')">Click me</button>+ `, 'text/html');+ server.setRoute('/image.png', (_req, res) => {+ res.setHeader('Content-Type', 'image/png');+ res.end(pngBytes);+ });++ await client.callTool({+ name: 'browser_navigate',+ arguments: { url: server.PREFIX },+ });++ await client.callTool({+ name: 'browser_click',+ arguments: { element: 'Click me button', target: 'e2' },+ });++ const list = parseResponse(await client.callTool({+ name: 'browser_network_requests',+ arguments: { static: true },+ }));+ const match = list!.result!.match(/^(\d+)\. \[GET\] [^ ]+\/image\.png =>/m);+ expect(match).not.toBeNull();++ const detail = parseResponse(await client.callTool({+ name: 'browser_network_request',+ arguments: { index: Number(match![1]), part: 'response-body' },+ }));+ const bodyPath = path.resolve(test.info().outputPath(), detail!.result!.trim());+ expect(fs.readFileSync(bodyPath)).toEqual(pngBytes);+});++test('browser_network_request rejects out-of-range index', async ({ client, server }) => {+ await client.callTool({+ name: 'browser_navigate',+ arguments: { url: server.PREFIX },+ });++ const response = await client.callTool({+ name: 'browser_network_request',+ arguments: { index: 999 },+ });+ const parsed = parseResponse(response);+ expect(parsed!.error).toContain('Request #999 not found');});++function escapeRegExp(text: string): string {+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}diff --git a/tests/mcp/test-debug.spec.ts b/tests/mcp/test-debug.spec.tsindex c81ed7825e..88463d2970 100644--- a/tests/mcp/test-debug.spec.ts+++ b/tests/mcp/test-debug.spec.ts@@ -404,7 +404,7 @@ Error: expect(locator).toBeVisible() failed`));expect(await client.callTool({name: 'browser_network_requests',})).toHaveResponse({- result: `[GET\] ${server.PREFIX}/missing => [404] Not Found`,+ result: expect.stringContaining(`[GET] ${server.PREFIX}/missing => [404] Not Found`),});});