Skip to content

Commit 2b731fb

Browse files
author
Mati Horovitz
committed
fix(fetch): fix puppeteer server to allow evaluate async functions
1 parent 2578d6f commit 2b731fb

File tree

1 file changed

+28
-17
lines changed

1 file changed

+28
-17
lines changed

src/puppeteer/index.ts

Lines changed: 28 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,15 @@ async function ensureBrowser() {
124124
return page!;
125125
}
126126

127+
declare global {
128+
interface Window {
129+
mcpHelper: {
130+
logs: string[],
131+
originalConsole: Partial<typeof console>,
132+
}
133+
}
134+
}
135+
127136
async function handleToolCall(name: string, args: any): Promise<{ toolResult: CallToolResult }> {
128137
const page = await ensureBrowser();
129138

@@ -285,33 +294,35 @@ async function handleToolCall(name: string, args: any): Promise<{ toolResult: Ca
285294

286295
case "puppeteer_evaluate":
287296
try {
288-
const result = await page.evaluate((script) => {
289-
const logs: string[] = [];
290-
const originalConsole = { ...console };
297+
await page.evaluate(() => {
298+
window.mcpHelper = {
299+
logs: [],
300+
originalConsole: { ...console },
301+
};
291302

292303
['log', 'info', 'warn', 'error'].forEach(method => {
293304
(console as any)[method] = (...args: any[]) => {
294-
logs.push(`[${method}] ${args.join(' ')}`);
295-
(originalConsole as any)[method](...args);
305+
window.mcpHelper.logs.push(`[${method}] ${args.join(' ')}`);
306+
(window.mcpHelper.originalConsole as any)[method](...args);
296307
};
297-
});
298-
299-
try {
300-
const result = eval(script);
301-
Object.assign(console, originalConsole);
302-
return { result, logs };
303-
} catch (error) {
304-
Object.assign(console, originalConsole);
305-
throw error;
306-
}
307-
}, args.script);
308+
} );
309+
} );
310+
311+
const result = await page.evaluate( args.script );
312+
313+
const logs = await page.evaluate(() => {
314+
Object.assign(console, window.mcpHelper.originalConsole);
315+
const logs = window.mcpHelper.logs;
316+
delete ( window.mcpHelper as any).logs;
317+
return logs;
318+
});
308319

309320
return {
310321
toolResult: {
311322
content: [
312323
{
313324
type: "text",
314-
text: `Execution result:\n${JSON.stringify(result.result, null, 2)}\n\nConsole output:\n${result.logs.join('\n')}`,
325+
text: `Execution result:\n${JSON.stringify(result, null, 2)}\n\nConsole output:\n${logs.join('\n')}`,
315326
},
316327
],
317328
isError: false,

0 commit comments

Comments
 (0)