@treegress.com/treegress-browser-mcp 0.0.56-treegress.3

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 (67) hide show
  1. package/README.md +68 -0
  2. package/cli.js +25 -0
  3. package/config.d.ts +223 -0
  4. package/index.d.ts +23 -0
  5. package/index.js +19 -0
  6. package/mcp/browser/browserContextFactory.js +332 -0
  7. package/mcp/browser/browserServerBackend.js +105 -0
  8. package/mcp/browser/config.js +489 -0
  9. package/mcp/browser/configIni.js +194 -0
  10. package/mcp/browser/context.js +302 -0
  11. package/mcp/browser/domSnapshot.js +307 -0
  12. package/mcp/browser/logFile.js +96 -0
  13. package/mcp/browser/response.js +299 -0
  14. package/mcp/browser/sessionLog.js +75 -0
  15. package/mcp/browser/tab.js +1193 -0
  16. package/mcp/browser/tools/common.js +63 -0
  17. package/mcp/browser/tools/config.js +41 -0
  18. package/mcp/browser/tools/console.js +65 -0
  19. package/mcp/browser/tools/cookies.js +152 -0
  20. package/mcp/browser/tools/devtools.js +42 -0
  21. package/mcp/browser/tools/dialogs.js +59 -0
  22. package/mcp/browser/tools/evaluate.js +61 -0
  23. package/mcp/browser/tools/files.js +58 -0
  24. package/mcp/browser/tools/form.js +63 -0
  25. package/mcp/browser/tools/install.js +73 -0
  26. package/mcp/browser/tools/keyboard.js +151 -0
  27. package/mcp/browser/tools/mouse.js +159 -0
  28. package/mcp/browser/tools/navigate.js +105 -0
  29. package/mcp/browser/tools/network.js +92 -0
  30. package/mcp/browser/tools/pdf.js +48 -0
  31. package/mcp/browser/tools/route.js +140 -0
  32. package/mcp/browser/tools/runCode.js +76 -0
  33. package/mcp/browser/tools/screenshot.js +86 -0
  34. package/mcp/browser/tools/snapshot.js +207 -0
  35. package/mcp/browser/tools/storage.js +67 -0
  36. package/mcp/browser/tools/tabs.js +67 -0
  37. package/mcp/browser/tools/tool.js +47 -0
  38. package/mcp/browser/tools/tracing.js +75 -0
  39. package/mcp/browser/tools/utils.js +88 -0
  40. package/mcp/browser/tools/verify.js +143 -0
  41. package/mcp/browser/tools/video.js +89 -0
  42. package/mcp/browser/tools/wait.js +63 -0
  43. package/mcp/browser/tools/webstorage.js +223 -0
  44. package/mcp/browser/tools.js +96 -0
  45. package/mcp/browser/watchdog.js +44 -0
  46. package/mcp/config.d.js +16 -0
  47. package/mcp/extension/cdpRelay.js +354 -0
  48. package/mcp/extension/extensionContextFactory.js +77 -0
  49. package/mcp/extension/protocol.js +28 -0
  50. package/mcp/index.js +61 -0
  51. package/mcp/log.js +35 -0
  52. package/mcp/program.js +126 -0
  53. package/mcp/sdk/exports.js +28 -0
  54. package/mcp/sdk/http.js +172 -0
  55. package/mcp/sdk/inProcessTransport.js +71 -0
  56. package/mcp/sdk/server.js +223 -0
  57. package/mcp/sdk/tool.js +54 -0
  58. package/mcp/test/browserBackend.js +98 -0
  59. package/mcp/test/generatorTools.js +122 -0
  60. package/mcp/test/plannerTools.js +145 -0
  61. package/mcp/test/seed.js +82 -0
  62. package/mcp/test/streams.js +44 -0
  63. package/mcp/test/testBackend.js +99 -0
  64. package/mcp/test/testContext.js +285 -0
  65. package/mcp/test/testTool.js +30 -0
  66. package/mcp/test/testTools.js +108 -0
  67. package/package.json +46 -0
