Skip to content
Closed
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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -258,8 +258,9 @@ If you run into any issues, checkout our [troubleshooting guide](./docs/troubles
- [`emulate_cpu`](docs/tool-reference.md#emulate_cpu)
- [`emulate_network`](docs/tool-reference.md#emulate_network)
- [`resize_page`](docs/tool-reference.md#resize_page)
- **Performance** (3 tools)
- **Performance** (4 tools)
- [`performance_analyze_insight`](docs/tool-reference.md#performance_analyze_insight)
- [`performance_query_chrome_ux_report`](docs/tool-reference.md#performance_query_chrome_ux_report)
- [`performance_start_trace`](docs/tool-reference.md#performance_start_trace)
- [`performance_stop_trace`](docs/tool-reference.md#performance_stop_trace)
- **Network** (2 tools)
Expand Down
15 changes: 14 additions & 1 deletion docs/tool-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@
- [`emulate_cpu`](#emulate_cpu)
- [`emulate_network`](#emulate_network)
- [`resize_page`](#resize_page)
- **[Performance](#performance)** (3 tools)
- **[Performance](#performance)** (4 tools)
- [`performance_analyze_insight`](#performance_analyze_insight)
- [`performance_query_chrome_ux_report`](#performance_query_chrome_ux_report)
- [`performance_start_trace`](#performance_start_trace)
- [`performance_stop_trace`](#performance_stop_trace)
- **[Network](#network)** (2 tools)
Expand Down Expand Up @@ -232,6 +233,18 @@

---

### `performance_query_chrome_ux_report`

**Description:** Queries the Chrome UX Report (aka CrUX) to get aggregated real-user experience metrics (like Core Web Vitals) for a given URL or origin.

**Parameters:**

- **origin** (string) _(optional)_: The origin to query, e.g., "https://web.dev". Do not provide this if "url" is specified.
- **url** (string) _(optional)_: The specific page URL to query, e.g., "https://web.dev/s/results?q=puppies". Do not provide this if "origin" is specified.
- **formFactor** (enum: "DESKTOP", "PHONE", "TABLET") _(optional)_: The form factor to filter by. If omitted, data for all form factors is aggregated.

---

### `performance_start_trace`

**Description:** Starts a performance trace recording on the selected page. This can be used to look for performance problems and insights to improve the performance of the page. It will also report Core Web Vital (CWV) scores for the page.
Expand Down
68 changes: 68 additions & 0 deletions src/tools/performance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,3 +185,71 @@ async function stopTracingAndAppendOutput(
context.setIsRunningPerformanceTrace(false);
}
}

// This key is expected to be visible. b/349721878
const CRUX_API_KEY = 'AIzaSyBn5gimNjhiEyA_euicSKko6IlD3HdgUfk';
const CRUX_ENDPOINT = `https://chromeuxreport.googleapis.com/v1/records:queryRecord?key=${CRUX_API_KEY}`;

export const queryChromeUXReport = defineTool({
name: 'performance_query_chrome_ux_report',
description:
'Queries the Chrome UX Report (aka CrUX) to get aggregated real-user experience metrics (like Core Web Vitals) for a given URL or origin.',
annotations: {
category: ToolCategory.PERFORMANCE,
readOnlyHint: true,
},
schema: {
origin: zod
.string()
.describe(
'The origin to query, e.g., "https://web.dev". Do not provide this if "url" is specified.',
)
.optional(),
url: zod
.string()
.describe(
'The specific page URL to query, e.g., "https://web.dev/s/results?q=puppies". Do not provide this if "origin" is specified.',
)
.optional(),
formFactor: zod
.enum(['DESKTOP', 'PHONE', 'TABLET'])
.describe(
'The form factor to filter by. If omitted, data for all form factors is aggregated.',
)
.optional(),
},
handler: async (request, response) => {
const {origin: origin_, url, formFactor} = request.params;
// Ensure probably formatted origin (no trailing slash);
const origin = URL.parse(origin_ ?? '')?.origin;

if ((!origin && !url) || (origin && url)) {
return response.appendResponseLine(
'Error: you must provide either "origin" or "url", but not both.',
);
}

try {
const cruxResponse = await fetch(CRUX_ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
referer: 'devtools://mcp',
},
body: JSON.stringify({
origin,
url,
formFactor,
}),
});

const data = await cruxResponse.json();
response.appendResponseLine(JSON.stringify(data, null, 2));
} catch (e) {
const errorText = e instanceof Error ? e.message : JSON.stringify(e);
logger(`Error fetching CrUX data: ${errorText}`);
response.appendResponseLine('An error occurred fetching CrUX data:');
response.appendResponseLine(errorText);
}
},
});
103 changes: 103 additions & 0 deletions tests/tools/performance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import sinon from 'sinon';

import {
analyzeInsight,
queryChromeUXReport,
startTrace,
stopTrace,
} from '../../src/tools/performance.js';
Expand Down Expand Up @@ -272,4 +273,106 @@ describe('performance', () => {
});
});
});

describe('performance_query_chrome_ux_report', () => {
it('successfully queries with origin', async () => {
const mockResponse = {record: {key: {origin: 'https://example.com'}}};
const fetchStub = sinon.stub(global, 'fetch').resolves(
new Response(JSON.stringify(mockResponse), {
status: 200,
headers: {'Content-Type': 'application/json'},
}),
);

await withBrowser(async (response, context) => {
await queryChromeUXReport.handler(
{params: {origin: 'https://example.com'}},
response,
context,
);

assert.ok(fetchStub.calledOnce);
assert.strictEqual(
response.responseLines[0],
JSON.stringify(mockResponse, null, 2),
);
});
});

it('successfully queries with url', async () => {
const mockResponse = {record: {key: {url: 'https://example.com'}}};
const fetchStub = sinon.stub(global, 'fetch').resolves(
new Response(JSON.stringify(mockResponse), {
status: 200,
headers: {'Content-Type': 'application/json'},
}),
);

await withBrowser(async (response, context) => {
await queryChromeUXReport.handler(
{params: {url: 'https://example.com'}},
response,
context,
);

assert.ok(fetchStub.calledOnce);
assert.strictEqual(
response.responseLines[0],
JSON.stringify(mockResponse, null, 2),
);
});
});

it('errors if both origin and url are provided', async () => {
await withBrowser(async (response, context) => {
await queryChromeUXReport.handler(
{
params: {origin: 'https://example.com', url: 'https://example.com'},
},
response,
context,
);

assert.ok(
response.responseLines[0]?.includes(
'Error: you must provide either "origin" or "url", but not both.',
),
);
});
});

it('errors if neither origin nor url are provided', async () => {
await withBrowser(async (response, context) => {
await queryChromeUXReport.handler({params: {}}, response, context);

assert.ok(
response.responseLines[0]?.includes(
'Error: you must provide either "origin" or "url", but not both.',
),
);
});
});

it('handles fetch API error', async () => {
const fetchStub = sinon
.stub(global, 'fetch')
.rejects(new Error('API is down'));

await withBrowser(async (response, context) => {
await queryChromeUXReport.handler(
{params: {origin: 'https://example.com'}},
response,
context,
);

assert.ok(fetchStub.calledOnce);
assert.ok(
response.responseLines[0]?.includes(
'An error occurred fetching CrUX data:',
),
);
assert.strictEqual(response.responseLines[1], 'API is down');
});
});
});
});
Loading