Description
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:
- 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.
- Complex scripts with special characters: Scripts containing template literals, regex patterns, or escaped characters can be mangled when passed as string parameters.
- 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.
- 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_scripttool parameter.
Describe the solution you'd like
Add a new tool called evaluate_script_file that:
- Accepts a
filePathparameter pointing to a local JavaScript file. - Reads the file content from the local filesystem.
- Evaluates the JavaScript function defined in the file inside the currently selected page.
- Supports optional
argsparameter to pass arguments to the function (same asevaluate_script). - 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
-
Using
evaluate_scriptwith file content read by the AI agent: The agent could read the file first and then pass the content toevaluate_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. -
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). -
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
OrKoN commentedon Apr 1, 2026
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.
marco-prontera commentedon Apr 1, 2026
This could be useful also for #848
jkellerer commentedon Apr 21, 2026
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_scriptunnecessarily fills the context (and even sometimes breaks for minified code as the model tries to read it without success).natorion commentedon Apr 22, 2026
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.
achideal commentedon Apr 24, 2026
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_filetool with an explicitmodeparameter:mode: "function"(default) — file contains a function expression like(el) => el.innerText. Supportsargs(element UIDs). Same behavior as currentevaluate_script.mode: "script"— file contains classic JavaScript statements. Returns the last expression value (like running code in DevTools Console). Noargssupport since there's no parameter list.Why explicit
modeinstead of auto-detection:functionmode usesRuntime.callFunctionOn(supports passing ElementHandles as args), whilescriptmode usesRuntime.evaluatedirectlyWhy not ESM:
Runtime.evaluateparses code as Script grammar, whereimport/exportare 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.
OrKoN commentedon May 11, 2026
Thanks @achideal this sounds good to me.
OrKoN commentedon May 11, 2026
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
functionoptional.achideal commentedon May 19, 2026
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
filePathparameter toevaluate_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_scripttool, with only additive changes:functionsourcePathsourcePathfunctionformat"function""function"keeps existing behavior;"script"runs the code as classic JS (returns last expression's value, noargssupport)filePathargs,dialogAction,pageId,serviceWorkerIdNaming-wise I went with
sourcePath(source code path) to avoid confusion withformat: "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:
evaluate_scriptthat provided onlyfunctionbehaves identically —formatdefaults to"function", which is the current behavior.formatis optional with a default;sourcePathis optional.function's type is unchanged (stillstring); only itsrequiredflag flips to optional. From the AI agent's perspective, passingfunctioncontinues to work exactly as before.filePathkeeps the output semantics from feat: support filePath in evaluate_script #2054.format === "function"branch reuses the currentperformEvaluation()logic unchanged.Behavior matrix
functionsourcePathformatfunction(default)scriptRuntime.evaluatefunctionargs)scriptWhy these specific choices
Why not require
formatexplicitly? It would break every existing call. Default"function"covers the dominant case with zero migration cost.Why not support ESM?
Runtime.evaluateparses code as Script grammar —import/exportare 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:format: "script"would be friction without benefit.Runtime.callFunctionOn(function mode) andRuntime.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 existingfunctionparameter holds non-function code. We're accepting this as a documented historical naming — renamingfunctionwould be a breaking change against the published API. The parameter'sdescribe()will clarify that its content's format is determined byformat. This mirrors howeval()andnew 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:
function/sourcePathmust be provided.argscannot be combined withformat: "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 updatedocs/tool-reference.mdand add tests covering the four valid cells of the behavior matrix.cloorc commentedon May 24, 2026
This is necessary and useful for large script(that may contain long text but shouldn't be included in context).
Lightning00Blade commentedon Jun 23, 2026
With #2054 I think we can close this as complete.
Please leave a comment or open new feature request if something is missing.
jkellerer commentedon Jun 23, 2026
@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.
zyzyzyryxy commentedon Jul 3, 2026
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)
feat: support evaluating scripts from local files (ChromeDevTools#2606)