package/mcp/program.js ADDED
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var program_exports = {};
30
+ __export(program_exports, {
31
+ decorateMCPCommand: () => decorateMCPCommand
32
+ });
33
+ module.exports = __toCommonJS(program_exports);
34
+ var import_utilsBundle = require("playwright-core/lib/utilsBundle");
35
+ var mcpServer = __toESM(require("./sdk/server"));
36
+ var import_config = require("./browser/config");
37
+ var import_watchdog = require("./browser/watchdog");
38
+ var import_browserContextFactory = require("./browser/browserContextFactory");
39
+ var import_browserServerBackend = require("./browser/browserServerBackend");
40
+ var import_extensionContextFactory = require("./extension/extensionContextFactory");
41
+ function decorateMCPCommand(command, version) {
42
+ command
43
+ .option("--allowed-hosts <hosts...>", "comma-separated list of hosts this server is allowed to serve from. Defaults to the host the server is bound to. Pass '*' to disable the host check.", import_config.commaSeparatedList)
44
+ .option("--allowed-origins <origins>", "semicolon-separated list of TRUSTED origins to allow the browser to request. Default is to allow all.\nImportant: *does not* serve as a security boundary and *does not* affect redirects. ", import_config.semicolonSeparatedList)
45
+ .option("--allow-unrestricted-file-access", "allow access to files outside of the workspace roots. Also allows unrestricted access to file:// URLs. By default access to file system is restricted to workspace root directories (or cwd if no roots are configured) only, and navigation to file:// URLs is blocked.")
46
+ .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.\nImportant: *does not* serve as a security boundary and *does not* affect redirects.", import_config.semicolonSeparatedList)
47
+ .option("--block-service-workers", "block service workers")
48
+ .option("--browser <browser>", "browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.")
49
+ .option("--caps <caps>", "comma-separated list of additional capabilities to enable, possible values: vision, pdf, devtools.", import_config.commaSeparatedList)
50
+ .option("--cdp-endpoint <endpoint>", "CDP endpoint to connect to.")
51
+ .option("--cdp-header <headers...>", "CDP headers to send with the connect request, multiple can be specified.", import_config.headerParser)
52
+ .option("--cdp-timeout <timeout>", "timeout in milliseconds for connecting to CDP endpoint, defaults to 30000ms", import_config.numberParser)
53
+ .option("--codegen <lang>", 'specify the language to use for code generation, possible values: "typescript", "none". Default is "typescript".', import_config.enumParser.bind(null, "--codegen", ["none", "typescript"]))
54
+ .option("--config <path>", "path to the configuration file.")
55
+ .option("--console-level <level>", 'level of console messages to return: "error", "warning", "info", "debug". Each level includes the messages of more severe levels.', import_config.enumParser.bind(null, "--console-level", ["error", "warning", "info", "debug"]))
56
+ .option("--device <device>", 'device to emulate, for example: "iPhone 15"')
57
+ .option("--executable-path <path>", "path to the browser executable.")
58
+ .option("--extension", 'Connect to a running browser instance (Edge/Chrome only). Requires the "Playwright MCP Bridge" browser extension to be installed.')
59
+ .option("--grant-permissions <permissions...>", 'List of permissions to grant to the browser context, for example "geolocation", "clipboard-read", "clipboard-write".', import_config.commaSeparatedList)
60
+ .option("--headless", "run browser in headless mode, headed by default")
61
+ .option("--host <host>", "host to bind server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.")
62
+ .option("--ignore-https-errors", "ignore https errors")
63
+ .option("--init-page <path...>", "path to TypeScript file to evaluate on Playwright page object")
64
+ .option("--init-script <path...>", "path to JavaScript file to add as an initialization script. The script will be evaluated in every page before any of the page's scripts. Can be specified multiple times.")
65
+ .option("--isolated", "keep the browser profile in memory, do not save it to the disk.")
66
+ .option("--image-responses <mode>", 'whether to send image responses to the client. Can be "allow" or "omit", Defaults to "allow".', import_config.enumParser.bind(null, "--image-responses", ["allow", "omit"]))
67
+ .option("--no-sandbox", "disable the sandbox for all process types that are normally sandboxed.")
68
+ .option("--output-dir <path>", "path to the directory for output files.")
69
+ .option("--output-mode <mode>", 'whether to save snapshots, console messages, network logs to a file or to the standard output. Can be "file" or "stdout". Default is "stdout".', import_config.enumParser.bind(null, "--output-mode", ["file", "stdout"]))
70
+ .option("--port <port>", "port to listen on for SSE transport.")
71
+ .option("--proxy-bypass <bypass>", 'comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com"')
72
+ .option("--proxy-server <proxy>", 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"')
73
+ .option("--sandbox", "enable the sandbox for all process types that are normally not sandboxed.")
74
+ .option("--save-session", "Whether to save the Playwright MCP session into the output directory.")
75
+ .option("--save-trace", "Whether to save the Playwright Trace of the session into the output directory.")
76
+ .option("--save-video <size>", 'Whether to save the video of the session into the output directory. For example "--save-video=800x600"', import_config.resolutionParser.bind(null, "--save-video"))
77
+ .option("--secrets <path>", "path to a file containing secrets in the dotenv format", import_config.dotenvFileLoader)
78
+ .option("--shared-browser-context", "reuse the same browser context between all connected HTTP clients.")
79
+ .option("--snapshot-engine <engine>", 'snapshot engine for page snapshots. "dom" uses the playwright-core custom-dom backend, "aria" keeps the legacy accessibility fallback. Default is "dom".', import_config.enumParser.bind(null, "--snapshot-engine", ["aria", "dom"]))
80
+ .option("--dom-serializer <path>", "path to a domSerializer.js file for the historical/debug-only local DOM engine.")
81
+ .option("--snapshot-mode <mode>", 'when taking snapshots for responses, specifies the mode to use. Can be "incremental", "full", or "none". Default is incremental.', import_config.enumParser.bind(null, "--snapshot-mode", ["incremental", "full", "none"]))
82
+ .option("--dom-fallback-to-aria", "historical/debug-only local DOM engine: fallback to aria-ref resolving when local dom based resolution fails.")
83
+ .option("--dom-nonstrict", "historical/debug-only local DOM engine: disable strict locator enforcement.")
84
+ .option("--storage-state <path>", "path to the storage state file for isolated sessions.")
85
+ .option("--test-id-attribute <attribute>", 'specify the attribute to use for test ids, defaults to "data-testid"')
86
+ .option("--timeout-action <timeout>", "specify action timeout in milliseconds, defaults to 5000ms", import_config.numberParser)
87
+ .option("--timeout-navigation <timeout>", "specify navigation timeout in milliseconds, defaults to 60000ms", import_config.numberParser)
88
+ .option("--user-agent <ua string>", "specify user agent string")
89
+ .option("--user-data-dir <path>", "path to the user data directory. If not specified, a temporary directory will be created.")
90
+ .option("--viewport-size <size>", 'specify browser viewport size in pixels, for example "1280x720"', import_config.resolutionParser.bind(null, "--viewport-size"))
91
+ .addOption(new import_utilsBundle.ProgramOption("--vision", "Legacy option, use --caps=vision instead").hideHelp())
92
+ .action(async (options) => {
93
+ options.sandbox = options.sandbox === true ? void 0 : false;
94
+ (0, import_watchdog.setupExitWatchdog)();
95
+ if (options.vision) {
96
+ console.error("The --vision option is deprecated, use --caps=vision instead");
97
+ options.caps = "vision";
98
+ }
99
+ if (options.caps?.includes("tracing"))
100
+ options.caps.push("devtools");
101
+ const config = await (0, import_config.resolveCLIConfig)(options);
102
+ const browserContextFactory = (0, import_browserContextFactory.contextFactory)(config);
103
+ const extensionContextFactory = new import_extensionContextFactory.ExtensionContextFactory(config.browser.launchOptions.channel || "chrome", config.browser.userDataDir, config.browser.launchOptions.executablePath);
104
+ if (config.extension) {
105
+ const serverBackendFactory = {
106
+ name: "Playwright w/ extension",
107
+ nameInConfig: "playwright-extension",
108
+ version,
109
+ create: () => new import_browserServerBackend.BrowserServerBackend(config, extensionContextFactory)
110
+ };
111
+ await mcpServer.start(serverBackendFactory, config.server);
112
+ return;
113
+ }
114
+ const factory = {
115
+ name: "Playwright",
116
+ nameInConfig: "playwright",
117
+ version,
118
+ create: () => new import_browserServerBackend.BrowserServerBackend(config, browserContextFactory)
119
+ };
120
+ await mcpServer.start(factory, config.server);
121
+ });
122
+ }
123
+ // Annotate the CommonJS export names for ESM import in node:
124
+ 0 && (module.exports = {
125
+ decorateMCPCommand
126
+ });
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ }
12
+ return to;
13
+ };
14
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
15
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
16
+ var exports_exports = {};
17
+ module.exports = __toCommonJS(exports_exports);
18
+ __reExport(exports_exports, require("./inProcessTransport"), module.exports);
19
+ __reExport(exports_exports, require("./server"), module.exports);
20
+ __reExport(exports_exports, require("./tool"), module.exports);
21
+ __reExport(exports_exports, require("./http"), module.exports);
22
+ // Annotate the CommonJS export names for ESM import in node:
23
+ 0 && (module.exports = {
24
+ ...require("./inProcessTransport"),
25
+ ...require("./server"),
26
+ ...require("./tool"),
27
+ ...require("./http")
28
+ });
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var http_exports = {};
30
+ __export(http_exports, {
31
+ addressToString: () => addressToString,
32
+ startMcpHttpServer: () => startMcpHttpServer
33
+ });
34
+ module.exports = __toCommonJS(http_exports);
35
+ var import_assert = __toESM(require("assert"));
36
+ var import_crypto = __toESM(require("crypto"));
37
+ var import_utilsBundle = require("playwright-core/lib/utilsBundle");
38
+ var mcpBundle = __toESM(require("playwright-core/lib/mcpBundle"));
39
+ var import_utils = require("playwright-core/lib/utils");
40
+ var mcpServer = __toESM(require("./server"));
41
+ const testDebug = (0, import_utilsBundle.debug)("pw:mcp:test");
42
+ function setCorsHeaders(req, res) {
43
+ const origin = req.headers.origin;
44
+ res.setHeader("Access-Control-Allow-Origin", origin || "*");
45
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
46
+ res.setHeader(
47
+ "Access-Control-Allow-Headers",
48
+ req.headers["access-control-request-headers"] || "Content-Type, Accept, Mcp-Session-Id, Mcp-Protocol-Version"
49
+ );
50
+ res.setHeader("Access-Control-Allow-Credentials", "true");
51
+ }
52
+ async function startMcpHttpServer(config, serverBackendFactory, allowedHosts) {
53
+ const httpServer = (0, import_utils.createHttpServer)();
54
+ await (0, import_utils.startHttpServer)(httpServer, config);
55
+ return await installHttpTransport(httpServer, serverBackendFactory, allowedHosts);
56
+ }
57
+ function addressToString(address, options) {
58
+ (0, import_assert.default)(address, "Could not bind server socket");
59
+ if (typeof address === "string")
60
+ throw new Error("Unexpected address type: " + address);
61
+ let host = address.family === "IPv4" ? address.address : `[${address.address}]`;
62
+ if (options.normalizeLoopback && (host === "0.0.0.0" || host === "[::]" || host === "[::1]" || host === "127.0.0.1"))
63
+ host = "localhost";
64
+ return `${options.protocol}://${host}:${address.port}`;
65
+ }
66
+ async function installHttpTransport(httpServer, serverBackendFactory, allowedHosts) {
67
+ const url = addressToString(httpServer.address(), { protocol: "http", normalizeLoopback: true });
68
+ const host = new URL(url).host;
69
+ allowedHosts = (allowedHosts || [host]).map((h) => h.toLowerCase());
70
+ const allowAnyHost = allowedHosts.includes("*");
71
+ const sseSessions = /* @__PURE__ */ new Map();
72
+ const streamableSessions = /* @__PURE__ */ new Map();
73
+ httpServer.on("request", async (req, res) => {
74
+ setCorsHeaders(req, res);
75
+ if (req.method === "OPTIONS") {
76
+ res.statusCode = 204;
77
+ return res.end();
78
+ }
79
+ if (!allowAnyHost) {
80
+ const host2 = req.headers.host?.toLowerCase();
81
+ if (!host2) {
82
+ res.statusCode = 400;
83
+ return res.end("Missing host");
84
+ }
85
+ if (!allowedHosts.includes(host2)) {
86
+ res.statusCode = 403;
87
+ return res.end("Access is only allowed at " + allowedHosts.join(", "));
88
+ }
89
+ }
90
+ const url2 = new URL(`http://localhost${req.url}`);
91
+ if (url2.pathname === "/killkillkill" && req.method === "GET") {
92
+ res.statusCode = 200;
93
+ res.end("Killing process");
94
+ process.emit("SIGINT");
95
+ return;
96
+ }
97
+ if (url2.pathname === "/") {
98
+ res.setHeader("content-type", "text/plain; charset=utf-8");
99
+ res.end("Playwright MCP HTTP transport is available at /mcp (Streamable HTTP) or /sse (legacy SSE).");
100
+ return;
101
+ }
102
+ if (url2.pathname.startsWith("/sse"))
103
+ await handleSSE(serverBackendFactory, req, res, url2, sseSessions);
104
+ else
105
+ await handleStreamable(serverBackendFactory, req, res, streamableSessions);
106
+ });
107
+ return url;
108
+ }
109
+ async function handleSSE(serverBackendFactory, req, res, url, sessions) {
110
+ if (req.method === "POST") {
111
+ const sessionId = url.searchParams.get("sessionId");
112
+ if (!sessionId) {
113
+ res.statusCode = 400;
114
+ return res.end("Missing sessionId");
115
+ }
116
+ const transport = sessions.get(sessionId);
117
+ if (!transport) {
118
+ res.statusCode = 404;
119
+ return res.end("Session not found");
120
+ }
121
+ return await transport.handlePostMessage(req, res);
122
+ } else if (req.method === "GET") {
123
+ const transport = new mcpBundle.SSEServerTransport("/sse", res);
124
+ sessions.set(transport.sessionId, transport);
125
+ testDebug(`create SSE session: ${transport.sessionId}`);
126
+ await mcpServer.connect(serverBackendFactory, transport, false);
127
+ res.on("close", () => {
128
+ testDebug(`delete SSE session: ${transport.sessionId}`);
129
+ sessions.delete(transport.sessionId);
130
+ });
131
+ return;
132
+ }
133
+ res.statusCode = 405;
134
+ res.end("Method not allowed");
135
+ }
136
+ async function handleStreamable(serverBackendFactory, req, res, sessions) {
137
+ const sessionId = req.headers["mcp-session-id"];
138
+ if (sessionId) {
139
+ const transport = sessions.get(sessionId);
140
+ if (!transport) {
141
+ res.statusCode = 404;
142
+ res.end("Session not found");
143
+ return;
144
+ }
145
+ return await transport.handleRequest(req, res);
146
+ }
147
+ if (req.method === "POST") {
148
+ const transport = new mcpBundle.StreamableHTTPServerTransport({
149
+ sessionIdGenerator: () => import_crypto.default.randomUUID(),
150
+ onsessioninitialized: async (sessionId2) => {
151
+ testDebug(`create http session: ${transport.sessionId}`);
152
+ await mcpServer.connect(serverBackendFactory, transport, false);
153
+ sessions.set(sessionId2, transport);
154
+ }
155
+ });
156
+ transport.onclose = () => {
157
+ if (!transport.sessionId)
158
+ return;
159
+ sessions.delete(transport.sessionId);
160
+ testDebug(`delete http session: ${transport.sessionId}`);
161
+ };
162
+ await transport.handleRequest(req, res);
163
+ return;
164
+ }
165
+ res.statusCode = 400;
166
+ res.end("Invalid request");
167
+ }
168
+ // Annotate the CommonJS export names for ESM import in node:
169
+ 0 && (module.exports = {
170
+ addressToString,
171
+ startMcpHttpServer
172
+ });
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var inProcessTransport_exports = {};
20
+ __export(inProcessTransport_exports, {
21
+ InProcessTransport: () => InProcessTransport
22
+ });
23
+ module.exports = __toCommonJS(inProcessTransport_exports);
24
+ class InProcessTransport {
25
+ constructor(server) {
26
+ this._connected = false;
27
+ this._server = server;
28
+ this._serverTransport = new InProcessServerTransport(this);
29
+ }
30
+ async start() {
31
+ if (this._connected)
32
+ throw new Error("InprocessTransport already started!");
33
+ await this._server.connect(this._serverTransport);
34
+ this._connected = true;
35
+ }
36
+ async send(message, options) {
37
+ if (!this._connected)
38
+ throw new Error("Transport not connected");
39
+ this._serverTransport._receiveFromClient(message);
40
+ }
41
+ async close() {
42
+ if (this._connected) {
43
+ this._connected = false;
44
+ this.onclose?.();
45
+ this._serverTransport.onclose?.();
46
+ }
47
+ }
48
+ _receiveFromServer(message, extra) {
49
+ this.onmessage?.(message, extra);
50
+ }
51
+ }
52
+ class InProcessServerTransport {
53
+ constructor(clientTransport) {
54
+ this._clientTransport = clientTransport;
55
+ }
56
+ async start() {
57
+ }
58
+ async send(message, options) {
59
+ this._clientTransport._receiveFromServer(message);
60
+ }
61
+ async close() {
62
+ this.onclose?.();
63
+ }
64
+ _receiveFromClient(message) {
65
+ this.onmessage?.(message);
66
+ }
67
+ }
68
+ // Annotate the CommonJS export names for ESM import in node:
69
+ 0 && (module.exports = {
70
+ InProcessTransport
71
+ });
@@ -0,0 +1,223 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var server_exports = {};
30
+ __export(server_exports, {
31
+ allRootPaths: () => allRootPaths,
32
+ connect: () => connect,
33
+ createServer: () => createServer,
34
+ firstRootPath: () => firstRootPath,
35
+ start: () => start,
36
+ wrapInClient: () => wrapInClient,
37
+ wrapInProcess: () => wrapInProcess
38
+ });
39
+ module.exports = __toCommonJS(server_exports);
40
+ var import_url = require("url");
41
+ var import_utilsBundle = require("playwright-core/lib/utilsBundle");
42
+ var mcpBundle = __toESM(require("playwright-core/lib/mcpBundle"));
43
+ var import_http = require("./http");
44
+ var import_inProcessTransport = require("./inProcessTransport");
45
+ const serverDebug = (0, import_utilsBundle.debug)("pw:mcp:server");
46
+ const serverDebugResponse = (0, import_utilsBundle.debug)("pw:mcp:server:response");
47
+ async function connect(factory, transport, runHeartbeat) {
48
+ const server = createServer(factory.name, factory.version, factory.create(), runHeartbeat);
49
+ await server.connect(transport);
50
+ }
51
+ function wrapInProcess(backend) {
52
+ const server = createServer("Internal", "0.0.0", backend, false);
53
+ return new import_inProcessTransport.InProcessTransport(server);
54
+ }
55
+ async function wrapInClient(backend, options) {
56
+ const server = createServer("Internal", "0.0.0", backend, false);
57
+ const transport = new import_inProcessTransport.InProcessTransport(server);
58
+ const client = new mcpBundle.Client({ name: options.name, version: options.version });
59
+ await client.connect(transport);
60
+ await client.ping();
61
+ return client;
62
+ }
63
+ function createServer(name, version, backend, runHeartbeat) {
64
+ const server = new mcpBundle.Server({ name, version }, {
65
+ capabilities: {
66
+ tools: {}
67
+ }
68
+ });
69
+ server.setRequestHandler(mcpBundle.ListToolsRequestSchema, async () => {
70
+ serverDebug("listTools");
71
+ const tools = await backend.listTools();
72
+ return { tools };
73
+ });
74
+ let initializePromise;
75
+ server.setRequestHandler(mcpBundle.CallToolRequestSchema, async (request, extra) => {
76
+ serverDebug("callTool", request);
77
+ const progressToken = request.params._meta?.progressToken;
78
+ let progressCounter = 0;
79
+ const progress = progressToken ? (params) => {
80
+ extra.sendNotification({
81
+ method: "notifications/progress",
82
+ params: {
83
+ progressToken,
84
+ progress: params.progress ?? ++progressCounter,
85
+ total: params.total,
86
+ message: params.message
87
+ }
88
+ }).catch((e) => serverDebug("notification", e));
89
+ } : () => {
90
+ };
91
+ try {
92
+ if (!initializePromise)
93
+ initializePromise = initializeServer(server, backend, runHeartbeat);
94
+ await initializePromise;
95
+ const toolResult = await backend.callTool(request.params.name, request.params.arguments || {}, progress);
96
+ const mergedResult = mergeTextParts(toolResult);
97
+ serverDebugResponse("callResult", mergedResult);
98
+ return mergedResult;
99
+ } catch (error) {
100
+ return {
101
+ content: [{ type: "text", text: "### Result\n" + String(error) }],
102
+ isError: true
103
+ };
104
+ }
105
+ });
106
+ addServerListener(server, "close", () => backend.serverClosed?.(server));
107
+ return server;
108
+ }
109
+ const initializeServer = async (server, backend, runHeartbeat) => {
110
+ const capabilities = server.getClientCapabilities();
111
+ let clientRoots = [];
112
+ if (capabilities?.roots) {
113
+ const { roots } = await server.listRoots().catch((e) => {
114
+ serverDebug(e);
115
+ return { roots: [] };
116
+ });
117
+ clientRoots = roots;
118
+ }
119
+ const clientInfo = {
120
+ name: server.getClientVersion()?.name ?? "unknown",
121
+ version: server.getClientVersion()?.version ?? "unknown",
122
+ roots: clientRoots,
123
+ timestamp: Date.now()
124
+ };
125
+ await backend.initialize?.(clientInfo);
126
+ if (runHeartbeat)
127
+ startHeartbeat(server);
128
+ };
129
+ const startHeartbeat = (server) => {
130
+ const beat = () => {
131
+ Promise.race([
132
+ server.ping(),
133
+ new Promise((_, reject) => setTimeout(() => reject(new Error("ping timeout")), 5e3))
134
+ ]).then(() => {
135
+ setTimeout(beat, 3e3);
136
+ }).catch(() => {
137
+ void server.close();
138
+ });
139
+ };
140
+ beat();
141
+ };
142
+ function addServerListener(server, event, listener) {
143
+ const oldListener = server[`on${event}`];
144
+ server[`on${event}`] = () => {
145
+ oldListener?.();
146
+ listener();
147
+ };
148
+ }
149
+ async function start(serverBackendFactory, options) {
150
+ if (options.port === void 0) {
151
+ await connect(serverBackendFactory, new mcpBundle.StdioServerTransport(), false);
152
+ return;
153
+ }
154
+ const url = await (0, import_http.startMcpHttpServer)(options, serverBackendFactory, options.allowedHosts);
155
+ const mcpConfig = { mcpServers: {} };
156
+ mcpConfig.mcpServers[serverBackendFactory.nameInConfig] = {
157
+ url: `${url}/mcp`
158
+ };
159
+ const message = [
160
+ `Listening on ${url}`,
161
+ "Put this in your client config:",
162
+ JSON.stringify(mcpConfig, void 0, 2),
163
+ "For legacy SSE transport support, you can use the /sse endpoint instead."
164
+ ].join("\n");
165
+ console.error(message);
166
+ }
167
+ function firstRootPath(clientInfo) {
168
+ if (clientInfo.roots.length === 0)
169
+ return void 0;
170
+ const firstRootUri = clientInfo.roots[0]?.uri;
171
+ const url = firstRootUri ? new URL(firstRootUri) : void 0;
172
+ try {
173
+ return url ? (0, import_url.fileURLToPath)(url) : void 0;
174
+ } catch (error) {
175
+ serverDebug(error);
176
+ return void 0;
177
+ }
178
+ }
179
+ function allRootPaths(clientInfo) {
180
+ const paths = [];
181
+ for (const root of clientInfo.roots) {
182
+ try {
183
+ const url = new URL(root.uri);
184
+ const path = (0, import_url.fileURLToPath)(url);
185
+ if (path)
186
+ paths.push(path);
187
+ } catch (error) {
188
+ serverDebug(error);
189
+ }
190
+ }
191
+ return paths;
192
+ }
193
+ function mergeTextParts(result) {
194
+ const content = [];
195
+ const testParts = [];
196
+ for (const part of result.content) {
197
+ if (part.type === "text") {
198
+ testParts.push(part.text);
199
+ continue;
200
+ }
201
+ if (testParts.length > 0) {
202
+ content.push({ type: "text", text: testParts.join("\n") });
203
+ testParts.length = 0;
204
+ }
205
+ content.push(part);
206
+ }
207
+ if (testParts.length > 0)
208
+ content.push({ type: "text", text: testParts.join("\n") });
209
+ return {
210
+ ...result,
211
+ content
212
+ };
213
+ }
214
+ // Annotate the CommonJS export names for ESM import in node:
215
+ 0 && (module.exports = {
216
+ allRootPaths,
217
+ connect,
218
+ createServer,
219
+ firstRootPath,
220
+ start,
221
+ wrapInClient,
222
+ wrapInProcess
223
+ });
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var tool_exports = {};
20
+ __export(tool_exports, {
21
+ defineToolSchema: () => defineToolSchema,
22
+ toMcpTool: () => toMcpTool
23
+ });
24
+ module.exports = __toCommonJS(tool_exports);
25
+ var import_mcpBundle = require("playwright-core/lib/mcpBundle");
26
+ function toJSONSchema(schema) {
27
+ if (typeof import_mcpBundle.z.toJSONSchema === "function")
28
+ return import_mcpBundle.z.toJSONSchema(schema);
29
+ if (typeof import_mcpBundle.zodToJsonSchema === "function")
30
+ return import_mcpBundle.zodToJsonSchema(schema);
31
+ throw new Error("Unable to convert Zod schema to JSON Schema: no supported conversion helper found in playwright-core/lib/mcpBundle");
32
+ }
33
+ function toMcpTool(tool) {
34
+ const readOnly = tool.type === "readOnly" || tool.type === "assertion";
35
+ return {
36
+ name: tool.name,
37
+ description: tool.description,
38
+ inputSchema: toJSONSchema(tool.inputSchema),
39
+ annotations: {
40
+ title: tool.title,
41
+ readOnlyHint: readOnly,
42
+ destructiveHint: !readOnly,
43
+ openWorldHint: true
44
+ }
45
+ };
46
+ }
47
+ function defineToolSchema(tool) {
48
+ return tool;
49
+ }
50
+ // Annotate the CommonJS export names for ESM import in node:
51
+ 0 && (module.exports = {
52
+ defineToolSchema,
53
+ toMcpTool
54
+ });