@playwright/mcp 0.0.36-alpha-2025-09-04 → 0.0.37-alpha-2025-09-08

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +81 -46
  2. package/cli.js +7 -1
  3. package/config.d.ts +24 -0
  4. package/index.js +1 -1
  5. package/package.json +14 -39
  6. package/lib/browser/browserContextFactory.js +0 -251
  7. package/lib/browser/browserServerBackend.js +0 -79
  8. package/lib/browser/codegen.js +0 -54
  9. package/lib/browser/config.js +0 -263
  10. package/lib/browser/context.js +0 -223
  11. package/lib/browser/response.js +0 -165
  12. package/lib/browser/sessionLog.js +0 -126
  13. package/lib/browser/tab.js +0 -251
  14. package/lib/browser/tools/common.js +0 -57
  15. package/lib/browser/tools/console.js +0 -35
  16. package/lib/browser/tools/dialogs.js +0 -49
  17. package/lib/browser/tools/evaluate.js +0 -88
  18. package/lib/browser/tools/files.js +0 -46
  19. package/lib/browser/tools/form.js +0 -92
  20. package/lib/browser/tools/install.js +0 -57
  21. package/lib/browser/tools/keyboard.js +0 -113
  22. package/lib/browser/tools/mouse.js +0 -101
  23. package/lib/browser/tools/navigate.js +0 -56
  24. package/lib/browser/tools/network.js +0 -43
  25. package/lib/browser/tools/pdf.js +0 -76
  26. package/lib/browser/tools/screenshot.js +0 -115
  27. package/lib/browser/tools/snapshot.js +0 -175
  28. package/lib/browser/tools/tabs.js +0 -61
  29. package/lib/browser/tools/tool.js +0 -37
  30. package/lib/browser/tools/utils.js +0 -79
  31. package/lib/browser/tools/verify.js +0 -172
  32. package/lib/browser/tools/wait.js +0 -57
  33. package/lib/browser/tools.js +0 -61
  34. package/lib/extension/cdpRelay.js +0 -395
  35. package/lib/extension/extensionContextFactory.js +0 -93
  36. package/lib/extension/protocol.js +0 -21
  37. package/lib/index.js +0 -75
  38. package/lib/log.js +0 -28
  39. package/lib/package.js +0 -24
  40. package/lib/program.js +0 -161
  41. package/lib/sdk/bundle.js +0 -79
  42. package/lib/sdk/http.js +0 -175
  43. package/lib/sdk/inProcessTransport.js +0 -67
  44. package/lib/sdk/manualPromise.js +0 -113
  45. package/lib/sdk/mdb.js +0 -237
  46. package/lib/sdk/proxyBackend.js +0 -141
  47. package/lib/sdk/server.js +0 -164
  48. package/lib/sdk/tool.js +0 -36
  49. package/lib/vscode/host.js +0 -199
  50. package/lib/vscode/main.js +0 -97
