|
| 1 | +/** |
| 2 | + * Copyright (c) Microsoft Corporation. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +import { fileURLToPath } from 'url'; |
| 18 | +import path from 'path'; |
| 19 | +import { z } from 'zod'; |
| 20 | +import { zodToJsonSchema } from 'zod-to-json-schema'; |
| 21 | + |
| 22 | + |
| 23 | +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; |
| 24 | +import { ListRootsRequestSchema, PingRequestSchema } from '@modelcontextprotocol/sdk/types.js'; |
| 25 | +import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; |
| 26 | +import * as mcpServer from '../mcp/server.js'; |
| 27 | +import { logUnhandledError } from '../utils/log.js'; |
| 28 | +import { packageJSON } from '../utils/package.js'; |
| 29 | + |
| 30 | +import { FullConfig } from '../config.js'; |
| 31 | +import { BrowserServerBackend } from '../browserServerBackend.js'; |
| 32 | +import { contextFactory } from '../browserContextFactory.js'; |
| 33 | +import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'; |
| 34 | +import type { ClientVersion, ServerBackend } from '../mcp/server.js'; |
| 35 | +import type { Root, Tool, CallToolResult, CallToolRequest } from '@modelcontextprotocol/sdk/types.js'; |
| 36 | + |
| 37 | +const contextSwitchOptions = z.object({ |
| 38 | + connectionString: z.string().optional().describe('The connection string to use to connect to the browser'), |
| 39 | + lib: z.string().optional().describe('The library to use for the connection'), |
| 40 | +}); |
| 41 | + |
| 42 | +class VSCodeProxyBackend implements ServerBackend { |
| 43 | + name = 'Playwright MCP Client Switcher'; |
| 44 | + version = packageJSON.version; |
| 45 | + |
| 46 | + private _currentClient: Client | undefined; |
| 47 | + private _contextSwitchTool: Tool; |
| 48 | + private _roots: Root[] = []; |
| 49 | + private _clientVersion?: ClientVersion; |
| 50 | + |
| 51 | + constructor(private readonly _config: FullConfig, private readonly _defaultTransportFactory: () => Promise<Transport>) { |
| 52 | + this._contextSwitchTool = this._defineContextSwitchTool(); |
| 53 | + } |
| 54 | + |
| 55 | + async initialize(clientVersion: ClientVersion, roots: Root[]): Promise<void> { |
| 56 | + this._clientVersion = clientVersion; |
| 57 | + this._roots = roots; |
| 58 | + const transport = await this._defaultTransportFactory(); |
| 59 | + await this._setCurrentClient(transport); |
| 60 | + } |
| 61 | + |
| 62 | + async listTools(): Promise<Tool[]> { |
| 63 | + const response = await this._currentClient!.listTools(); |
| 64 | + return [ |
| 65 | + ...response.tools, |
| 66 | + this._contextSwitchTool, |
| 67 | + ]; |
| 68 | + } |
| 69 | + |
| 70 | + async callTool(name: string, args: CallToolRequest['params']['arguments']): Promise<CallToolResult> { |
| 71 | + if (name === this._contextSwitchTool.name) |
| 72 | + return this._callContextSwitchTool(args as any); |
| 73 | + return await this._currentClient!.callTool({ |
| 74 | + name, |
| 75 | + arguments: args, |
| 76 | + }) as CallToolResult; |
| 77 | + } |
| 78 | + |
| 79 | + serverClosed?(): void { |
| 80 | + void this._currentClient?.close().catch(logUnhandledError); |
| 81 | + } |
| 82 | + |
| 83 | + private async _callContextSwitchTool(params: z.infer<typeof contextSwitchOptions>): Promise<CallToolResult> { |
| 84 | + if (!params.connectionString || !params.lib) { |
| 85 | + const transport = await this._defaultTransportFactory(); |
| 86 | + await this._setCurrentClient(transport); |
| 87 | + return { |
| 88 | + content: [{ type: 'text', text: '### Result\nSuccessfully disconnected.\n' }], |
| 89 | + }; |
| 90 | + } |
| 91 | + |
| 92 | + await this._setCurrentClient( |
| 93 | + new StdioClientTransport({ |
| 94 | + command: process.execPath, |
| 95 | + cwd: process.cwd(), |
| 96 | + args: [ |
| 97 | + path.join(fileURLToPath(import.meta.url), '..', 'main.js'), |
| 98 | + JSON.stringify(this._config), |
| 99 | + params.connectionString, |
| 100 | + params.lib, |
| 101 | + ], |
| 102 | + }) |
| 103 | + ); |
| 104 | + return { |
| 105 | + content: [{ type: 'text', text: '### Result\nSuccessfully connected.\n' }], |
| 106 | + }; |
| 107 | + } |
| 108 | + |
| 109 | + private _defineContextSwitchTool(): Tool { |
| 110 | + return { |
| 111 | + name: 'browser_connect', |
| 112 | + description: 'Do not call, this tool is used in the integration with the Playwright VS Code Extension and meant for programmatic usage only.', |
| 113 | + inputSchema: zodToJsonSchema(contextSwitchOptions, { strictUnions: true }) as Tool['inputSchema'], |
| 114 | + annotations: { |
| 115 | + title: 'Connect to a browser running in VS Code.', |
| 116 | + readOnlyHint: true, |
| 117 | + openWorldHint: false, |
| 118 | + }, |
| 119 | + }; |
| 120 | + } |
| 121 | + |
| 122 | + private async _setCurrentClient(transport: Transport) { |
| 123 | + await this._currentClient?.close(); |
| 124 | + this._currentClient = undefined; |
| 125 | + |
| 126 | + const client = new Client(this._clientVersion!); |
| 127 | + client.registerCapabilities({ |
| 128 | + roots: { |
| 129 | + listRoots: true, |
| 130 | + }, |
| 131 | + }); |
| 132 | + client.setRequestHandler(ListRootsRequestSchema, () => ({ roots: this._roots })); |
| 133 | + client.setRequestHandler(PingRequestSchema, () => ({})); |
| 134 | + |
| 135 | + await client.connect(transport); |
| 136 | + this._currentClient = client; |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +export async function runVSCodeTools(config: FullConfig) { |
| 141 | + const serverBackendFactory: mcpServer.ServerBackendFactory = { |
| 142 | + name: 'Playwright w/ vscode', |
| 143 | + nameInConfig: 'playwright-vscode', |
| 144 | + version: packageJSON.version, |
| 145 | + create: () => new VSCodeProxyBackend(config, () => mcpServer.wrapInProcess(new BrowserServerBackend(config, contextFactory(config)))) |
| 146 | + }; |
| 147 | + await mcpServer.start(serverBackendFactory, config.server); |
| 148 | + return; |
| 149 | +} |
0 commit comments