Skip to main content
Glama
jomon003

PlayMCP Browser Automation Server

by jomon003

executeJavaScript

Run JavaScript code directly on web pages to extract data, manipulate content, or automate interactions during browser automation tasks.

Instructions

Execute arbitrary JavaScript code on the current page and return the result

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
scriptYesThe JavaScript code to execute on the page. Can be expressions or statements.

Implementation Reference

  • The core handler function in PlaywrightController that executes arbitrary JavaScript on the current page using page.evaluate, handling both expressions and statements, with logging and error handling.
    async executeJavaScript(script: string): Promise<any> {
      try {
        if (!this.isInitialized()) {
          throw new Error('Browser not initialized');
        }
        this.log('Executing JavaScript:', script);
        const result = await this.state.page?.evaluate((scriptToExecute) => {
          // Create a function wrapper to handle different types of JavaScript code
          try {
            // If the script is an expression, return its value
            // If the script is statements, execute them and return undefined
            const wrappedScript = `
              (function() {
                ${scriptToExecute}
              })()
            `;
            return eval(wrappedScript);
          } catch (error) {
            // If wrapping fails, try executing directly
            return eval(scriptToExecute);
          }
        }, script);
        this.log('JavaScript execution completed:', result);
        return result;
      } catch (error: any) {
        console.error('Execute JavaScript error:', error);
        throw new BrowserError('Failed to execute JavaScript', 'Check if the JavaScript syntax is valid');
      }
    }
  • Defines the input schema, name, and description for the executeJavaScript tool used for MCP validation.
    const EXECUTE_JAVASCRIPT_TOOL: Tool = {
      name: "executeJavaScript",
      description: "Execute arbitrary JavaScript code on the current page and return the result",
      inputSchema: {
        type: "object",
        properties: {
          script: { 
            type: "string",
            description: "The JavaScript code to execute on the page. Can be expressions or statements."
          }
        },
        required: ["script"]
      }
    };
  • src/server.ts:555-565 (registration)
    Registers all tools, including executeJavaScript, by passing the 'tools' object to the MCP Server's capabilities.
    const server = new Server(
      {
        name: "playmcp-browser",
        version: "1.0.0",
      },
      {
        capabilities: {
          tools,
        },
      }
    );
  • The dispatch logic in the MCP 'callTool' request handler that validates input, calls the controller's executeJavaScript method, and formats the response.
    case 'executeJavaScript': {
      if (!args.script || typeof args.script !== 'string') {
        return {
          content: [{ type: "text", text: "JavaScript script is required" }],
          isError: true
        };
      }
      const result = await playwrightController.executeJavaScript(args.script);
      return {
        content: [{ 
          type: "text", 
          text: result !== undefined ? JSON.stringify(result, null, 2) : "Script executed successfully (no return value)"
        }]
      };
    }
  • src/server.ts:534-534 (registration)
    Adds the executeJavaScript tool to the central 'tools' dictionary used for MCP tool listing and capabilities.
    executeJavaScript: EXECUTE_JAVASCRIPT_TOOL,
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 mentions executing code and returning results but omits critical details like security implications, execution context (e.g., sandboxing), error handling, or performance impacts. For a tool that runs arbitrary JavaScript, 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, front-loaded sentence that efficiently conveys the core functionality without unnecessary words. Every part of the sentence earns its place by specifying the action, target, and outcome, making it highly concise and well-structured.

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 executing arbitrary JavaScript and the lack of annotations and output schema, the description is incomplete. It fails to address safety concerns, execution environment, or result formatting, which are crucial for an agent to use this tool effectively in a browser automation context.

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?

Schema description coverage is 100%, with the parameter 'script' well-documented in the schema. The description adds no additional meaning beyond the schema, such as examples of valid scripts or constraints, so it meets the baseline for high schema coverage without compensating value.

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 specific action ('Execute arbitrary JavaScript code') and target ('on the current page'), with the verb 'execute' and resource 'JavaScript code' being precise. It distinguishes from siblings like 'evaluateWithReturn' by emphasizing arbitrary execution rather than evaluation of specific elements or expressions.

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, such as 'evaluateWithReturn' or other DOM interaction tools. It lacks context about use cases, prerequisites, or exclusions, leaving the agent to infer usage based on the tool name alone.

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/jomon003/PlayMCP'

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