Skip to main content
Glama

playwright_evaluate

Execute JavaScript in the browser console to automate web interactions, extract data, or manipulate web elements using the Playwright MCP Server.

Instructions

Execute JavaScript in the browser console

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
scriptYesJavaScript code to execute

Implementation Reference

  • Switch case handling the 'playwright_evaluate' tool: executes JavaScript in the browser page context using page.evaluate, overrides console methods to capture logs, and returns the result along with console output.
    case "playwright_evaluate":
      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: `Execution result:\n${JSON.stringify(result.result, null, 2)}\n\nConsole 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,
          },
        };
      }
  • Tool schema definition for 'playwright_evaluate', specifying name, description, and input schema requiring a 'script' string.
    {
      name: "playwright_evaluate",
      description: "Execute JavaScript in the browser console",
      inputSchema: {
        type: "object",
        properties: {
          script: { type: "string", description: "JavaScript code to execute" },
        },
        required: ["script"],
      },
    },
  • Registration of the tool list handler, which returns all tools including 'playwright_evaluate' from createToolDefinitions().
    // List tools handler
    server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: tools,
    }));
  • Registration of the tool call handler, which dispatches to handleToolCall for 'playwright_evaluate' and other tools.
    server.setRequestHandler(CallToolRequestSchema, async (request) =>
      handleToolCall(request.params.name, request.params.arguments ?? {}, server)
    );
  • BROWSER_TOOLS array listing 'playwright_evaluate' to trigger browser launch when this tool is called.
    export const BROWSER_TOOLS = [
      "playwright_navigate",
      "playwright_screenshot",
      "playwright_click",
      "playwright_fill",
      "playwright_select",
      "playwright_hover",
      "playwright_evaluate"
    ];
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 what the tool does but lacks critical details: it doesn't mention execution context (e.g., current page, frame), error handling, security implications, or what happens if the script fails. This is a significant gap for a tool that executes arbitrary JavaScript in a browser environment.

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 extremely concise—a single, clear sentence that directly states the tool's function without any unnecessary words. It is front-loaded with the core action, making it easy to understand at a glance.

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?

For a tool that executes JavaScript in a browser—a potentially complex and risky operation—the description is inadequate. With no annotations, no output schema, and minimal behavioral context, it fails to provide essential information about execution environment, error handling, or security considerations, leaving significant gaps for an AI agent to use it safely and effectively.

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 schema description coverage is 100%, with the 'script' parameter clearly documented as 'JavaScript code to execute'. The description adds no additional semantic information beyond this, such as examples of valid scripts, return value expectations, or constraints on script content. Given the high schema coverage, a baseline score of 3 is appropriate.

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 action ('Execute JavaScript') and the context ('in the browser console'), which is specific and unambiguous. However, it doesn't explicitly differentiate from sibling tools like playwright_get or playwright_navigate, which might also involve browser interactions but serve different purposes.

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 executing JavaScript is preferred over other browser automation tools (e.g., playwright_click for clicks, playwright_fill for form inputs), nor does it specify prerequisites or exclusions for its use.

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/lebrodus/mcp-playwright'

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