Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion packages/playwright-core/src/tools/backend/browserBackend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,22 @@ export class BrowserBackend implements ServerBackend {
let responseObject: mcpServer.CallToolResult;
try {
await tool.handle(context, parsedArguments, response);
for (const reason of context.drainPendingUnhandledRejections())
response.addError(formatRejectionReason(reason));
responseObject = await response.serialize();
this._sessionLog?.logResponse(name, parsedArguments, responseObject);
} catch (error: any) {
return formatError(String(error));
const messages = [String(error), ...context.drainPendingUnhandledRejections().map(formatRejectionReason)];
return formatError(messages.join('\n\n'));
} finally {
context.setRunningTool(undefined);
}
return responseObject;
}
}

function formatRejectionReason(reason: unknown): string {
if (reason instanceof Error)
return reason.stack ?? reason.message;
return String(reason);
}
12 changes: 12 additions & 0 deletions packages/playwright-core/src/tools/backend/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,16 +105,22 @@ export class Context {
private _disposables: Disposable[] = [];

private _runningToolName: string | undefined;
private _pendingUnhandledRejections: unknown[] = [];
private _onUnhandledRejection = (reason: unknown) => {
this._pendingUnhandledRejections.push(reason);
};

constructor(browserContext: playwrightTypes.BrowserContext, options: ContextOptions) {
this.config = options.config;
this.sessionLog = options.sessionLog;
this.options = options;
this._rawBrowserContext = browserContext;
testDebug('create context');
process.on('unhandledRejection', this._onUnhandledRejection);
}

async dispose() {
process.off('unhandledRejection', this._onUnhandledRejection);
await disposeAll(this._disposables);
for (const tab of this._tabs)
await tab.dispose();
Expand All @@ -123,6 +129,12 @@ export class Context {
await this.stopVideoRecording();
}

drainPendingUnhandledRejections(): unknown[] {
const reasons = this._pendingUnhandledRejections.slice();
this._pendingUnhandledRejections.length = 0;
return reasons;
}

debugger() {
return this._rawBrowserContext.debugger;
}
Expand Down
34 changes: 34 additions & 0 deletions tests/mcp/run-code.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,40 @@ test('browser_run_code return value', async ({ client, server }) => {
expect(content).toContain('[LOG] Submit');
});

test('browser_run_code route handler exception keeps server alive', async ({ client, server }) => {
server.setContent('/', '<button>Submit</button>', 'text/html');
await client.callTool({
name: 'browser_navigate',
arguments: { url: server.PREFIX },
});

const code = `async (page) => {
await page.unroute('**/*').catch(() => {});
await page.route('**/route-throws.json', async (route) => {
const path = new URL(route.request().url()).pathname;
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ path }) });
});
return await page.evaluate(async () => {
const response = await fetch('/route-throws.json');
return response.text();
});
}`;
expect(await client.callTool({
name: 'browser_run_code',
arguments: { code },
})).toHaveResponse({
error: expect.stringContaining('ReferenceError: URL is not defined'),
isError: true,
});

// Subsequent tool calls should still work because the transport remains alive.
const followUp = await client.callTool({
name: 'browser_tabs',
arguments: { action: 'list' },
});
expect(followUp.isError).toBeFalsy();
});

test('browser_run_code with filename', async ({ client, server }) => {
server.setContent('/', `
<button onclick="console.log('Clicked')">Click</button>
Expand Down
Loading