Skip to content

Feature: Add evaluate_script_file tool to evaluate JavaScript files from the local filesystem #1775

Description

@achideal

Is your feature request related to a problem? Please describe.

When using the evaluate_script tool, the entire JavaScript code must be passed as a string parameter. This becomes problematic when:

  1. Large scripts: Scripts with hundreds of lines need to be passed entirely as a parameter, which is inefficient and can hit token limits in AI agent contexts.
  2. Complex scripts with special characters: Scripts containing template literals, regex patterns, or escaped characters can be mangled when passed as string parameters.
  3. Reusable scripts: When the same script needs to be executed multiple times across different pages, it must be re-sent each time rather than referenced from a file.
  4. Development workflow: Developers often have pre-written JavaScript files they want to inject into pages for testing, debugging, or automation purposes. Currently, they must manually copy-paste the file contents into the evaluate_script tool parameter.

Describe the solution you'd like

Add a new tool called evaluate_script_file that:

  1. Accepts a filePath parameter pointing to a local JavaScript file.
  2. Reads the file content from the local filesystem.
  3. Evaluates the JavaScript function defined in the file inside the currently selected page.
  4. Supports optional args parameter to pass arguments to the function (same as evaluate_script).
  5. Returns the result as JSON (same as evaluate_script).

Example usage:

Given a file /path/to/script.js containing:

(el) => {
  return el.innerText;
}

The tool would be called with:

{
  "filePath": "/path/to/script.js",
  "args": ["<element-uid>"]
}

This is essentially the file-based counterpart of the existing evaluate_script tool, similar to how many CLI tools support both inline and file-based input.

Describe alternatives you've considered

  1. Using evaluate_script with file content read by the AI agent: The agent could read the file first and then pass the content to evaluate_script. However, this wastes tokens by sending the script content through the AI context, and special characters may get corrupted during the string parameter encoding process.

  2. Using a wrapper script: Writing a small wrapper that uses fetch() or dynamic <script> injection. This is fragile and doesn't work for all use cases (e.g., scripts that need to return values).

  3. No alternative considered viable: The most natural and efficient approach is to have the MCP server read the file directly from the filesystem, avoiding any encoding issues and token overhead.

Additional context

I have already implemented this feature and submitted a PR: #1772. The implementation adds a new evaluate_script_file tool alongside the existing evaluate_script tool, reads the JavaScript file using fs.readFileSync with UTF-8 encoding, validates that the file exists and is readable, and supports the same args parameter for passing element UIDs or other arguments.

This feature is particularly useful for AI agent workflows where pre-written scripts need to be injected into web pages for automation, testing, or data extraction purposes.

