Skip to main content
Glama

evaluate_script

Execute JavaScript functions in a live Chrome browser page to retrieve JSON-serializable data for automation, debugging, or content extraction.

Instructions

Evaluate a JavaScript function inside the currently selected page. Returns the response as JSON so returned values have to JSON-serializable.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
functionYesA JavaScript function to run in the currently selected page. Example without arguments: `() => { return document.title }` or `async () => { return await fetch("example.com") }`. Example with arguments: `(el) => { return el.innerText; }`
argsNoAn optional list of arguments to pass to the function.

Implementation Reference

  • The main handler function for the 'evaluate_script' tool. It evaluates the provided JavaScript function on the currently selected page using Puppeteer, passes optional element arguments by UID, serializes the result to JSON, and appends the output to the response.
    handler: async (request, response, context) => {
      const page = context.getSelectedPage();
      const fn = await page.evaluateHandle(`(${request.params.function})`);
      const args: Array<JSHandle<unknown>> = [fn];
      try {
        for (const el of request.params.args ?? []) {
          args.push(await context.getElementByUid(el.uid));
        }
        await context.waitForEventsAfterAction(async () => {
          const result = await page.evaluate(
            async (fn, ...args) => {
              // @ts-expect-error no types.
              return JSON.stringify(await fn(...args));
            },
            ...args,
          );
          response.appendResponseLine('Script ran on page and returned:');
          response.appendResponseLine('```json');
          response.appendResponseLine(`${result}`);
          response.appendResponseLine('```');
        });
      } finally {
        Promise.allSettled(args.map(arg => arg.dispose())).catch(() => {
          // Ignore errors
        });
      }
    },
  • Zod schema defining the input parameters for the tool: 'function' (string describing the JS function to evaluate) and optional 'args' (array of {uid: string} for page elements).
      schema: {
        function: z.string().describe(
          `A JavaScript function to run in the currently selected page.
    Example without arguments: \`() => {
      return document.title
    }\` or \`async () => {
      return await fetch("example.com")
    }\`.
    Example with arguments: \`(el) => {
      return el.innerText;
    }\`
    `,
        ),
        args: z
          .array(
            z.object({
              uid: z
                .string()
                .describe(
                  'The uid of an element on the page from the page content snapshot',
                ),
            }),
          )
          .optional()
          .describe(`An optional list of arguments to pass to the function.`),
      },
  • The tool registration using defineTool, including name 'evaluate_script', description, annotations, schema, and handler.
    export const evaluateScript = defineTool({
      name: 'evaluate_script',
      description: `Evaluate a JavaScript function inside the currently selected page. Returns the response as JSON
    so returned values have to JSON-serializable.`,
      annotations: {
        category: ToolCategories.DEBUGGING,
        readOnlyHint: false,
      },
      schema: {
        function: z.string().describe(
          `A JavaScript function to run in the currently selected page.
    Example without arguments: \`() => {
      return document.title
    }\` or \`async () => {
      return await fetch("example.com")
    }\`.
    Example with arguments: \`(el) => {
      return el.innerText;
    }\`
    `,
        ),
        args: z
          .array(
            z.object({
              uid: z
                .string()
                .describe(
                  'The uid of an element on the page from the page content snapshot',
                ),
            }),
          )
          .optional()
          .describe(`An optional list of arguments to pass to the function.`),
      },
      handler: async (request, response, context) => {
        const page = context.getSelectedPage();
        const fn = await page.evaluateHandle(`(${request.params.function})`);
        const args: Array<JSHandle<unknown>> = [fn];
        try {
          for (const el of request.params.args ?? []) {
            args.push(await context.getElementByUid(el.uid));
          }
          await context.waitForEventsAfterAction(async () => {
            const result = await page.evaluate(
              async (fn, ...args) => {
                // @ts-expect-error no types.
                return JSON.stringify(await fn(...args));
              },
              ...args,
            );
            response.appendResponseLine('Script ran on page and returned:');
            response.appendResponseLine('```json');
            response.appendResponseLine(`${result}`);
            response.appendResponseLine('```');
          });
        } finally {
          Promise.allSettled(args.map(arg => arg.dispose())).catch(() => {
            // Ignore errors
          });
        }
      },
    });
Behavior4/5

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

Annotations provide readOnlyHint=false, indicating this is not a read-only operation. The description adds valuable context beyond annotations by specifying that it runs in 'the currently selected page' (implying a browser automation context) and that returned values must be JSON-serializable (a behavioral constraint). However, it doesn't disclose potential side effects, error handling, or execution limits that would be useful for a code execution tool.

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 only two sentences, both of which earn their place. The first sentence states the core functionality and context, while the second adds a critical constraint about JSON serialization. There is zero wasted text, and information is front-loaded effectively.

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?

For a tool that executes arbitrary JavaScript in a browser page (a complex operation with readOnlyHint=false), the description is somewhat incomplete. It lacks information about error handling, execution timeouts, security implications, or what happens if the page context changes. With no output schema and minimal behavioral disclosure, there are significant gaps for an agent to use this tool safely and effectively.

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 detailed examples for the 'function' parameter and clear documentation for 'args'. The description adds minimal semantic value beyond the schema, only reinforcing that the function runs in the page context. Since the schema already does the heavy lifting, the baseline score of 3 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?

The description clearly states the specific action ('Evaluate a JavaScript function') and resource ('inside the currently selected page'), distinguishing it from sibling tools like click, fill, or navigate_page which perform different browser interactions. It explicitly mentions the return format ('Returns the response as JSON'), which further clarifies its purpose.

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 for executing JavaScript in a browser context, but provides no explicit guidance on when to use this tool versus alternatives like list_console_messages or performance_analyze_insight. It mentions the requirement for JSON-serializable returns, which offers some contextual hint, but lacks clear when-to-use or when-not-to-use statements compared to siblings.

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/SHAY5555-gif/chrome-devtools-mcp'

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