@andrew-chen-wang/camoufox-mcp 0.0.1

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.
package/config.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ import type * as playwright from "playwright-core";
2
+ export type ToolCapability =
3
+ | "core"
4
+ | "tabs"
5
+ | "pdf"
6
+ | "history"
7
+ | "wait"
8
+ | "files"
9
+ | "install"
10
+ | "testing";
11
+
12
+ export type Config = {
13
+ browser?: {
14
+ browserAgent?: string;
15
+ browserName?: "chromium" | "firefox" | "webkit";
16
+ isolated?: boolean;
17
+ userDataDir?: string;
18
+ launchOptions?: playwright.LaunchOptions & Record<string, any>;
19
+ contextOptions?: playwright.BrowserContextOptions;
20
+ cdpEndpoint?: string;
21
+ remoteEndpoint?: string;
22
+ };
23
+ server?: {
24
+ port?: number;
25
+ host?: string;
26
+ };
27
+ capabilities?: ToolCapability[];
28
+ vision?: boolean;
29
+ saveTrace?: boolean;
30
+ saveVideo?: {
31
+ width: number;
32
+ height: number;
33
+ };
34
+ allowUnrestrictedFileAccess?: boolean;
35
+ outputDir?: string;
36
+ network?: {
37
+ allowedOrigins?: string[];
38
+ blockedOrigins?: string[];
39
+ };
40
+ imageResponses?: "allow" | "omit" | "auto";
41
+ };
package/index.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import type http from "node:http";
2
+
3
+ import type { BrowserContext } from "playwright-core";
4
+ import type { Config } from "./config.js";
5
+
6
+ export type CreateMCPHTTPServerOptions = {
7
+ config?: Config;
8
+ headless?: boolean;
9
+ host?: string;
10
+ port?: number;
11
+ };
12
+
13
+ export declare function createConnection(
14
+ config?: Config,
15
+ contextGetter?: () => Promise<BrowserContext>,
16
+ ): Promise<import("@modelcontextprotocol/sdk/server/index.js").Server>;
17
+
18
+ export declare function createMCPHTTPServer(
19
+ options?: CreateMCPHTTPServerOptions,
20
+ ): Promise<http.Server>;
21
+
22
+ export type { Config } from "./config.js";
package/index.js ADDED
@@ -0,0 +1 @@
1
+ export { createConnection, createMCPHTTPServer } from "./lib/index.js";
@@ -0,0 +1,178 @@
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
+ import fs from 'node:fs';
17
+ import os from 'node:os';
18
+ import path from 'node:path';
19
+ import debug from 'debug';
20
+ import { launchOptions as createCamoufoxLaunchOptions } from 'camoufox-js';
21
+ import { firefox } from 'playwright-core';
22
+ const testDebug = debug('camoufox:mcp:test');
23
+ export function contextFactory(browserConfig) {
24
+ if (browserConfig.remoteEndpoint)
25
+ return new RemoteContextFactory(browserConfig);
26
+ if (browserConfig.cdpEndpoint)
27
+ return new CdpContextFactory(browserConfig);
28
+ if (browserConfig.isolated)
29
+ return new IsolatedContextFactory(browserConfig);
30
+ return new PersistentContextFactory(browserConfig);
31
+ }
32
+ class BaseContextFactory {
33
+ browserConfig;
34
+ _browserPromise;
35
+ name;
36
+ constructor(name, browserConfig) {
37
+ this.name = name;
38
+ this.browserConfig = browserConfig;
39
+ }
40
+ async _obtainBrowser() {
41
+ if (this._browserPromise)
42
+ return this._browserPromise;
43
+ testDebug(`obtain browser (${this.name})`);
44
+ this._browserPromise = this._doObtainBrowser();
45
+ void this._browserPromise.then(browser => {
46
+ browser.on('disconnected', () => {
47
+ this._browserPromise = undefined;
48
+ });
49
+ }).catch(() => {
50
+ this._browserPromise = undefined;
51
+ });
52
+ return this._browserPromise;
53
+ }
54
+ async _doObtainBrowser() {
55
+ throw new Error('Not implemented');
56
+ }
57
+ async createContext() {
58
+ testDebug(`create browser context (${this.name})`);
59
+ const browser = await this._obtainBrowser();
60
+ const browserContext = await this._doCreateContext(browser);
61
+ return { browserContext, close: () => this._closeBrowserContext(browserContext, browser) };
62
+ }
63
+ async _doCreateContext(browser) {
64
+ throw new Error('Not implemented');
65
+ }
66
+ async _closeBrowserContext(browserContext, browser) {
67
+ testDebug(`close browser context (${this.name})`);
68
+ if (browser.contexts().length === 1)
69
+ this._browserPromise = undefined;
70
+ await browserContext.close().catch(() => { });
71
+ if (browser.contexts().length === 0) {
72
+ testDebug(`close browser (${this.name})`);
73
+ await browser.close().catch(() => { });
74
+ }
75
+ }
76
+ }
77
+ class IsolatedContextFactory extends BaseContextFactory {
78
+ constructor(browserConfig) {
79
+ super('isolated', browserConfig);
80
+ }
81
+ async _doObtainBrowser() {
82
+ return firefox.launch({
83
+ ...(await toCamoufoxLaunchOptions(this.browserConfig)),
84
+ handleSIGINT: false,
85
+ handleSIGTERM: false,
86
+ }).catch(error => {
87
+ if (String(error.message).includes('Executable doesn\'t exist'))
88
+ throw new Error('Camoufox is not installed. Run `npx camoufox-js fetch` and retry.');
89
+ throw error;
90
+ });
91
+ }
92
+ async _doCreateContext(browser) {
93
+ return browser.newContext(this.browserConfig.contextOptions);
94
+ }
95
+ }
96
+ class CdpContextFactory extends BaseContextFactory {
97
+ constructor(browserConfig) {
98
+ super('cdp', browserConfig);
99
+ }
100
+ async _doObtainBrowser() {
101
+ throw new Error('camoufox-mcp does not support cdpEndpoint because Camoufox is Firefox-based.');
102
+ }
103
+ async _doCreateContext() {
104
+ throw new Error('Not implemented');
105
+ }
106
+ }
107
+ class RemoteContextFactory extends BaseContextFactory {
108
+ constructor(browserConfig) {
109
+ super('remote', browserConfig);
110
+ }
111
+ async _doObtainBrowser() {
112
+ return firefox.connect(this.browserConfig.remoteEndpoint);
113
+ }
114
+ async _doCreateContext(browser) {
115
+ return browser.newContext(this.browserConfig.contextOptions);
116
+ }
117
+ }
118
+ class PersistentContextFactory {
119
+ browserConfig;
120
+ _userDataDirs = new Set();
121
+ constructor(browserConfig) {
122
+ this.browserConfig = browserConfig;
123
+ }
124
+ async createContext() {
125
+ testDebug('create browser context (persistent)');
126
+ const userDataDir = this.browserConfig.userDataDir ?? await this._createUserDataDir();
127
+ this._userDataDirs.add(userDataDir);
128
+ testDebug('lock user data dir', userDataDir);
129
+ for (let i = 0; i < 5; i++) {
130
+ try {
131
+ const browserContext = await firefox.launchPersistentContext(userDataDir, {
132
+ ...(await toCamoufoxLaunchOptions(this.browserConfig)),
133
+ ...this.browserConfig.contextOptions,
134
+ handleSIGINT: false,
135
+ handleSIGTERM: false,
136
+ });
137
+ const close = () => this._closeBrowserContext(browserContext, userDataDir);
138
+ return { browserContext, close };
139
+ }
140
+ catch (error) {
141
+ if (String(error.message).includes('Executable doesn\'t exist'))
142
+ throw new Error('Camoufox is not installed. Run `npx camoufox-js fetch` and retry.');
143
+ if (String(error.message).includes('ProcessSingleton') || String(error.message).includes('Invalid URL')) {
144
+ await new Promise(resolve => setTimeout(resolve, 1000));
145
+ continue;
146
+ }
147
+ throw error;
148
+ }
149
+ }
150
+ throw new Error(`Browser is already in use for ${userDataDir}, use --isolated to run multiple instances of the same browser`);
151
+ }
152
+ async _closeBrowserContext(browserContext, userDataDir) {
153
+ testDebug('close browser context (persistent)');
154
+ testDebug('release user data dir', userDataDir);
155
+ await browserContext.close().catch(() => { });
156
+ this._userDataDirs.delete(userDataDir);
157
+ testDebug('close browser context complete (persistent)');
158
+ }
159
+ async _createUserDataDir() {
160
+ let cacheDirectory;
161
+ if (process.platform === 'linux')
162
+ cacheDirectory = process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache');
163
+ else if (process.platform === 'darwin')
164
+ cacheDirectory = path.join(os.homedir(), 'Library', 'Caches');
165
+ else if (process.platform === 'win32')
166
+ cacheDirectory = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
167
+ else
168
+ throw new Error('Unsupported platform: ' + process.platform);
169
+ const result = path.join(cacheDirectory, 'camoufox-mcp', `mcp-${this.browserConfig.launchOptions?.channel ?? this.browserConfig?.browserName}-profile`);
170
+ await fs.promises.mkdir(result, { recursive: true });
171
+ return result;
172
+ }
173
+ }
174
+ async function toCamoufoxLaunchOptions(browserConfig) {
175
+ return createCamoufoxLaunchOptions({
176
+ ...browserConfig.launchOptions,
177
+ });
178
+ }
package/lib/config.js ADDED
@@ -0,0 +1,204 @@
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
+ import fs from 'fs';
17
+ import os from 'os';
18
+ import path from 'path';
19
+ import { devices } from 'playwright-core';
20
+ import { sanitizeForFilePath } from './tools/utils.js';
21
+ const defaultConfig = {
22
+ browser: {
23
+ browserName: 'firefox',
24
+ launchOptions: {
25
+ headless: os.platform() === 'linux' && !process.env.DISPLAY,
26
+ },
27
+ contextOptions: {
28
+ viewport: null,
29
+ },
30
+ },
31
+ network: {
32
+ allowedOrigins: undefined,
33
+ blockedOrigins: undefined,
34
+ },
35
+ server: {},
36
+ outputDir: path.join(os.tmpdir(), 'camoufox-mcp-output', sanitizeForFilePath(new Date().toISOString())),
37
+ };
38
+ export async function resolveConfig(config) {
39
+ return finalizeConfig(mergeConfig(defaultConfig, config));
40
+ }
41
+ export async function resolveCLIConfig(cliOptions) {
42
+ const configInFile = await loadConfig(cliOptions.config);
43
+ const cliOverrides = await configFromCLIOptions(cliOptions);
44
+ return finalizeConfig(mergeConfig(mergeConfig(defaultConfig, configInFile), cliOverrides));
45
+ }
46
+ export function validateConfig(config) {
47
+ if (config.browser?.browserName && config.browser.browserName !== 'firefox')
48
+ throw new Error(`camoufox-mcp only supports Firefox-compatible Camoufox browsers. Received "${config.browser.browserName}".`);
49
+ if (config.browser?.cdpEndpoint)
50
+ throw new Error('camoufox-mcp does not support cdpEndpoint because Camoufox is Firefox-based.');
51
+ if (config.browser?.browserAgent)
52
+ throw new Error('camoufox-mcp does not support browserAgent mode.');
53
+ if (config.extension)
54
+ throw new Error('camoufox-mcp does not support extension mode.');
55
+ }
56
+ export async function configFromCLIOptions(cliOptions) {
57
+ let browserName;
58
+ let channel;
59
+ switch (cliOptions.browser) {
60
+ case 'chrome':
61
+ case 'chrome-beta':
62
+ case 'chrome-canary':
63
+ case 'chrome-dev':
64
+ case 'chromium':
65
+ case 'msedge':
66
+ case 'msedge-beta':
67
+ case 'msedge-canary':
68
+ case 'msedge-dev':
69
+ browserName = 'chromium';
70
+ channel = cliOptions.browser;
71
+ break;
72
+ case 'firefox':
73
+ browserName = 'firefox';
74
+ break;
75
+ case 'webkit':
76
+ browserName = 'webkit';
77
+ break;
78
+ }
79
+ // Launch options
80
+ const launchOptions = {
81
+ channel,
82
+ executablePath: cliOptions.executablePath,
83
+ headless: cliOptions.headless,
84
+ };
85
+ if (cliOptions.proxyServer) {
86
+ launchOptions.proxy = {
87
+ server: cliOptions.proxyServer
88
+ };
89
+ if (cliOptions.proxyBypass)
90
+ launchOptions.proxy.bypass = cliOptions.proxyBypass;
91
+ }
92
+ if (cliOptions.device && cliOptions.cdpEndpoint)
93
+ throw new Error('Device emulation is not supported with cdpEndpoint.');
94
+ if (cliOptions.device && cliOptions.extension)
95
+ throw new Error('Device emulation is not supported with extension mode.');
96
+ // Context options
97
+ const contextOptions = cliOptions.device ? devices[cliOptions.device] : {};
98
+ if (cliOptions.storageState)
99
+ contextOptions.storageState = cliOptions.storageState;
100
+ if (cliOptions.userAgent)
101
+ contextOptions.userAgent = cliOptions.userAgent;
102
+ if (cliOptions.viewportSize) {
103
+ try {
104
+ const [width, height] = cliOptions.viewportSize.split(',').map(n => +n);
105
+ if (isNaN(width) || isNaN(height))
106
+ throw new Error('bad values');
107
+ contextOptions.viewport = { width, height };
108
+ }
109
+ catch (e) {
110
+ throw new Error('Invalid viewport size format: use "width,height", for example --viewport-size="800,600"');
111
+ }
112
+ }
113
+ if (cliOptions.ignoreHttpsErrors)
114
+ contextOptions.ignoreHTTPSErrors = true;
115
+ if (cliOptions.blockServiceWorkers)
116
+ contextOptions.serviceWorkers = 'block';
117
+ const result = {
118
+ browser: {
119
+ browserAgent: cliOptions.browserAgent ?? process.env.PW_BROWSER_AGENT,
120
+ browserName,
121
+ isolated: cliOptions.isolated,
122
+ userDataDir: cliOptions.userDataDir,
123
+ launchOptions,
124
+ contextOptions,
125
+ cdpEndpoint: cliOptions.cdpEndpoint,
126
+ },
127
+ server: {
128
+ port: cliOptions.port,
129
+ host: cliOptions.host,
130
+ },
131
+ capabilities: cliOptions.caps?.split(',').map((c) => c.trim()),
132
+ vision: !!cliOptions.vision,
133
+ extension: !!cliOptions.extension,
134
+ network: {
135
+ allowedOrigins: cliOptions.allowedOrigins,
136
+ blockedOrigins: cliOptions.blockedOrigins,
137
+ },
138
+ saveTrace: cliOptions.saveTrace,
139
+ outputDir: cliOptions.outputDir,
140
+ imageResponses: cliOptions.imageResponses,
141
+ saveVideo: undefined,
142
+ };
143
+ return result;
144
+ }
145
+ async function loadConfig(configFile) {
146
+ if (!configFile)
147
+ return {};
148
+ try {
149
+ return JSON.parse(await fs.promises.readFile(configFile, 'utf8'));
150
+ }
151
+ catch (error) {
152
+ throw new Error(`Failed to load config file: ${configFile}, ${error}`);
153
+ }
154
+ }
155
+ export async function outputFile(config, name) {
156
+ await fs.promises.mkdir(config.outputDir, { recursive: true });
157
+ const fileName = sanitizeForFilePath(name);
158
+ return path.join(config.outputDir, fileName);
159
+ }
160
+ function pickDefined(obj) {
161
+ return Object.fromEntries(Object.entries(obj ?? {}).filter(([_, v]) => v !== undefined));
162
+ }
163
+ function mergeConfig(base, overrides) {
164
+ const browser = {
165
+ ...pickDefined(base.browser),
166
+ ...pickDefined(overrides.browser),
167
+ browserName: overrides.browser?.browserName ?? base.browser?.browserName ?? 'firefox',
168
+ isolated: overrides.browser?.isolated ?? base.browser?.isolated ?? false,
169
+ launchOptions: {
170
+ ...pickDefined(base.browser?.launchOptions),
171
+ ...pickDefined(overrides.browser?.launchOptions),
172
+ },
173
+ contextOptions: {
174
+ ...pickDefined(base.browser?.contextOptions),
175
+ ...pickDefined(overrides.browser?.contextOptions),
176
+ },
177
+ };
178
+ if (browser.browserName !== 'chromium' && browser.launchOptions)
179
+ delete browser.launchOptions.channel;
180
+ return {
181
+ ...pickDefined(base),
182
+ ...pickDefined(overrides),
183
+ browser,
184
+ network: {
185
+ ...pickDefined(base.network),
186
+ ...pickDefined(overrides.network),
187
+ },
188
+ server: {
189
+ ...pickDefined(base.server),
190
+ ...pickDefined(overrides.server),
191
+ },
192
+ };
193
+ }
194
+ function finalizeConfig(config) {
195
+ if (config.saveTrace)
196
+ config.browser.launchOptions.tracesDir = path.join(config.outputDir, 'traces');
197
+ if (config.saveVideo) {
198
+ config.browser.contextOptions.recordVideo = {
199
+ dir: path.join(config.outputDir, 'videos'),
200
+ size: config.saveVideo,
201
+ };
202
+ }
203
+ return config;
204
+ }
@@ -0,0 +1,84 @@
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
+ import { Server as McpServer } from '@modelcontextprotocol/sdk/server/index.js';
17
+ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
18
+ import { zodToJsonSchema } from 'zod-to-json-schema';
19
+ import { Context } from './context.js';
20
+ import { snapshotTools, visionTools } from './tools.js';
21
+ import { packageJSON } from './package.js';
22
+ import { validateConfig } from './config.js';
23
+ export function createConnection(config, browserContextFactory) {
24
+ const allTools = config.vision ? visionTools : snapshotTools;
25
+ const tools = allTools.filter(tool => !config.capabilities || tool.capability === 'core' || config.capabilities.includes(tool.capability));
26
+ validateConfig(config);
27
+ const context = new Context(tools, config, browserContextFactory);
28
+ const server = new McpServer({ name: 'Camoufox', version: packageJSON.version }, {
29
+ capabilities: {
30
+ tools: {},
31
+ }
32
+ });
33
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
34
+ return {
35
+ tools: tools.map(tool => ({
36
+ name: tool.schema.name,
37
+ description: tool.schema.description,
38
+ inputSchema: zodToJsonSchema(tool.schema.inputSchema),
39
+ annotations: {
40
+ title: tool.schema.title,
41
+ readOnlyHint: tool.schema.type === 'readOnly',
42
+ destructiveHint: tool.schema.type === 'destructive',
43
+ openWorldHint: true,
44
+ },
45
+ })),
46
+ };
47
+ });
48
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
49
+ const errorResult = (...messages) => ({
50
+ content: [{ type: 'text', text: messages.join('\n') }],
51
+ isError: true,
52
+ });
53
+ const tool = tools.find(tool => tool.schema.name === request.params.name);
54
+ if (!tool)
55
+ return errorResult(`Tool "${request.params.name}" not found`);
56
+ const modalStates = context.modalStates().map(state => state.type);
57
+ if (tool.clearsModalState && !modalStates.includes(tool.clearsModalState))
58
+ return errorResult(`The tool "${request.params.name}" can only be used when there is related modal state present.`, ...context.modalStatesMarkdown());
59
+ if (!tool.clearsModalState && modalStates.length)
60
+ return errorResult(`Tool "${request.params.name}" does not handle the modal state.`, ...context.modalStatesMarkdown());
61
+ try {
62
+ return await context.run(tool, request.params.arguments);
63
+ }
64
+ catch (error) {
65
+ return errorResult(String(error));
66
+ }
67
+ });
68
+ return new Connection(server, context);
69
+ }
70
+ export class Connection {
71
+ server;
72
+ context;
73
+ constructor(server, context) {
74
+ this.server = server;
75
+ this.context = context;
76
+ this.server.oninitialized = () => {
77
+ this.context.clientVersion = this.server.getClientVersion();
78
+ };
79
+ }
80
+ async close() {
81
+ await this.server.close();
82
+ await this.context.close();
83
+ }
84
+ }