Skip to main content
Glama
BrowserGenie

BrowserGenie MCP Server

by BrowserGenie

execute_javascript

Run custom JavaScript code directly in the browser page to extract data, modify content, trigger events, and access all page APIs, such as window and document.

Instructions

Run ANY JavaScript code directly in the page. This is your escape hatch for anything the other tools can't do: extract data, modify the page, trigger events, check values, etc. Full access to window, document, and all page APIs.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
expressionYesJavaScript code to run. Can be a simple expression or multi-line function.
tabIdNoTarget tab ID (defaults to active tab)
apiKeyNoAPI key for authentication if enabled

Implementation Reference

  • Handler function that defines the 'execute_javascript' MCP tool. It accepts a JavaScript expression, sends it via WebSocket bridge to a Chrome extension which executes it in the page context, and returns the result. Handles both success and JavaScript exception details.
    server.tool(
      'execute_javascript',
      'Run ANY JavaScript code directly in the page. This is your escape hatch for anything the other tools can\'t do: extract data, modify the page, trigger events, check values, etc. Full access to window, document, and all page APIs.',
      {
        expression: z.string().describe('JavaScript code to run. Can be a simple expression or multi-line function.'),
        tabId: z.number().optional().describe('Target tab ID (defaults to active tab)'),
        apiKey: z.string().optional().describe('API key for authentication if enabled'),
      },
      async ({ expression, tabId, apiKey }) => {
        const result = await bridge.sendCommand({
          command: 'execute_javascript',
          params: { expression },
          tabId,
          apiKey,
        });
        if (!result.success) {
          return { content: [{ type: 'text', text: `Error: ${result.error?.message}` }], isError: true };
        }
        const data = result.data as { result: unknown; exceptionDetails?: unknown };
        if (data.exceptionDetails) {
          return {
            content: [{ type: 'text', text: `JavaScript exception: ${JSON.stringify(data.exceptionDetails, null, 2)}` }],
            isError: true,
          };
        }
        return { content: [{ type: 'text', text: JSON.stringify(data.result, null, 2) }] };
      }
    );
  • Zod schema for the 'execute_javascript' tool parameters: 'expression' (required string), 'tabId' (optional number), and 'apiKey' (optional string).
    {
      expression: z.string().describe('JavaScript code to run. Can be a simple expression or multi-line function.'),
      tabId: z.number().optional().describe('Target tab ID (defaults to active tab)'),
      apiKey: z.string().optional().describe('API key for authentication if enabled'),
    },
  • Registration function 'registerDevtoolsConsoleTools' that registers the 'execute_javascript' tool (along with 'get_console_logs') on the MCP server. Called from src/tools/index.ts line 43.
    export function registerDevtoolsConsoleTools(server: McpServer, bridge: WebSocketBridge) {
      server.tool(
        'get_console_logs',
        'Get all console messages from the page (console.log, console.error, warnings, etc.). Use this to debug JavaScript errors, see what the page is logging, or verify your code is running.',
        {
          level: z.enum(['log', 'warn', 'error', 'info', 'debug', 'all']).optional()
            .describe('Filter logs: "error" for errors only, "warn" for warnings, "all" for everything (default)'),
          clear: z.boolean().optional().describe('Clear all logs after reading so you only get new messages next time'),
          tabId: z.number().optional().describe('Target tab ID (defaults to active tab)'),
          apiKey: z.string().optional().describe('API key for authentication if enabled'),
        },
        async ({ level, clear, tabId, apiKey }) => {
          const result = await bridge.sendCommand({
            command: 'get_console_logs',
            params: { level, clear },
            tabId,
            apiKey,
          });
          if (!result.success) {
            return { content: [{ type: 'text', text: `Error: ${result.error?.message}` }], isError: true };
          }
          return { content: [{ type: 'text', text: JSON.stringify(result.data, null, 2) }] };
        }
      );
    
      server.tool(
        'execute_javascript',
        'Run ANY JavaScript code directly in the page. This is your escape hatch for anything the other tools can\'t do: extract data, modify the page, trigger events, check values, etc. Full access to window, document, and all page APIs.',
        {
          expression: z.string().describe('JavaScript code to run. Can be a simple expression or multi-line function.'),
          tabId: z.number().optional().describe('Target tab ID (defaults to active tab)'),
          apiKey: z.string().optional().describe('API key for authentication if enabled'),
        },
        async ({ expression, tabId, apiKey }) => {
          const result = await bridge.sendCommand({
            command: 'execute_javascript',
            params: { expression },
            tabId,
            apiKey,
          });
          if (!result.success) {
            return { content: [{ type: 'text', text: `Error: ${result.error?.message}` }], isError: true };
          }
          const data = result.data as { result: unknown; exceptionDetails?: unknown };
          if (data.exceptionDetails) {
            return {
              content: [{ type: 'text', text: `JavaScript exception: ${JSON.stringify(data.exceptionDetails, null, 2)}` }],
              isError: true,
            };
          }
          return { content: [{ type: 'text', text: JSON.stringify(data.result, null, 2) }] };
        }
      );
    }
  • WebSocketBridge.sendCommand() - the helper that sends the 'execute_javascript' command over WebSocket to the Chrome extension, with timeout handling and response resolution.
    async sendCommand(cmd: BridgeCommand): Promise<BridgeResponse> {
      if (!this.isConnected()) {
        return {
          success: false,
          error: {
            code: 'NOT_CONNECTED',
            message: 'Chrome extension is not connected. Ensure the extension is installed, enabled, and the browser is running.',
          },
        };
      }
    
      const id = crypto.randomUUID();
      const timeout = cmd.timeout ?? DEFAULT_TIMEOUT;
    
      return new Promise<BridgeResponse>((resolve, reject) => {
        const timer = setTimeout(() => {
          this.pending.delete(id);
          resolve({
            success: false,
            error: {
              code: 'TIMEOUT',
              message: `Command '${cmd.command}' timed out after ${timeout}ms`,
            },
          });
        }, timeout);
    
        this.pending.set(id, { resolve, reject, timer });
    
        const message = {
          id,
          type: 'request',
          command: cmd.command,
          params: cmd.params,
          tabId: cmd.tabId,
          apiKey: cmd.apiKey,
          timestamp: Date.now(),
        };
    
        this.client!.send(JSON.stringify(message));
      });
    }
Behavior3/5

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

Describes full access to page APIs, which is a key behavioral trait. However, without annotations, it should also disclose potential risks (e.g., page crashes, mutation side effects) and return behavior. The description is honest but not exhaustive.

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?

Two concise sentences. First sentence defines the core action, second sentence frames its role and gives examples. Highly efficient and front-loaded.

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

Completeness3/5

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

No output schema, so the description should explain return values. It does not mention that the return result of the JavaScript expression is returned. Also lacks error handling or promise resolution behavior. Given the tool's simplicity, this is a notable gap.

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?

Input schema covers 100% of parameters with descriptions. The description adds no extra meaning beyond what the schema already provides for each parameter. Baseline score is appropriate.

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?

Clearly states it executes JavaScript in the page, positions itself as an escape hatch, and provides concrete examples (extract data, modify page, trigger events, check values). Distinguishes from sibling tools that are more specific.

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

Usage Guidelines4/5

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

Explicitly frames the tool as an escape hatch for tasks other tools cannot do, implying use when other tools are insufficient. Lacks explicit 'when not to use' or alternative suggestions, but the sibling list provides context.

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/BrowserGenie/mcp'

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