44 * SPDX-License-Identifier: Apache-2.0
55 */
66
7- import { type Page , zod , ajv , type JSONSchema7 } from '../third_party/index.js' ;
7+ import { zod , ajv , type JSONSchema7 , type ElementHandle } from '../third_party/index.js' ;
88
99import { ToolCategory } from './categories.js' ;
1010import { defineTool } from './ToolDefinition.js' ;
@@ -57,6 +57,17 @@ export const executeInPageTool = defineTool({
5757 const toolName = request . params . toolName ;
5858 const params = request . params . params ?? { } ;
5959
60+ // Creates array of ElementHandles from the uids in the params.
61+ // We do not replace the uids with the ElementsHandles yet, because
62+ // the `evaluate` function only turns them into DOM elements if they
63+ // are passed as non-nested arguments.
64+ const handles : ElementHandle [ ] = [ ] ;
65+ for ( const value of Object . values ( params ) ) {
66+ if ( value instanceof Object && 'uid' in value && typeof value . uid === 'string' ) {
67+ handles . push ( await context . getElementByUid ( value . uid ) ) ;
68+ }
69+ }
70+
6071 // Get tools from context
6172 const toolGroup = context . getInPageTools ( ) ;
6273 // Alternatively: get tools from page
@@ -73,7 +84,14 @@ export const executeInPageTool = defineTool({
7384 throw new Error ( `Invalid parameters for tool ${ toolName } : ${ ajvInstance . errorsText ( validate . errors ) } ` ) ;
7485 }
7586
76- const result = await page . evaluate ( async ( name , args ) => {
87+ const result = await page . evaluate ( async ( name , args , ...elements ) => {
88+ // Replace the uids with DOM elements.
89+ for ( const [ key , value ] of Object . entries ( args ) ) {
90+ if ( value instanceof Object && 'uid' in value && typeof value . uid === 'string' ) {
91+ args [ key ] = elements . shift ( ) ;
92+ }
93+ }
94+
7795 if ( ! window . __mcp_tool_group ) {
7896 throw new Error ( 'No tools found on the page' ) ;
7997 }
@@ -82,7 +100,7 @@ export const executeInPageTool = defineTool({
82100 return await tool . execute ( args ) ;
83101 }
84102 throw new Error ( `Tool ${ name } not found` ) ;
85- } , toolName , params ) ;
103+ } , toolName , params , ... handles ) ;
86104 response . appendResponseLine ( typeof result === 'string' ? result : JSON . stringify ( result , null , 2 ) ) ;
87105 } ,
88106} ) ;
0 commit comments