Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

feat(mcp): add maxResults option to browser_find (#42077) (#42947)

Alok Pandey6907c8e079c7
diff --git a/packages/playwright-core/src/tools/backend/find.ts b/packages/playwright-core/src/tools/backend/find.ts
index 3251df89b7..d45df7e1fc 100644
--- a/packages/playwright-core/src/tools/backend/find.ts
+++ b/packages/playwright-core/src/tools/backend/find.ts
@@ -30,6 +30,7 @@ const find = defineTabTool({
inputSchema: z.object({
text: z.string().optional().describe('Plain text to search for in the page snapshot (case-insensitive substring match). Provide either text or regex, not both.'),
regex: z.string().optional().refine(v => !v || isValidRegex(v), { message: 'Invalid regular expression' }).describe('Regular expression to search for in the page snapshot. Matching is case-sensitive by default; wrap the pattern in slashes to add flags, e.g. "/error/i" for case-insensitive. Provide either text or regex, not both.'),
+ maxResults: z.number().optional().describe('Maximum number of matching items to return. Defaults to returning all matches.'),
filename: z.string().optional().describe('Save results to a file instead of returning them in the response. Relative file names are resolved against the workspace root.'),
}),
type: 'readOnly',
@@ -44,6 +45,10 @@ const find = defineTabTool({
response.addError('Provide only one of "text" or "regex", not both.');
return;
}
+ if (params.maxResults !== undefined && (!Number.isInteger(params.maxResults) || params.maxResults <= 0)) {
+ response.addError('"maxResults" must be a positive integer.');
+ return;
+ }
let query: string;
let matches: (line: string) => boolean;
@@ -74,9 +79,14 @@ const find = defineTabTool({
return;
}
+ const totalMatches = matchedLines.length;
+ const matchesToRender = params.maxResults !== undefined && params.maxResults < totalMatches
+ ? matchedLines.slice(0, params.maxResults)
+ : matchedLines;
+
// Merge matched lines into windows of context, coalescing overlapping ones.
const windows: { start: number, end: number }[] = [];
- for (const line of matchedLines) {
+ for (const line of matchesToRender) {
const start = Math.max(0, line - contextLines);
const end = Math.min(lines.length - 1, line + contextLines);
const last = windows[windows.length - 1];
@@ -87,7 +97,7 @@ const find = defineTabTool({
}
const path = new Set<number>();
- for (const match of matchedLines) {
+ for (const match of matchesToRender) {
path.add(match);
for (const ancestor of ancestorIndices(lines, indents, match))
path.add(ancestor);
@@ -106,8 +116,11 @@ const find = defineTabTool({
}
return out.join('\n');
});
- const matchWord = matchedLines.length === 1 ? 'match' : 'matches';
- await response.addResult('Find results', `Found ${matchedLines.length} ${matchWord} for ${query}:\n\n${snippets.join('\n\n----\n\n')}`, { prefix: 'find', ext: 'md', suggestedFilename: params.filename });
+ const matchWord = totalMatches === 1 ? 'match' : 'matches';
+ const header = matchesToRender.length < totalMatches
+ ? `Found ${totalMatches} ${matchWord} for ${query} (showing first ${matchesToRender.length}):`
+ : `Found ${totalMatches} ${matchWord} for ${query}:`;
+ await response.addResult('Find results', `${header}\n\n${snippets.join('\n\n----\n\n')}`, { prefix: 'find', ext: 'md', suggestedFilename: params.filename });
},
});
diff --git a/packages/playwright-core/src/tools/cli-daemon/commands.ts b/packages/playwright-core/src/tools/cli-daemon/commands.ts
index 530c0c1803..c28b54f855 100644
--- a/packages/playwright-core/src/tools/cli-daemon/commands.ts
+++ b/packages/playwright-core/src/tools/cli-daemon/commands.ts
@@ -399,9 +399,10 @@ const find = declareCommand({
options: z.object({
regex: z.string().optional().describe('Regular expression to search for in the page snapshot. Provide either a text argument or --regex, not both.'),
filename: z.string().optional().describe('Save results to a file instead of returning them in the response.'),
+ ['max-results']: numberArg.optional().describe('Maximum number of matching items to return, unlimited by default.'),
}),
toolName: 'browser_find',
- toolParams: ({ text, regex, filename }) => ({ text, regex, filename }),
+ toolParams: ({ text, regex, filename, ['max-results']: maxResults }) => ({ text, regex, filename, maxResults }),
});
const generateLocator = declareCommand({
diff --git a/tests/mcp/cli-find.spec.ts b/tests/mcp/cli-find.spec.ts
index 5c6a93c0ac..0d341a765d 100644
--- a/tests/mcp/cli-find.spec.ts
+++ b/tests/mcp/cli-find.spec.ts
@@ -73,3 +73,52 @@ test('find --filename', async ({ cli, server }, testInfo) => {
expect(content).toContain('Found 1 match for "Bananas":');
expect(content).toContain('Apples');
});
+
+test('find --max-results truncates output', async ({ cli, server }) => {
+ server.setContent('/', `
+ <section aria-label="First Section">
+ <ul>
+ <li>Fruit: Apples</li>
+ <li>Fruit: Bananas</li>
+ <li>Spacer 1</li>
+ <li>Spacer 2</li>
+ <li>Spacer 3</li>
+ <li>Spacer 4</li>
+ </ul>
+ </section>
+ <section aria-label="Second Section">
+ <ul>
+ <li>Fruit: Cherries</li>
+ </ul>
+ </section>
+ `, 'text/html');
+ await cli('open', server.PREFIX);
+
+ // With 3 matches and --max-results=2: header shows truncation notice,
+ // output contains first 2 matches and their ancestor, and omits the 3rd match and its ancestor.
+ const { output } = await cli('find', '--regex=Fruit', '--max-results=2');
+ expect(output).toContain('Found 3 matches for /Fruit/ (showing first 2):');
+ expect(output).toContain('Apples');
+ expect(output).toContain('Bananas');
+ expect(output).toContain('First Section');
+ expect(output).not.toContain('Cherries');
+ expect(output).not.toContain('Second Section');
+});
+
+test('find --max-results exceeding match count shows all results', async ({ cli, server }) => {
+ server.setContent('/', listPage, 'text/html');
+ await cli('open', server.PREFIX);
+
+ // With --max-results exceeding the total match count, no truncation suffix appears.
+ const { output } = await cli('find', 'Bananas', '--max-results=10');
+ expect(output).toContain('Found 1 match for "Bananas":');
+ expect(output).not.toContain('(showing first');
+});
+
+test('find --max-results=0 is rejected', async ({ cli, server }) => {
+ server.setContent('/', listPage, 'text/html');
+ await cli('open', server.PREFIX);
+
+ const { output } = await cli('find', 'Apples', '--max-results=0');
+ expect(output).toContain('"maxResults" must be a positive integer.');
+});
diff --git a/tests/mcp/find.spec.ts b/tests/mcp/find.spec.ts
index 3252fc8658..0664e5c4b9 100644
--- a/tests/mcp/find.spec.ts
+++ b/tests/mcp/find.spec.ts
@@ -247,3 +247,93 @@ test('browser_find saves results to file', async ({ client, server }, testInfo)
expect(content).toContain('Found 1 match for "Bananas":');
expect(content).toContain('Apples');
});
+
+test('browser_find maxResults option', async ({ client, server }) => {
+ server.setContent('/', `
+ <section aria-label="First Section">
+ <ul>
+ <li>Fruit: Apples</li>
+ <li>Fruit: Bananas</li>
+ <li>Spacer 1</li>
+ <li>Spacer 2</li>
+ <li>Spacer 3</li>
+ <li>Spacer 4</li>
+ </ul>
+ </section>
+ <section aria-label="Second Section">
+ <ul>
+ <li>Fruit: Cherries</li>
+ </ul>
+ </section>
+ `, 'text/html');
+ await client.callTool({ name: 'browser_navigate', arguments: { url: server.PREFIX } });
+
+ // Case 1: maxResults truncates output.
+ // With maxResults=2 and 3 matches (Apples, Bananas, Cherries):
+ // - header shows "Found 3 matches ... (showing first 2)"
+ // - output contains Apples and Bananas (first 2 matches)
+ // - output contains ancestor path of rendered matches ("First Section")
+ // - output does NOT contain Cherries (the truncated 3rd match)
+ // - output does NOT contain the truncated match's ancestor path ("Second Section")
+ const truncated = await client.callTool({
+ name: 'browser_find',
+ arguments: { regex: 'Fruit', maxResults: 2 },
+ });
+ expect(truncated).toHaveResponse({
+ result: expect.stringContaining('Found 3 matches for /Fruit/ (showing first 2):'),
+ });
+ expect(truncated).toHaveResponse({
+ result: expect.stringContaining('Apples'),
+ });
+ expect(truncated).toHaveResponse({
+ result: expect.stringContaining('Bananas'),
+ });
+ expect(truncated).toHaveResponse({
+ result: expect.stringContaining('First Section'),
+ });
+ expect(truncated).toHaveResponse({
+ result: expect.not.stringContaining('Cherries'),
+ });
+ expect(truncated).toHaveResponse({
+ result: expect.not.stringContaining('Second Section'),
+ });
+
+ // Case 2: maxResults >= total matches → no truncation suffix.
+ const notTruncated = await client.callTool({
+ name: 'browser_find',
+ arguments: { text: 'Bananas', maxResults: 5 },
+ });
+ expect(notTruncated).toHaveResponse({
+ result: expect.stringContaining('Found 1 match for "Bananas":'),
+ });
+ expect(notTruncated).toHaveResponse({
+ result: expect.not.stringContaining('(showing first'),
+ });
+
+ // Case 3: maxResults=0 → validation error.
+ expect(await client.callTool({
+ name: 'browser_find',
+ arguments: { text: 'Apples', maxResults: 0 },
+ })).toHaveResponse({
+ error: expect.stringContaining('"maxResults" must be a positive integer.'),
+ isError: true,
+ });
+
+ // Case 4: maxResults=-1 → validation error.
+ expect(await client.callTool({
+ name: 'browser_find',
+ arguments: { text: 'Apples', maxResults: -1 },
+ })).toHaveResponse({
+ error: expect.stringContaining('"maxResults" must be a positive integer.'),
+ isError: true,
+ });
+
+ // Case 5: maxResults=1.5 (non-integer) → validation error.
+ expect(await client.callTool({
+ name: 'browser_find',
+ arguments: { text: 'Apples', maxResults: 1.5 },
+ })).toHaveResponse({
+ error: expect.stringContaining('"maxResults" must be a positive integer.'),
+ isError: true,
+ });
+});