Activity

  1. added theissue type on Mar 31, 2026
  2. OrKoN commented on Apr 1, 2026

    @OrKoN
    Collaborator

    I think if we execute a script from file we should not require it to be a function. Instead, it should support a classic or an ESM module (probably configurable). @natorion to chime in on the priority for something like this.

  3. marco-prontera commented on Apr 1, 2026

    @marco-prontera
    Contributor

    This could be useful also for #848

  4. jkellerer commented on Apr 21, 2026

    @jkellerer

    This feature is especially useful for injecting adapters that make it easier (faster) for AI to control standard frameworks or UIs build on top of them. Injecting adapters via evaluate_script unnecessarily fills the context (and even sometimes breaks for minified code as the model tries to read it without success).

  5. natorion commented on Apr 22, 2026

    @natorion
    Contributor

    I think if we execute a script from file we should not require it to be a function. Instead, it should support a classic or an ESM module (probably configurable). @natorion to chime in on the priority for something like this.

    I think we can settle on one format that we want to have. This would also be useful for use in our skills I think.

  6. achideal commented on Apr 24, 2026

    @achideal
    ContributorAuthor

    I think if we execute a script from file we should not require it to be a function. Instead, it should support a classic or an ESM module (probably configurable). @natorion to chime in on the priority for something like this.

    I think we can settle on one format that we want to have. This would also be useful for use in our skills I think.

    Thanks for the feedback @OrKoN @natorion!

    I agree that requiring a function expression wrapper for files is not ideal. Here's my updated proposal:

    Add a new evaluate_script_file tool with an explicit mode parameter:

    • mode: "function" (default) — file contains a function expression like (el) => el.innerText. Supports args (element UIDs). Same behavior as current evaluate_script.
    • mode: "script" — file contains classic JavaScript statements. Returns the last expression value (like running code in DevTools Console). No args support since there's no parameter list.

    Why explicit mode instead of auto-detection:

    • Clear contract — no ambiguity about how the file will be executed
    • Under the hood, function mode uses Runtime.callFunctionOn (supports passing ElementHandles as args), while script mode uses Runtime.evaluate directly

    Why not ESM: Runtime.evaluate parses code as Script grammar, where import/export are syntax errors. Supporting ESM would require a fundamentally different injection mechanism. We can revisit this later if needed.

    If this direction sounds good, I'd be happy to open a new PR with this approach.

  7. OrKoN commented on May 11, 2026

    @OrKoN
    Collaborator

    Thanks @achideal this sounds good to me.

  8. OrKoN commented on May 11, 2026

    @OrKoN
    Collaborator

    One suggestion, can we embed this functionality into existing evaluate script tool? I think it would benefit from the mode as well (perhaps "format" is a better name) and we can add an optional filePath and make function optional.

  9. achideal commented on May 19, 2026

    @achideal
    ContributorAuthor

    Thanks for the feedback @OrKoN! Quick heads-up before I open a new PR — the landscape has shifted slightly:

    Context: PR #2054 has been merged

    PR #2054 added an optional filePath parameter to evaluate_script, but its semantics are output redirection — it saves the script's return value to a file, not reading a script from a file. The original input-side use case we discussed (avoiding token waste by reading large pre-written scripts from disk) is still unmet.

    To avoid clashing with filePath's now-published meaning and to preserve full backward compatibility for existing users, skills, and AI agents, here's the updated proposal:

    Updated design

    Embed everything into the existing evaluate_script tool, with only additive changes:

    Parameter Status Description
    function changed: required → optional Inline JavaScript code. Mutually exclusive with sourcePath
    sourcePath new, optional Absolute or relative path to a JavaScript file. Mutually exclusive with function
    format new, optional, default "function" "function" keeps existing behavior; "script" runs the code as classic JS (returns last expression's value, no args support)
    filePath unchanged Output destination — keeps the meaning introduced in #2054
    args, dialogAction, pageId, serviceWorkerId unchanged

    Naming-wise I went with sourcePath (source code path) to avoid confusion with format: "script". Open to another name if you prefer.

    Backward compatibility — explicit guarantees

    This is the part I want to call out clearly, since existing skills and AI agents are actively using this tool:

    • All existing calls work unchanged. Any call to evaluate_script that provided only function behaves identically — format defaults to "function", which is the current behavior.
    • No required parameter is added. format is optional with a default; sourcePath is optional.
    • function's type is unchanged (still string); only its required flag flips to optional. From the AI agent's perspective, passing function continues to work exactly as before.
    • No parameter is renamed or removed. filePath keeps the output semantics from feat: support filePath in evaluate_script #2054.
    • No behavioral drift in existing code paths. The format === "function" branch reuses the current performEvaluation() logic unchanged.

    Behavior matrix

    function sourcePath format Behavior
    ✓ – function (default) Current behavior — unchanged
    ✓ – script Run inline code as classic script via Runtime.evaluate
    – ✓ function Read file, evaluate as function expression (supports args)
    – ✓ script Read file, run as classic script
    ✓ ✓ * Error: mutually exclusive
    – – * Error: must provide one

    Why these specific choices

    • Why not require format explicitly? It would break every existing call. Default "function" covers the dominant case with zero migration cost.

    • Why not support ESM? Runtime.evaluate parses code as Script grammar — import/export are syntax errors there. Supporting ESM would require a fundamentally different injection mechanism (e.g., <script type="module">), which loses the synchronous return value contract. Can revisit if real demand emerges.

    • Why allow format: "script" for both inline and file input (not just file)? Three reasons:

      1. It directly addresses the original concern in this thread — "we should not require it to be a function" — for both file and inline use cases.
      2. AI agents frequently need to execute quick exploratory scripts (think DevTools Console snippets) without wrapping them in a function. Forcing them to either write a temp file or wrap as IIFE just to use format: "script" would be friction without benefit.
      3. Once the implementation reads code from any source, switching between Runtime.callFunctionOn (function mode) and Runtime.evaluate (script mode) is a trivial branch — restricting it to file-only input would be an artificial limitation.
    • One naming caveat: when format: "script", the existing function parameter holds non-function code. We're accepting this as a documented historical naming — renaming function would be a breaking change against the published API. The parameter's describe() will clarify that its content's format is determined by format. This mirrors how eval() and new Function(body) accept either expressions or statements.

    Validation handled in handler (not schema-level)

    Two checks live in the handler since zod refine across multiple fields is awkward with the current tool-definition style:

    1. Exactly one of function / sourcePath must be provided.
    2. args cannot be combined with format: "script" (classic scripts have no parameter list).

    Error messages will guide users toward the right combination.


    If this direction looks good, I'll close my old PR (#1772) and open a fresh one against main, plus update docs/tool-reference.md and add tests covering the four valid cells of the behavior matrix.

  10. cloorc commented on May 24, 2026

    @cloorc

    This is necessary and useful for large script(that may contain long text but shouldn't be included in context).

  11. Lightning00Blade commented on Jun 23, 2026

    @Lightning00Blade
    Collaborator

    With #2054 I think we can close this as complete.
    Please leave a comment or open new feature request if something is missing.

  12. jkellerer commented on Jun 23, 2026

    @jkellerer

    @Lightning00Blade, #2054 is about saving the script’s output to a file. But this topic is about reading the script from a file. The case should not be closed.

  13. zyzyzyryxy commented on Jul 3, 2026

    @zyzyzyryxy
    Contributor

    I like the idea behind the new tool and see it better than all alternatives proposed. This would fix an issue I observed sometimes (#1896)

  14. added a commit that references this issue on Oct 1, 2026
    9cf47a4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions