browser_evaluate
Execute JavaScript directly in the browser context to manipulate DOM elements, interact with web content, or perform API requests for autonomous browser automation.
Instructions
Execute JavaScript in the browser context
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| script | Yes | JavaScript code to execute |
Implementation Reference
- src/executor.ts:456-510 (handler)The handler function that executes the provided JavaScript code in the browser context using Playwright's page.evaluate, captures overridden console logs, and returns the evaluation result along with any console output.async function handleBrowserEvaluate(page: Page, args: any): Promise<{ toolResult: CallToolResult }> { try { const result = await page.evaluate((script) => { const logs: string[] = []; const originalConsole = { ...console }; ['log', 'info', 'warn', 'error'].forEach(method => { (console as any)[method] = (...args: any[]) => { logs.push(`[${method}] ${args.join(' ')}`); (originalConsole as any)[method](...args); }; }); try { const result = eval(script); Object.assign(console, originalConsole); return { result, logs }; } catch (error) { Object.assign(console, originalConsole); throw error; } }, args.script); return { toolResult: { content: [ { type: "text", text: `Script result: ${JSON.stringify(result.result, null, 2)}`, }, { type: "text", text: `Console output:\n${result.logs.join('\n')}`, } ], isError: false, }, }; } catch (error) { return { toolResult: { content: [{ type: "text", text: `Script execution failed: ${(error as Error).message}`, }], isError: true, }, }; } }
- src/tools.ts:119-129 (schema)Defines the tool schema including name, description, and input schema requiring a 'script' string parameter.{ name: "browser_evaluate", description: "Execute JavaScript in the browser context", inputSchema: { type: "object", properties: { script: { type: "string", description: "JavaScript code to execute" } }, required: ["script"] } },
- src/executor.ts:206-207 (registration)Registers the tool name in the switch statement within executeToolCall, dispatching to the specific handler.case "browser_evaluate": return await handleBrowserEvaluate(activePage!, args);
- src/index.ts:79-80 (registration)Calls registerTools() to get the list of tools including browser_evaluate and passes it to setupHandlers for MCP server registration.const tools = registerTools(); setupHandlers(server, tools);
- src/tools.ts:3-12 (helper)Includes 'browser_evaluate' in the BROWSER_TOOLS array used to identify browser-related tools and initialize the browser.export const BROWSER_TOOLS = [ "browser_navigate", "browser_screenshot", "browser_click", "browser_fill", "browser_select", "browser_hover", "browser_evaluate", "browser_set_viewport" ];