package/lib/index.js DELETED
@@ -1,75 +0,0 @@
1
- "use strict";
2
- /**
3
- * Copyright (c) Microsoft Corporation.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
- if (k2 === undefined) k2 = k;
19
- var desc = Object.getOwnPropertyDescriptor(m, k);
20
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
- desc = { enumerable: true, get: function() { return m[k]; } };
22
- }
23
- Object.defineProperty(o, k2, desc);
24
- }) : (function(o, m, k, k2) {
25
- if (k2 === undefined) k2 = k;
26
- o[k2] = m[k];
27
- }));
28
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
29
- Object.defineProperty(o, "default", { enumerable: true, value: v });
30
- }) : function(o, v) {
31
- o["default"] = v;
32
- });
33
- var __importStar = (this && this.__importStar) || (function () {
34
- var ownKeys = function(o) {
35
- ownKeys = Object.getOwnPropertyNames || function (o) {
36
- var ar = [];
37
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
38
- return ar;
39
- };
40
- return ownKeys(o);
41
- };
42
- return function (mod) {
43
- if (mod && mod.__esModule) return mod;
44
- var result = {};
45
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
46
- __setModuleDefault(result, mod);
47
- return result;
48
- };
49
- })();
50
- Object.defineProperty(exports, "__esModule", { value: true });
51
- exports.createConnection = createConnection;
52
- const browserServerBackend_1 = require("./browser/browserServerBackend");
53
- const config_1 = require("./browser/config");
54
- const browserContextFactory_1 = require("./browser/browserContextFactory");
55
- const mcpServer = __importStar(require("./sdk/server"));
56
- const package_1 = require("./package");
57
- async function createConnection(userConfig = {}, contextGetter) {
58
- const config = await (0, config_1.resolveConfig)(userConfig);
59
- const factory = contextGetter ? new SimpleBrowserContextFactory(contextGetter) : (0, browserContextFactory_1.contextFactory)(config);
60
- return mcpServer.createServer('Playwright', package_1.packageJSON.version, new browserServerBackend_1.BrowserServerBackend(config, factory), false);
61
- }
62
- class SimpleBrowserContextFactory {
63
- constructor(contextGetter) {
64
- this.name = 'custom';
65
- this.description = 'Connect to a browser using a custom context getter';
66
- this._contextGetter = contextGetter;
67
- }
68
- async createContext() {
69
- const browserContext = await this._contextGetter();
70
- return {
71
- browserContext,
72
- close: () => browserContext.close()
73
- };
74
- }
75
- }
package/lib/log.js DELETED
@@ -1,28 +0,0 @@
1
- "use strict";
2
- /**
3
- * Copyright (c) Microsoft Corporation.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- var __importDefault = (this && this.__importDefault) || function (mod) {
18
- return (mod && mod.__esModule) ? mod : { "default": mod };
19
- };
20
- Object.defineProperty(exports, "__esModule", { value: true });
21
- exports.testDebug = void 0;
22
- exports.logUnhandledError = logUnhandledError;
23
- const debug_1 = __importDefault(require("debug"));
24
- const errorsDebug = (0, debug_1.default)('pw:mcp:errors');
25
- function logUnhandledError(error) {
26
- errorsDebug(error);
27
- }
28
- exports.testDebug = (0, debug_1.default)('pw:mcp:test');
package/lib/package.js DELETED
@@ -1,24 +0,0 @@
1
- "use strict";
2
- /**
3
- * Copyright (c) Microsoft Corporation.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- var __importDefault = (this && this.__importDefault) || function (mod) {
18
- return (mod && mod.__esModule) ? mod : { "default": mod };
19
- };
20
- Object.defineProperty(exports, "__esModule", { value: true });
21
- exports.packageJSON = void 0;
22
- const fs_1 = __importDefault(require("fs"));
23
- const path_1 = __importDefault(require("path"));
24
- exports.packageJSON = JSON.parse(fs_1.default.readFileSync(path_1.default.join(__dirname, '..', 'package.json'), 'utf8'));
package/lib/program.js DELETED
@@ -1,161 +0,0 @@
1
- "use strict";
2
- /**
3
- * Copyright (c) Microsoft Corporation.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
- if (k2 === undefined) k2 = k;
19
- var desc = Object.getOwnPropertyDescriptor(m, k);
20
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
- desc = { enumerable: true, get: function() { return m[k]; } };
22
- }
23
- Object.defineProperty(o, k2, desc);
24
- }) : (function(o, m, k, k2) {
25
- if (k2 === undefined) k2 = k;
26
- o[k2] = m[k];
27
- }));
28
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
29
- Object.defineProperty(o, "default", { enumerable: true, value: v });
30
- }) : function(o, v) {
31
- o["default"] = v;
32
- });
33
- var __importStar = (this && this.__importStar) || (function () {
34
- var ownKeys = function(o) {
35
- ownKeys = Object.getOwnPropertyNames || function (o) {
36
- var ar = [];
37
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
38
- return ar;
39
- };
40
- return ownKeys(o);
41
- };
42
- return function (mod) {
43
- if (mod && mod.__esModule) return mod;
44
- var result = {};
45
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
46
- __setModuleDefault(result, mod);
47
- return result;
48
- };
49
- })();
50
- Object.defineProperty(exports, "__esModule", { value: true });
51
- const commander_1 = require("commander");
52
- const mcpServer = __importStar(require("./sdk/server"));
53
- const config_1 = require("./browser/config");
54
- const package_1 = require("./package");
55
- const context_1 = require("./browser/context");
56
- const browserContextFactory_1 = require("./browser/browserContextFactory");
57
- const proxyBackend_1 = require("./sdk/proxyBackend");
58
- const browserServerBackend_1 = require("./browser/browserServerBackend");
59
- const extensionContextFactory_1 = require("./extension/extensionContextFactory");
60
- const host_1 = require("./vscode/host");
61
- commander_1.program
62
- .version('Version ' + package_1.packageJSON.version)
63
- .name(package_1.packageJSON.name)
64
- .option('--allowed-origins <origins>', 'semicolon-separated list of origins to allow the browser to request. Default is to allow all.', config_1.semicolonSeparatedList)
65
- .option('--blocked-origins <origins>', 'semicolon-separated list of origins to block the browser from requesting. Blocklist is evaluated before allowlist. If used without the allowlist, requests not matching the blocklist are still allowed.', config_1.semicolonSeparatedList)
66
- .option('--block-service-workers', 'block service workers')
67
- .option('--browser <browser>', 'browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.')
68
- .option('--caps <caps>', 'comma-separated list of additional capabilities to enable, possible values: vision, pdf.', config_1.commaSeparatedList)
69
- .option('--cdp-endpoint <endpoint>', 'CDP endpoint to connect to.')
70
- .option('--config <path>', 'path to the configuration file.')
71
- .option('--device <device>', 'device to emulate, for example: "iPhone 15"')
72
- .option('--executable-path <path>', 'path to the browser executable.')
73
- .option('--extension', 'Connect to a running browser instance (Edge/Chrome only). Requires the "Playwright MCP Bridge" browser extension to be installed.')
74
- .option('--headless', 'run browser in headless mode, headed by default')
75
- .option('--host <host>', 'host to bind server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.')
76
- .option('--ignore-https-errors', 'ignore https errors')
77
- .option('--isolated', 'keep the browser profile in memory, do not save it to disk.')
78
- .option('--image-responses <mode>', 'whether to send image responses to the client. Can be "allow" or "omit", Defaults to "allow".')
79
- .option('--no-sandbox', 'disable the sandbox for all process types that are normally sandboxed.')
80
- .option('--output-dir <path>', 'path to the directory for output files.')
81
- .option('--port <port>', 'port to listen on for SSE transport.')
82
- .option('--proxy-bypass <bypass>', 'comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com"')
83
- .option('--proxy-server <proxy>', 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"')
84
- .option('--save-session', 'Whether to save the Playwright MCP session into the output directory.')
85
- .option('--save-trace', 'Whether to save the Playwright Trace of the session into the output directory.')
86
- .option('--storage-state <path>', 'path to the storage state file for isolated sessions.')
87
- .option('--user-agent <ua string>', 'specify user agent string')
88
- .option('--user-data-dir <path>', 'path to the user data directory. If not specified, a temporary directory will be created.')
89
- .option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"')
90
- .addOption(new commander_1.Option('--connect-tool', 'Allow to switch between different browser connection methods.').hideHelp())
91
- .addOption(new commander_1.Option('--vscode', 'VS Code tools.').hideHelp())
92
- .addOption(new commander_1.Option('--vision', 'Legacy option, use --caps=vision instead').hideHelp())
93
- .action(async (options) => {
94
- setupExitWatchdog();
95
- if (options.vision) {
96
- // eslint-disable-next-line no-console
97
- console.error('The --vision option is deprecated, use --caps=vision instead');
98
- options.caps = 'vision';
99
- }
100
- const config = await (0, config_1.resolveCLIConfig)(options);
101
- const browserContextFactory = (0, browserContextFactory_1.contextFactory)(config);
102
- const extensionContextFactory = new extensionContextFactory_1.ExtensionContextFactory(config.browser.launchOptions.channel || 'chrome', config.browser.userDataDir, config.browser.launchOptions.executablePath);
103
- if (options.extension) {
104
- const serverBackendFactory = {
105
- name: 'Playwright w/ extension',
106
- nameInConfig: 'playwright-extension',
107
- version: package_1.packageJSON.version,
108
- create: () => new browserServerBackend_1.BrowserServerBackend(config, extensionContextFactory)
109
- };
110
- await mcpServer.start(serverBackendFactory, config.server);
111
- return;
112
- }
113
- if (options.vscode) {
114
- await (0, host_1.runVSCodeTools)(config);
115
- return;
116
- }
117
- if (options.connectTool) {
118
- const providers = [
119
- {
120
- name: 'default',
121
- description: 'Starts standalone browser',
122
- connect: () => mcpServer.wrapInProcess(new browserServerBackend_1.BrowserServerBackend(config, browserContextFactory)),
123
- },
124
- {
125
- name: 'extension',
126
- description: 'Connect to a browser using the Playwright MCP extension',
127
- connect: () => mcpServer.wrapInProcess(new browserServerBackend_1.BrowserServerBackend(config, extensionContextFactory)),
128
- },
129
- ];
130
- const factory = {
131
- name: 'Playwright w/ switch',
132
- nameInConfig: 'playwright-switch',
133
- version: package_1.packageJSON.version,
134
- create: () => new proxyBackend_1.ProxyBackend(providers),
135
- };
136
- await mcpServer.start(factory, config.server);
137
- return;
138
- }
139
- const factory = {
140
- name: 'Playwright',
141
- nameInConfig: 'playwright',
142
- version: package_1.packageJSON.version,
143
- create: () => new browserServerBackend_1.BrowserServerBackend(config, browserContextFactory)
144
- };
145
- await mcpServer.start(factory, config.server);
146
- });
147
- function setupExitWatchdog() {
148
- let isExiting = false;
149
- const handleExit = async () => {
150
- if (isExiting)
151
- return;
152
- isExiting = true;
153
- setTimeout(() => process.exit(0), 15000);
154
- await context_1.Context.disposeAll();
155
- process.exit(0);
156
- };
157
- process.stdin.on('close', handleExit);
158
- process.on('SIGINT', handleExit);
159
- process.on('SIGTERM', handleExit);
160
- }
161
- void commander_1.program.parseAsync(process.argv);
package/lib/sdk/bundle.js DELETED
@@ -1,79 +0,0 @@
1
- "use strict";
2
- /**
3
- * Copyright (c) Microsoft Corporation.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
- if (k2 === undefined) k2 = k;
19
- var desc = Object.getOwnPropertyDescriptor(m, k);
20
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
- desc = { enumerable: true, get: function() { return m[k]; } };
22
- }
23
- Object.defineProperty(o, k2, desc);
24
- }) : (function(o, m, k, k2) {
25
- if (k2 === undefined) k2 = k;
26
- o[k2] = m[k];
27
- }));
28
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
29
- Object.defineProperty(o, "default", { enumerable: true, value: v });
30
- }) : function(o, v) {
31
- o["default"] = v;
32
- });
33
- var __importStar = (this && this.__importStar) || (function () {
34
- var ownKeys = function(o) {
35
- ownKeys = Object.getOwnPropertyNames || function (o) {
36
- var ar = [];
37
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
38
- return ar;
39
- };
40
- return ownKeys(o);
41
- };
42
- return function (mod) {
43
- if (mod && mod.__esModule) return mod;
44
- var result = {};
45
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
46
- __setModuleDefault(result, mod);
47
- return result;
48
- };
49
- })();
50
- Object.defineProperty(exports, "__esModule", { value: true });
51
- exports.z = exports.PingRequestSchema = exports.ListToolsRequestSchema = exports.ListRootsRequestSchema = exports.CallToolRequestSchema = exports.StreamableHTTPServerTransport = exports.StreamableHTTPClientTransport = exports.StdioServerTransport = exports.StdioClientTransport = exports.SSEServerTransport = exports.Server = exports.Client = exports.zodToJsonSchema = void 0;
52
- // @ts-ignore
53
- const bundle = __importStar(require("playwright/lib/mcpBundleImpl"));
54
- const zodToJsonSchema = bundle.zodToJsonSchema;
55
- exports.zodToJsonSchema = zodToJsonSchema;
56
- const Client = bundle.Client;
57
- exports.Client = Client;
58
- const Server = bundle.Server;
59
- exports.Server = Server;
60
- const SSEServerTransport = bundle.SSEServerTransport;
61
- exports.SSEServerTransport = SSEServerTransport;
62
- const StdioClientTransport = bundle.StdioClientTransport;
63
- exports.StdioClientTransport = StdioClientTransport;
64
- const StdioServerTransport = bundle.StdioServerTransport;
65
- exports.StdioServerTransport = StdioServerTransport;
66
- const StreamableHTTPServerTransport = bundle.StreamableHTTPServerTransport;
67
- exports.StreamableHTTPServerTransport = StreamableHTTPServerTransport;
68
- const StreamableHTTPClientTransport = bundle.StreamableHTTPClientTransport;
69
- exports.StreamableHTTPClientTransport = StreamableHTTPClientTransport;
70
- const CallToolRequestSchema = bundle.CallToolRequestSchema;
71
- exports.CallToolRequestSchema = CallToolRequestSchema;
72
- const ListRootsRequestSchema = bundle.ListRootsRequestSchema;
73
- exports.ListRootsRequestSchema = ListRootsRequestSchema;
74
- const ListToolsRequestSchema = bundle.ListToolsRequestSchema;
75
- exports.ListToolsRequestSchema = ListToolsRequestSchema;
76
- const PingRequestSchema = bundle.PingRequestSchema;
77
- exports.PingRequestSchema = PingRequestSchema;
78
- const z = bundle.z;
79
- exports.z = z;
package/lib/sdk/http.js DELETED
@@ -1,175 +0,0 @@
1
- "use strict";
2
- /**
3
- * Copyright (c) Microsoft Corporation.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
- if (k2 === undefined) k2 = k;
19
- var desc = Object.getOwnPropertyDescriptor(m, k);
20
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
- desc = { enumerable: true, get: function() { return m[k]; } };
22
- }
23
- Object.defineProperty(o, k2, desc);
24
- }) : (function(o, m, k, k2) {
25
- if (k2 === undefined) k2 = k;
26
- o[k2] = m[k];
27
- }));
28
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
29
- Object.defineProperty(o, "default", { enumerable: true, value: v });
30
- }) : function(o, v) {
31
- o["default"] = v;
32
- });
33
- var __importStar = (this && this.__importStar) || (function () {
34
- var ownKeys = function(o) {
35
- ownKeys = Object.getOwnPropertyNames || function (o) {
36
- var ar = [];
37
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
38
- return ar;
39
- };
40
- return ownKeys(o);
41
- };
42
- return function (mod) {
43
- if (mod && mod.__esModule) return mod;
44
- var result = {};
45
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
46
- __setModuleDefault(result, mod);
47
- return result;
48
- };
49
- })();
50
- var __importDefault = (this && this.__importDefault) || function (mod) {
51
- return (mod && mod.__esModule) ? mod : { "default": mod };
52
- };
53
- Object.defineProperty(exports, "__esModule", { value: true });
54
- exports.startHttpServer = startHttpServer;
55
- exports.httpAddressToString = httpAddressToString;
56
- exports.installHttpTransport = installHttpTransport;
57
- const assert_1 = __importDefault(require("assert"));
58
- const http_1 = __importDefault(require("http"));
59
- const crypto_1 = __importDefault(require("crypto"));
60
- const debug_1 = __importDefault(require("debug"));
61
- const mcpBundle = __importStar(require("./bundle"));
62
- const mcpServer = __importStar(require("./server"));
63
- const testDebug = (0, debug_1.default)('pw:mcp:test');
64
- async function startHttpServer(config, abortSignal) {
65
- const { host, port } = config;
66
- const httpServer = http_1.default.createServer();
67
- decorateServer(httpServer);
68
- await new Promise((resolve, reject) => {
69
- httpServer.on('error', reject);
70
- abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener('abort', () => {
71
- httpServer.close();
72
- reject(new Error('Aborted'));
73
- });
74
- httpServer.listen(port, host, () => {
75
- resolve();
76
- httpServer.removeListener('error', reject);
77
- });
78
- });
79
- return httpServer;
80
- }
81
- function httpAddressToString(address) {
82
- (0, assert_1.default)(address, 'Could not bind server socket');
83
- if (typeof address === 'string')
84
- return address;
85
- const resolvedPort = address.port;
86
- let resolvedHost = address.family === 'IPv4' ? address.address : `[${address.address}]`;
87
- if (resolvedHost === '0.0.0.0' || resolvedHost === '[::]')
88
- resolvedHost = 'localhost';
89
- return `http://${resolvedHost}:${resolvedPort}`;
90
- }
91
- async function installHttpTransport(httpServer, serverBackendFactory) {
92
- const sseSessions = new Map();
93
- const streamableSessions = new Map();
94
- httpServer.on('request', async (req, res) => {
95
- const url = new URL(`http://localhost${req.url}`);
96
- if (url.pathname.startsWith('/sse'))
97
- await handleSSE(serverBackendFactory, req, res, url, sseSessions);
98
- else
99
- await handleStreamable(serverBackendFactory, req, res, streamableSessions);
100
- });
101
- }
102
- async function handleSSE(serverBackendFactory, req, res, url, sessions) {
103
- if (req.method === 'POST') {
104
- const sessionId = url.searchParams.get('sessionId');
105
- if (!sessionId) {
106
- res.statusCode = 400;
107
- return res.end('Missing sessionId');
108
- }
109
- const transport = sessions.get(sessionId);
110
- if (!transport) {
111
- res.statusCode = 404;
112
- return res.end('Session not found');
113
- }
114
- return await transport.handlePostMessage(req, res);
115
- }
116
- else if (req.method === 'GET') {
117
- const transport = new mcpBundle.SSEServerTransport('/sse', res);
118
- sessions.set(transport.sessionId, transport);
119
- testDebug(`create SSE session: ${transport.sessionId}`);
120
- await mcpServer.connect(serverBackendFactory, transport, false);
121
- res.on('close', () => {
122
- testDebug(`delete SSE session: ${transport.sessionId}`);
123
- sessions.delete(transport.sessionId);
124
- });
125
- return;
126
- }
127
- res.statusCode = 405;
128
- res.end('Method not allowed');
129
- }
130
- async function handleStreamable(serverBackendFactory, req, res, sessions) {
131
- const sessionId = req.headers['mcp-session-id'];
132
- if (sessionId) {
133
- const transport = sessions.get(sessionId);
134
- if (!transport) {
135
- res.statusCode = 404;
136
- res.end('Session not found');
137
- return;
138
- }
139
- return await transport.handleRequest(req, res);
140
- }
141
- if (req.method === 'POST') {
142
- const transport = new mcpBundle.StreamableHTTPServerTransport({
143
- sessionIdGenerator: () => crypto_1.default.randomUUID(),
144
- onsessioninitialized: async (sessionId) => {
145
- testDebug(`create http session: ${transport.sessionId}`);
146
- await mcpServer.connect(serverBackendFactory, transport, true);
147
- sessions.set(sessionId, transport);
148
- }
149
- });
150
- transport.onclose = () => {
151
- if (!transport.sessionId)
152
- return;
153
- sessions.delete(transport.sessionId);
154
- testDebug(`delete http session: ${transport.sessionId}`);
155
- };
156
- await transport.handleRequest(req, res);
157
- return;
158
- }
159
- res.statusCode = 400;
160
- res.end('Invalid request');
161
- }
162
- function decorateServer(server) {
163
- const sockets = new Set();
164
- server.on('connection', socket => {
165
- sockets.add(socket);
166
- socket.once('close', () => sockets.delete(socket));
167
- });
168
- const close = server.close;
169
- server.close = (callback) => {
170
- for (const socket of sockets)
171
- socket.destroy();
172
- sockets.clear();
173
- return close.call(server, callback);
174
- };
175
- }
@@ -1,67 +0,0 @@
1
- "use strict";
2
- /**
3
- * Copyright (c) Microsoft Corporation.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.InProcessTransport = void 0;
19
- class InProcessTransport {
20
- constructor(server) {
21
- this._connected = false;
22
- this._server = server;
23
- this._serverTransport = new InProcessServerTransport(this);
24
- }
25
- async start() {
26
- if (this._connected)
27
- throw new Error('InprocessTransport already started!');
28
- await this._server.connect(this._serverTransport);
29
- this._connected = true;
30
- }
31
- async send(message, options) {
32
- if (!this._connected)
33
- throw new Error('Transport not connected');
34
- this._serverTransport._receiveFromClient(message);
35
- }
36
- async close() {
37
- var _a, _b, _c;
38
- if (this._connected) {
39
- this._connected = false;
40
- (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this);
41
- (_c = (_b = this._serverTransport).onclose) === null || _c === void 0 ? void 0 : _c.call(_b);
42
- }
43
- }
44
- _receiveFromServer(message, extra) {
45
- var _a;
46
- (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message, extra);
47
- }
48
- }
49
- exports.InProcessTransport = InProcessTransport;
50
- class InProcessServerTransport {
51
- constructor(clientTransport) {
52
- this._clientTransport = clientTransport;
53
- }
54
- async start() {
55
- }
56
- async send(message, options) {
57
- this._clientTransport._receiveFromServer(message);
58
- }
59
- async close() {
60
- var _a;
61
- (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this);
62
- }
63
- _receiveFromClient(message) {
64
- var _a;
65
- (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message);
66
- }
67
- }