playwright_evaluate
Execute JavaScript code in a browser console and retrieve results using a browser automation server. Ideal for scripting interactions, extracting data, or testing web functionality.
Instructions
在浏览器控制台中执行JavaScript代码并返回执行结果
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| script | Yes | 需要在浏览器中执行的JavaScript代码 |
Implementation Reference
- The EvaluateToolHandler class provides the core implementation of the 'playwright_evaluate' tool. It defines the tool's name, description, input schema, and the 'handle' method which executes the provided JavaScript 'script' on the current browser page using Playwright's page.evaluate() and returns the result.class EvaluateToolHandler(ToolHandler): name = "playwright_evaluate" description = "在浏览器控制台中执行JavaScript代码并返回执行结果" inputSchema = [ Property(name="script", typ="string", description="需要在浏览器中执行的JavaScript代码") ] async def handle(self, name: str, arguments: dict | None) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]: logger.info("开始执行JavaScript代码") if not self._sessions: logger.warning("没有活跃的会话。需要先创建一个新会话。") return [types.TextContent(type="text", text="No active session. Please create a new session first.")] try: session_id = list(self._sessions.keys())[-1] page = self._sessions[session_id]["page"] script = arguments.get("script") logger.debug(f"执行脚本: {script}") result = await page.evaluate(script) logger.info(f"脚本执行完成,结果: {result}") return [types.TextContent(type="text", text=f"Evaluated script, result: {result}")] except Exception as e: logger.error(f"脚本执行失败: {str(e)}", exc_info=True) return [types.TextContent(type="text", text=f"脚本执行失败: {str(e)}")]
- Input schema for the 'playwright_evaluate' tool, specifying a required 'script' parameter of type string.inputSchema = [ Property(name="script", typ="string", description="需要在浏览器中执行的JavaScript代码") ]
- src/playwright_server/server.py:43-55 (registration)Registration of the EvaluateToolHandler instance in the tool_handler_list, which is then mapped to a dictionary by name for use in the MCP server's list_tools() and call_tool() handlers.tool_handler_list = [ NavigateToolHandler(), # ScreenshotToolHandler(), EvaluateToolHandler(), GetTextContentToolHandler(), GetHtmlContentToolHandler(), NewSessionToolHandler(), ActionToolHandler() ] # 根据每个处理程序的 name 属性创建字典 tool_handlers = {handler.name: handler for handler in tool_handler_list}
- src/playwright_server/server.py:110-130 (registration)The MCP server's call_tool handler that dispatches to the registered tool_handlers[name].handle(), enabling execution of 'playwright_evaluate'.async def handle_call_tool( name: str, arguments: dict | None ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]: """ Handle tool execution requests. Tools can modify server state and notify clients of changes. """ logger.info(f"处理 call_tool 请求,工具: {name}, 参数: {arguments}") if name in tool_handlers: try: logger.debug(f"调用工具处理器: {name}") result = await tool_handlers[name].handle(name, arguments) logger.debug(f"工具处理器 {name} 执行完成") return result except Exception as e: logger.error(f"工具处理器 {name} 执行失败: {str(e)}", exc_info=True) raise else: logger.warning(f"未知工具: {name}") raise ValueError(f"Unknown tool: {name}")
- src/playwright_server/server.py:98-108 (registration)The MCP server's list_tools handler that exposes the registered tools, including 'playwright_evaluate', via tool_handler.to_tool() which generates the JSON schema from inputSchema.@server.list_tools() async def handle_list_tools() -> list[types.Tool]: """ List available tools. Each tool specifies its arguments using JSON Schema validation. """ logger.debug("处理 list_tools 请求") return [ tool_handler.to_tool() for tool_handler in tool_handlers.values() ]