Skip to main content
Glama

execute-code

Run custom Playwright JavaScript code on web pages to automate browser interactions, capture console logs, and retrieve execution results for testing and automation.

Instructions

Execute custom Playwright JS code against the current page

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesThe Playwright code to execute. Must be an async function declaration that takes a page parameter. Example: async function run(page) { console.log(await page.title()); return await page.title(); } Returns an object with: - result: The return value from your function - logs: Array of console logs from execution - errors: Array of any errors encountered Example response: {"result": "Google", "logs": ["[log] Google"], "errors": []}

Implementation Reference

  • Registration of the 'execute-code' MCP tool using server.tool, including schema and handler function that delegates to secureEvalAsync
    server.tool(
      'execute-code',
      'Execute custom Playwright JS code against the current page',
      {
        code: z.string().describe(`The Playwright code to execute. Must be an async function declaration that takes a page parameter.
    
    Example:
    async function run(page) {
      console.log(await page.title());
      return await page.title();
    }
    
    Returns an object with:
    - result: The return value from your function
    - logs: Array of console logs from execution
    - errors: Array of any errors encountered
    
    Example response:
    {"result": "Google", "logs": ["[log] Google"], "errors": []}`)
      },
      async ({ code }) => {
        posthogServer.capture({
          distinctId: getUserId(),
          event: 'execute_code',
          properties: {
            codeLength: code.length,
          },
        });
    
        const result = await secureEvalAsync(page, code);
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(result, null, 2) // Pretty print the JSON
            }
          ]
        };
      }
    )
  • MCP tool handler for 'execute-code': logs event, executes code via secureEvalAsync, and returns JSON-stringified result as text content
    async ({ code }) => {
      posthogServer.capture({
        distinctId: getUserId(),
        event: 'execute_code',
        properties: {
          codeLength: code.length,
        },
      });
    
      const result = await secureEvalAsync(page, code);
      return {
        content: [
          {
            type: "text",
            text: JSON.stringify(result, null, 2) // Pretty print the JSON
          }
        ]
      };
    }
  • Input schema for 'execute-code' tool: requires 'code' string with detailed description and example
      {
        code: z.string().describe(`The Playwright code to execute. Must be an async function declaration that takes a page parameter.
    
    Example:
    async function run(page) {
      console.log(await page.title());
      return await page.title();
    }
    
    Returns an object with:
    - result: The return value from your function
    - logs: Array of console logs from execution
    - errors: Array of any errors encountered
    
    Example response:
    {"result": "Google", "logs": ["[log] Google"], "errors": []}`)
  • Core implementation of secure code execution using Node.js vm module: wraps user code, sandboxes with page object and captured console, executes and returns result/logs/errors
    export const secureEvalAsync = async (page: Page, code: string, context = {}) => {
      // Set default options
      const timeout = 20000;
      const filename = 'eval.js';
    
      let logs: string[] = [];
      let errors: string[] = [];
    
      // Code should already be a function declaration
      // Just need to execute it with page argument
      const wrappedCode = `
        ${code}
        run(page);
      `;
    
      // Create restricted sandbox with provided context
      const sandbox = {
        // Core async essentials
        Promise,
        setTimeout,
        clearTimeout,
        setImmediate,
        clearImmediate,
    
        // Pass page object to sandbox
        page,
    
        // Capture all console methods
        console: {
          log: (...args: any[]) => {
            const msg = args.map(arg => String(arg)).join(' ');
            logs.push(`[log] ${msg}`);
          },
          error: (...args: any[]) => {
            const msg = args.map(arg => String(arg)).join(' ');
            errors.push(`[error] ${msg}`);
          },
          warn: (...args: any[]) => {
            const msg = args.map(arg => String(arg)).join(' ');
            logs.push(`[warn] ${msg}`);
          },
          info: (...args: any[]) => {
            const msg = args.map(arg => String(arg)).join(' ');
            logs.push(`[info] ${msg}`);
          },
          debug: (...args: any[]) => {
            const msg = args.map(arg => String(arg)).join(' ');
            logs.push(`[debug] ${msg}`);
          },
          trace: (...args: any[]) => {
            const msg = args.map(arg => String(arg)).join(' ');
            logs.push(`[trace] ${msg}`);
          }
        },
    
        // User-provided context
        ...context,
    
        // Explicitly block access to sensitive globals
        process: undefined,
        global: undefined,
        require: undefined,
        __dirname: undefined,
        __filename: undefined,
        Buffer: undefined
      };
    
      try {
        // Create context and script
        const vmContext = vm.createContext(sandbox);
        const script = new vm.Script(wrappedCode, { filename });
    
        // Execute and await result
        const result = script.runInContext(vmContext);
        const awaitedResult = await result;
    
        return {
          result: awaitedResult,
          logs,
          errors
        };
    
      } catch (error: any) {
        return {
          error: true,
          message: error.message,
          stack: error.stack,
          logs,
          errors
        };
      }
    }
Behavior4/5

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

With no annotations provided, the description carries the full burden. It discloses key behavioral traits: the code must be an async function with a page parameter, and it describes the return structure (result, logs, errors). However, it doesn't mention potential side effects like page navigation or mutation, rate limits, or error handling beyond the errors array.

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, front-loaded sentence that directly states the tool's purpose without unnecessary words. It efficiently conveys the core functionality, making every word count.

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

Completeness4/5

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

Given the tool's complexity (executing custom code) and lack of annotations or output schema, the description is reasonably complete. It covers the purpose, parameter expectations, and return structure, but could improve by addressing safety concerns or execution constraints. It's adequate for a tool with one well-documented parameter.

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

Parameters4/5

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

Schema description coverage is 100%, so the schema already documents the 'code' parameter thoroughly with examples and return details. The description adds minimal value beyond the schema by reiterating the context ('Playwright JS code against the current page'), but doesn't provide additional semantic insights. Baseline is 3, but the description slightly enhances clarity, warranting a 4.

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

Purpose5/5

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

The description clearly states the verb ('Execute') and resource ('custom Playwright JS code') with specific context ('against the current page'). It distinguishes from siblings like get-context or get-screenshot by focusing on code execution rather than retrieval or capture.

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

Usage Guidelines3/5

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

The description implies usage when custom Playwright operations are needed on the current page, but it doesn't explicitly state when to use this tool versus alternatives like get-full-dom for DOM inspection or init-browser for browser setup. No exclusions or prerequisites are mentioned.

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

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