Skip to main content
Glama
b3nw
by b3nw

Execute JavaScript

browser_evaluate

Execute JavaScript code in a browser context to automate web interactions, extract data, or manipulate page elements through the Playwright MCP Server.

Instructions

Execute JavaScript code in the browser context

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
scriptYes

Implementation Reference

  • The handler function for 'browser_evaluate' tool. Validates input with Zod, performs security checks against dangerous JavaScript patterns, ensures Playwright browser connection, executes the script using page.evaluate(), and formats the response in MCP protocol structure.
    async (params: any) => {
      try {
        const input = z.object({
          script: z.string()
        }).parse(params);
        await this.playwright.ensureConnected();
        
        // Basic security check - prevent dangerous operations
        const script = input.script.trim();
        const dangerousPatterns = [
          /require\s*\(/,
          /import\s+/,
          /eval\s*\(/,
          /Function\s*\(/,
          /process\./,
          /global\./,
          /window\.location/,
          /document\.cookie/
        ];
        
        if (dangerousPatterns.some(pattern => pattern.test(script))) {
          throw new Error('Script contains potentially dangerous operations');
        }
        
        const page = this.playwright.getPage();
        const result = await page.evaluate(input.script);
        
        return {
          content: [{
            type: 'text',
            text: `Script executed. Result: ${JSON.stringify(result)}`
          }]
        };
      } catch (error) {
        return {
          content: [{
            type: 'text',
            text: `Script evaluation failed: ${error instanceof Error ? error.message : String(error)}`
          }],
          isError: true
        };
      }
    }
  • Zod schema and TypeScript type definition for the input parameters of the browser_evaluate tool, requiring a 'script' field of type string.
    export const BrowserEvaluateInputSchema = z.object({
      script: z.string()
    });
    
    export const BrowserSnapshotInputSchema = z.object({
      selector: z.string().optional()
    });
    
    export const BrowserFileUploadInputSchema = z.object({
      selector: z.string(),
      paths: z.array(z.string()).min(1)
    });
    
    export const BrowserRefreshInputSchema = z.object({
      waitUntil: z.enum(['networkidle', 'domcontentloaded', 'load']).optional().default('load'),
      timeout: z.number().optional()
    });
    
    export type BrowserNavigateInput = z.infer<typeof BrowserNavigateInputSchema>;
    export type BrowserTakeScreenshotInput = z.infer<typeof BrowserTakeScreenshotInputSchema>;
    export type BrowserGetHtmlInput = z.infer<typeof BrowserGetHtmlInputSchema>;
    export type BrowserClickInput = z.infer<typeof BrowserClickInputSchema>;
    export type BrowserTypeInput = z.infer<typeof BrowserTypeInputSchema>;
    export type BrowserWaitForInput = z.infer<typeof BrowserWaitForInputSchema>;
    export type BrowserEvaluateInput = z.infer<typeof BrowserEvaluateInputSchema>;
  • src/server.ts:273-325 (registration)
    Registration of the 'browser_evaluate' tool in the MCP server within PlaywrightMcpServer.setupTools() method, including tool name, metadata, input schema, and inline handler reference.
    this.server.registerTool(
      'browser_evaluate',
      {
        title: 'Execute JavaScript',
        description: 'Execute JavaScript code in the browser context',
        inputSchema: {
          script: z.string()
        }
      },
      async (params: any) => {
        try {
          const input = z.object({
            script: z.string()
          }).parse(params);
          await this.playwright.ensureConnected();
          
          // Basic security check - prevent dangerous operations
          const script = input.script.trim();
          const dangerousPatterns = [
            /require\s*\(/,
            /import\s+/,
            /eval\s*\(/,
            /Function\s*\(/,
            /process\./,
            /global\./,
            /window\.location/,
            /document\.cookie/
          ];
          
          if (dangerousPatterns.some(pattern => pattern.test(script))) {
            throw new Error('Script contains potentially dangerous operations');
          }
          
          const page = this.playwright.getPage();
          const result = await page.evaluate(input.script);
          
          return {
            content: [{
              type: 'text',
              text: `Script executed. Result: ${JSON.stringify(result)}`
            }]
          };
        } catch (error) {
          return {
            content: [{
              type: 'text',
              text: `Script evaluation failed: ${error instanceof Error ? error.message : String(error)}`
            }],
            isError: true
          };
        }
      }
    );
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. While 'Execute JavaScript code' implies a write/mutation operation, it doesn't disclose important behavioral traits like execution context isolation, error handling, security implications, or what happens to the browser state after execution. This leaves significant gaps for an agent to understand the tool's behavior.

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 with just 7 words, front-loaded with the core action, and contains zero wasted words. Every element ('Execute', 'JavaScript code', 'in the browser context') earns its place.

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 arbitrary JavaScript in a browser context with no annotations and no output schema, the description is insufficiently complete. It doesn't address critical aspects like return values, error conditions, execution scope, or how results are captured, leaving the agent with significant uncertainty about how to use this tool effectively.

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

Parameters2/5

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

With 0% schema description coverage and 1 undocumented parameter, the description adds minimal value beyond the schema. It mentions 'JavaScript code' which gives some semantic meaning to the 'script' parameter, but doesn't explain format expectations, supported JavaScript features, or any constraints on the script content.

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 code') and the context ('in the browser context'), which is specific and distinguishes it from general JavaScript execution tools. However, it doesn't explicitly differentiate from potential sibling tools that might also execute scripts in different contexts.

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 like browser_navigate or browser_type. There's no mention of prerequisites, typical use cases, or limitations that would help an agent decide when this is the appropriate tool.

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

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

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