Skip to main content
Glama
ziux

Playwright Server MCP

by ziux

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
NameRequiredDescriptionDefault
scriptYes需要在浏览器中执行的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代码")
    ]
  • 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}
  • 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}")
  • 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()
        ]
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the tool executes JavaScript and returns results, but lacks details on execution context (e.g., page scope, timing), error handling, security implications, or performance considerations. For a tool that interacts with a browser, this is a significant gap in transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the tool's function without unnecessary words. It's front-loaded with the core action and outcome, making it easy to parse. Every part of the sentence contributes to understanding the tool's purpose.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of browser JavaScript execution and the lack of annotations and output schema, the description is incomplete. It doesn't address potential risks (e.g., script injection), execution environment details, or what the return values might look like (e.g., types of results). For a tool with no structured safety or output information, more context is needed.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description doesn't add parameter-specific information beyond what the input schema provides. The schema has 100% coverage with a clear description for the 'script' parameter. Since the schema does the heavy lifting, the baseline score of 3 is appropriate, as the description doesn't compensate with additional semantics like script format examples or constraints.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: '在浏览器控制台中执行JavaScript代码并返回执行结果' (Execute JavaScript code in the browser console and return the execution result). This specifies both the verb (execute JavaScript) and resource (browser console), though it doesn't explicitly differentiate from sibling tools like playwright_action or playwright_get_html_content, which may also involve browser interactions.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention scenarios where this is preferred over other sibling tools (e.g., playwright_get_html_content for DOM extraction) or any prerequisites, such as needing an active browser session. This leaves the agent without contextual usage cues.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/ziux/playwright-plus-python-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server