Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

fix(mcp): normalize bare host URLs and loopback IP addresses (#43264)

Alok Pandey29b3472a6dfd
diff --git a/packages/playwright-core/src/tools/backend/tab.ts b/packages/playwright-core/src/tools/backend/tab.ts
index 5a3c7ae4e7..14eda321de 100644
--- a/packages/playwright-core/src/tools/backend/tab.ts
+++ b/packages/playwright-core/src/tools/backend/tab.ts
@@ -333,10 +333,9 @@ export class Tab extends EventEmitter<TabEventsInterface> {
}
async checkUrlAndNavigate(url: string): Promise<string> {
- try {
- new URL(url);
- } catch (e) {
- if (url.startsWith('localhost'))
+ const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(url) || /^(about|data|blob|javascript):/i.test(url);
+ if (!hasScheme) {
+ if (url.startsWith('localhost') || url.startsWith('127.0.0.1') || url.startsWith('0.0.0.0') || url.startsWith('[::1]'))
url = 'http://' + url;
else
url = 'https://' + url;
diff --git a/tests/mcp/cli-navigation.spec.ts b/tests/mcp/cli-navigation.spec.ts
index a9a4147876..9c12229d4a 100644
--- a/tests/mcp/cli-navigation.spec.ts
+++ b/tests/mcp/cli-navigation.spec.ts
@@ -88,6 +88,16 @@ test('open without url opens about:blank', async ({ cli }) => {
expect(output).toContain('- Page URL: about:blank');
});
+test('open with bare 127.0.0.1 and port', async ({ cli, server }) => {
+ const { output } = await cli('open', '127.0.0.1:' + server.PORT);
+ expect(output).toContain(`- Page URL: http://127.0.0.1:${server.PORT}/`);
+});
+
+test('open with bare localhost and port', async ({ cli, server }) => {
+ const { output } = await cli('open', 'localhost:' + server.PORT);
+ expect(output).toContain(`- Page URL: http://localhost:${server.PORT}/`);
+});
+
test('tab-new with url', async ({ cli, server }) => {
await cli('open');
const { output } = await cli('tab-new', server.HELLO_WORLD);
diff --git a/tests/mcp/core.spec.ts b/tests/mcp/core.spec.ts
index b15209da69..9f333ef056 100644
--- a/tests/mcp/core.spec.ts
+++ b/tests/mcp/core.spec.ts
@@ -30,6 +30,19 @@ test('browser_navigate', async ({ client, server }) => {
});
});
+test('browser_navigate with bare host', async ({ client, server }) => {
+ const urlWithoutScheme = server.HELLO_WORLD.replace(/^https?:\/\//, '');
+ expect(await client.callTool({
+ name: 'browser_navigate',
+ arguments: { url: urlWithoutScheme },
+ })).toHaveResponse({
+ code: `await page.goto('${server.HELLO_WORLD}');`,
+ page: `- Page URL: ${server.HELLO_WORLD}
+- Page Title: Title`,
+ snapshot: `- generic [active] [ref=e1]: Hello, world!`,
+ });
+});
+
test('browser_navigate surfaces non-2xx HTTP status', async ({ client, server }) => {
server.setRoute('/locked', (req, res) => {
res.writeHead(402, { 'Content-Type': 'text/html' });