@@ -22,7 +22,8 @@ const TOOLS: Tool[] = [
2222 inputSchema : {
2323 type : "object" ,
2424 properties : {
25- url : { type : "string" } ,
25+ url : { type : "string" , description : "URL to navigate to" } ,
26+ args : { type : "object" , description : "Puppeteer launch options. Default null. If changed and not null, browser restarts. Example: { headless: true, args: ['--no-sandbox'] }" } ,
2627 } ,
2728 required : [ "url" ] ,
2829 } ,
@@ -105,12 +106,26 @@ let browser: Browser | undefined;
105106let page : Page | undefined ;
106107const consoleLogs : string [ ] = [ ] ;
107108const screenshots = new Map < string , string > ( ) ;
109+ let prevArgs : any = null ;
110+
111+ async function ensureBrowser ( args : any ) {
112+ try {
113+ if ( ( browser && ! ( await browser . isConnected ( ) ) ) ||
114+ ( args && ( JSON . stringify ( args ) != JSON . stringify ( prevArgs ) ) ) ) {
115+ await browser . close ( ) ;
116+ browser = null ;
117+ }
118+ }
119+ catch ( error ) {
120+ browser = null ;
121+ }
122+
123+ prevArgs = args ;
108124
109- async function ensureBrowser ( ) {
110125 if ( ! browser ) {
111126 const npx_args = { headless : false }
112127 const docker_args = { headless : true , args : [ "--no-sandbox" , "--single-process" , "--no-zygote" ] }
113- browser = await puppeteer . launch ( process . env . DOCKER_CONTAINER ? docker_args : npx_args ) ;
128+ browser = await puppeteer . launch ( args || ( process . env . DOCKER_CONTAINER ? docker_args : npx_args ) ) ;
114129 const pages = await browser . pages ( ) ;
115130 page = pages [ 0 ] ;
116131
@@ -136,7 +151,7 @@ declare global {
136151}
137152
138153async function handleToolCall ( name : string , args : any ) : Promise < CallToolResult > {
139- const page = await ensureBrowser ( ) ;
154+ const page = await ensureBrowser ( args . args ) ;
140155
141156 switch ( name ) {
142157 case "puppeteer_navigate" :
@@ -285,15 +300,15 @@ async function handleToolCall(name: string, args: any): Promise<CallToolResult>
285300 window . mcpHelper . logs . push ( `[${ method } ] ${ args . join ( ' ' ) } ` ) ;
286301 ( window . mcpHelper . originalConsole as any ) [ method ] ( ...args ) ;
287302 } ;
288- } ) ;
289- } ) ;
303+ } ) ;
304+ } ) ;
290305
291- const result = await page . evaluate ( args . script ) ;
306+ const result = await page . evaluate ( args . script ) ;
292307
293308 const logs = await page . evaluate ( ( ) => {
294309 Object . assign ( console , window . mcpHelper . originalConsole ) ;
295310 const logs = window . mcpHelper . logs ;
296- delete ( window as any ) . mcpHelper ;
311+ delete ( window as any ) . mcpHelper ;
297312 return logs ;
298313 } ) ;
299314
0 commit comments