Skip to main content
Glama

browser_evaluate

Execute JavaScript directly in the browser context to manipulate DOM elements, interact with web content, or perform API requests for autonomous browser automation.

Instructions

Execute JavaScript in the browser context

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
scriptYesJavaScript code to execute

Implementation Reference

  • The handler function that executes the provided JavaScript code in the browser context using Playwright's page.evaluate, captures overridden console logs, and returns the evaluation result along with any console output.
    async function handleBrowserEvaluate(page: Page, args: any): Promise<{ toolResult: CallToolResult }> {
      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: `Script result: ${JSON.stringify(result.result, null, 2)}`,
              },
              {
                type: "text",
                text: `Console 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,
          },
        };
      }
    }
  • Defines the tool schema including name, description, and input schema requiring a 'script' string parameter.
    {
      name: "browser_evaluate",
      description: "Execute JavaScript in the browser context",
      inputSchema: {
        type: "object",
        properties: {
          script: { type: "string", description: "JavaScript code to execute" }
        },
        required: ["script"]
      }
    },
  • Registers the tool name in the switch statement within executeToolCall, dispatching to the specific handler.
    case "browser_evaluate":
      return await handleBrowserEvaluate(activePage!, args);
  • src/index.ts:79-80 (registration)
    Calls registerTools() to get the list of tools including browser_evaluate and passes it to setupHandlers for MCP server registration.
    const tools = registerTools();
    setupHandlers(server, tools);
  • Includes 'browser_evaluate' in the BROWSER_TOOLS array used to identify browser-related tools and initialize the browser.
    export const BROWSER_TOOLS = [
      "browser_navigate",
      "browser_screenshot",
      "browser_click",
      "browser_fill",
      "browser_select",
      "browser_hover",
      "browser_evaluate",
      "browser_set_viewport"
    ];
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. While 'Execute JavaScript' implies a potentially powerful operation, it doesn't clarify safety aspects (e.g., whether it can modify page state, require specific permissions, or have side effects), execution context (e.g., runs in the current page), or error handling. This leaves significant gaps for an agent to understand risks and 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 a single, direct sentence with zero wasted words. It front-loads the core action ('Execute JavaScript') and specifies the context ('in the browser context'), making it highly efficient and easy to parse.

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 in a browser (a powerful operation with potential side effects), the description is insufficient. With no annotations, no output schema, and minimal behavioral context, it fails to provide necessary details like what the tool returns, how errors are handled, or security implications. This leaves the agent with inadequate information for safe and effective use.

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 single parameter 'script' clearly documented in the schema as 'JavaScript code to execute'. The description doesn't add any meaningful semantics beyond this, such as examples of valid scripts, return value expectations, or common use cases. The baseline of 3 is appropriate since the schema adequately covers the parameter.

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 verb ('Execute') and resource ('JavaScript in the browser context'), making the purpose immediately understandable. However, it doesn't explicitly differentiate from sibling tools like browser_click or browser_navigate, which also operate in the browser context but perform different actions.

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 preferable to using other browser tools (like browser_click for interactions) or API tools, nor does it specify prerequisites or constraints for usage.

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/imprvhub/mcp-browser-agent'

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