Skip to content
Merged
Show file tree
Hide file tree
Changes from 16 commits
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
12 changes: 7 additions & 5 deletions src/mcp/proxyBackend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import type { Root, Tool, CallToolResult, CallToolRequest } from '@modelcontextp
export type MCPProvider = {
name: string;
description: string;
connect(): Promise<Transport>;
connect(options: any): Promise<Transport>;
};

export class ProxyBackend implements ServerBackend {
Expand All @@ -56,7 +56,7 @@ export class ProxyBackend implements ServerBackend {
this._roots = roots;
}

await this._setCurrentClient(this._mcpProviders[0]);
await this._setCurrentClient(this._mcpProviders[0], undefined);
}

async listTools(): Promise<Tool[]> {
Expand Down Expand Up @@ -88,7 +88,7 @@ export class ProxyBackend implements ServerBackend {
if (!factory)
throw new Error('Unknown connection method: ' + params.name);

await this._setCurrentClient(factory);
await this._setCurrentClient(factory, params.options);
return {
content: [{ type: 'text', text: '### Result\nSuccessfully changed connection method.\n' }],
};
Expand All @@ -106,9 +106,11 @@ export class ProxyBackend implements ServerBackend {
description: [
'Connect to a browser using one of the available methods:',
...this._mcpProviders.map(factory => `- "${factory.name}": ${factory.description}`),
`By default, you're connected to the first method. Only call this tool to change it.`,
].join('\n'),
inputSchema: zodToJsonSchema(z.object({
name: z.enum(this._mcpProviders.map(factory => factory.name) as [string, ...string[]]).default(this._mcpProviders[0].name).describe('The method to use to connect to the browser'),
options: z.any().optional().describe('Options for the connection method'),
}), { strictUnions: true }) as Tool['inputSchema'],
annotations: {
title: 'Connect to a browser context',
Expand All @@ -118,7 +120,7 @@ export class ProxyBackend implements ServerBackend {
};
}

private async _setCurrentClient(factory: MCPProvider) {
private async _setCurrentClient(factory: MCPProvider, options: any) {
await this._currentClient?.close();
this._currentClient = undefined;

Expand All @@ -131,7 +133,7 @@ export class ProxyBackend implements ServerBackend {
client.setRequestHandler(ListRootsRequestSchema, () => ({ roots: this._roots }));
client.setRequestHandler(PingRequestSchema, () => ({}));

const transport = await factory.connect();
const transport = await factory.connect(options);
await client.connect(transport);
this._currentClient = client;
}
Expand Down
9 changes: 7 additions & 2 deletions src/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { BrowserServerBackend } from './browserServerBackend.js';
import { ExtensionContextFactory } from './extension/extensionContextFactory.js';
import { InProcessTransport } from './mcp/inProcessTransport.js';

import { VSCodeMCPFactory } from './vscode/host.js';
import type { MCPProvider } from './mcp/proxyBackend.js';
import type { FullConfig } from './config.js';
import type { BrowserContextFactory } from './browserContextFactory.js';
Expand Down Expand Up @@ -87,8 +88,12 @@ program

const browserContextFactory = contextFactory(config);
const providers: MCPProvider[] = [mcpProviderForBrowserContextFactory(config, browserContextFactory)];
if (options.connectTool)
providers.push(mcpProviderForBrowserContextFactory(config, createExtensionContextFactory(config)));
if (options.connectTool) {
providers.push(
mcpProviderForBrowserContextFactory(config, createExtensionContextFactory(config)),
new VSCodeMCPFactory(config), // TODO: automatically add this based on the client name
);
}
await mcpTransport.start(() => new ProxyBackend(providers), config.server);
});

Expand Down
4 changes: 4 additions & 0 deletions src/vscode/DEPS.list
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[*]
../mcp/
../browserServerBackend.js
../browserContextFactory.js
44 changes: 44 additions & 0 deletions src/vscode/host.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
import type { FullConfig } from '../config.js';
import type { MCPProvider } from '../mcp/proxyBackend.js';

export class VSCodeMCPFactory implements MCPProvider {
name = 'vscode';
description = 'Connect to a browser running in the Playwright VS Code extension';

constructor(private readonly _config: FullConfig) {}

async connect(options: any): Promise<Transport> {
if (typeof options.connectionString !== 'string')
throw new Error('Missing options.connectionString');
if (typeof options.lib !== 'string')
throw new Error('Missing options.lib');

return new StdioClientTransport({
command: process.execPath,
cwd: process.cwd(),
args: [
new URL('./main.js', import.meta.url).pathname,
JSON.stringify(this._config),
options.connectionString,
options.lib,
],
});
}
}
70 changes: 70 additions & 0 deletions src/vscode/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import * as mcpServer from '../mcp/server.js';
import { BrowserServerBackend } from '../browserServerBackend.js';
import { BrowserContextFactory, ClientInfo } from '../browserContextFactory.js';
import type { FullConfig } from '../config.js';
import type { BrowserContext } from 'playwright-core';

class VSCodeBrowserContextFactory implements BrowserContextFactory {
name = 'vscode';
description = 'Connect to a browser running in the Playwright VS Code extension';

constructor(private _config: FullConfig, private _playwright: typeof import('playwright'), private _connectionString: string) {}

async createContext(clientInfo: ClientInfo, abortSignal: AbortSignal): Promise<{ browserContext: BrowserContext; close: () => Promise<void>; }> {
let launchOptions: any = this._config.browser.launchOptions;
if (this._config.browser.userDataDir) {
launchOptions = {
...launchOptions,
...this._config.browser.contextOptions,
userDataDir: this._config.browser.userDataDir,
};
}
const connectionString = new URL(this._connectionString);
connectionString.searchParams.set('launch-options', JSON.stringify(launchOptions));

const browserType = this._playwright.chromium; // it could also be firefox or webkit, we just need some browser type to call `connect` on
const browser = await browserType.connect(connectionString.toString());

const context = browser.contexts()[0] ?? await browser.newContext(this._config.browser.contextOptions);

return {
browserContext: context,
close: async () => {
await browser.close();
}
};
}
}

async function main(config: FullConfig, connectionString: string, lib: string) {
const playwright = await import(lib).then(mod => mod.default ?? mod);
const factory = new VSCodeBrowserContextFactory(config, playwright, connectionString);
await mcpServer.connect(
() => new BrowserServerBackend(config, factory),
new StdioServerTransport(),
false
);
}

await main(
JSON.parse(process.argv[2]),
process.argv[3],
process.argv[4]
);
57 changes: 57 additions & 0 deletions tests/vscode.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { test, expect } from './fixtures.js';

test('browser_connect(vscode) works', async ({ startClient, playwright, browserName }) => {
const { client } = await startClient({
args: ['--connect-tool'],
});

const server = await playwright[browserName].launchServer();

expect(await client.callTool({
name: 'browser_connect',
arguments: {
name: 'vscode',
options: {
connectionString: server.wsEndpoint(),
lib: new URL('./index.js', import.meta.resolve('playwright')).pathname,
}
}
})).toHaveResponse({
result: 'Successfully changed connection method.'
});

expect(await client.callTool({
name: 'browser_navigate',
arguments: {
url: 'data:text/html,foo'
}
})).toHaveResponse({
pageState: expect.stringContaining('foo'),
});

await server.close();

expect(await client.callTool({
name: 'browser_snapshot',
arguments: {}
}), 'it actually used the server').toHaveResponse({
isError: true,
result: expect.stringContaining('ECONNREFUSED')
});
});
Loading