@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 +41 -0
- package/index.d.ts +22 -0
- package/index.js +1 -0
- package/lib/browserContextFactory.js +178 -0
- package/lib/config.js +204 -0
- package/lib/connection.js +84 -0
- package/lib/context.js +361 -0
- package/lib/fileUtils.js +32 -0
- package/lib/index.js +66 -0
- package/lib/javascript.js +49 -0
- package/lib/manualPromise.js +111 -0
- package/lib/mcpHttpServer.js +90 -0
- package/lib/package.js +20 -0
- package/lib/pageSnapshot.js +44 -0
- package/lib/resources/resource.js +16 -0
- package/lib/server.js +48 -0
- package/lib/tab.js +107 -0
- package/lib/tools/common.js +68 -0
- package/lib/tools/console.js +77 -0
- package/lib/tools/devtools.js +189 -0
- package/lib/tools/dialogs.js +52 -0
- package/lib/tools/files.js +51 -0
- package/lib/tools/forms.js +67 -0
- package/lib/tools/install.js +57 -0
- package/lib/tools/keyboard.js +158 -0
- package/lib/tools/mouse.js +119 -0
- package/lib/tools/navigate.js +117 -0
- package/lib/tools/network.js +197 -0
- package/lib/tools/pdf.js +49 -0
- package/lib/tools/screenshot.js +80 -0
- package/lib/tools/snapshot.js +307 -0
- package/lib/tools/storage.js +344 -0
- package/lib/tools/tabs.js +172 -0
- package/lib/tools/testing.js +60 -0
- package/lib/tools/tool.js +18 -0
- package/lib/tools/utils.js +87 -0
- package/lib/tools/vision.js +189 -0
- package/lib/tools/wait.js +59 -0
- package/lib/tools.js +73 -0
- package/package.json +48 -0
package/lib/context.js
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
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 debug from 'debug';
|
|
17
|
+
import { callOnPageNoTrace, waitForCompletion } from './tools/utils.js';
|
|
18
|
+
import { ManualPromise } from './manualPromise.js';
|
|
19
|
+
import { Tab } from './tab.js';
|
|
20
|
+
import { outputFile } from './config.js';
|
|
21
|
+
const testDebug = debug('pw:mcp:test');
|
|
22
|
+
export class Context {
|
|
23
|
+
tools;
|
|
24
|
+
config;
|
|
25
|
+
_browserContextPromise;
|
|
26
|
+
_browserContextFactory;
|
|
27
|
+
_tabs = [];
|
|
28
|
+
_currentTab;
|
|
29
|
+
_modalStates = [];
|
|
30
|
+
_pendingAction;
|
|
31
|
+
_downloads = [];
|
|
32
|
+
_routeRules = [];
|
|
33
|
+
_networkOffline = false;
|
|
34
|
+
_tracingActive = false;
|
|
35
|
+
clientVersion;
|
|
36
|
+
constructor(tools, config, browserContextFactory) {
|
|
37
|
+
this.tools = tools;
|
|
38
|
+
this.config = config;
|
|
39
|
+
this._browserContextFactory = browserContextFactory;
|
|
40
|
+
testDebug('create context');
|
|
41
|
+
}
|
|
42
|
+
clientSupportsImages() {
|
|
43
|
+
if (this.config.imageResponses === 'allow')
|
|
44
|
+
return true;
|
|
45
|
+
if (this.config.imageResponses === 'omit')
|
|
46
|
+
return false;
|
|
47
|
+
return !this.clientVersion?.name.includes('cursor');
|
|
48
|
+
}
|
|
49
|
+
modalStates() {
|
|
50
|
+
return this._modalStates;
|
|
51
|
+
}
|
|
52
|
+
setModalState(modalState, inTab) {
|
|
53
|
+
this._modalStates.push({ ...modalState, tab: inTab });
|
|
54
|
+
}
|
|
55
|
+
clearModalState(modalState) {
|
|
56
|
+
this._modalStates = this._modalStates.filter(state => state !== modalState);
|
|
57
|
+
}
|
|
58
|
+
modalStatesMarkdown() {
|
|
59
|
+
const result = ['### Modal state'];
|
|
60
|
+
if (this._modalStates.length === 0)
|
|
61
|
+
result.push('- There is no modal state present');
|
|
62
|
+
for (const state of this._modalStates) {
|
|
63
|
+
const tool = this.tools.find(tool => tool.clearsModalState === state.type);
|
|
64
|
+
result.push(`- [${state.description}]: can be handled by the "${tool?.schema.name}" tool`);
|
|
65
|
+
}
|
|
66
|
+
return result;
|
|
67
|
+
}
|
|
68
|
+
tabs() {
|
|
69
|
+
return this._tabs;
|
|
70
|
+
}
|
|
71
|
+
currentTabOrDie() {
|
|
72
|
+
if (!this._currentTab)
|
|
73
|
+
throw new Error('No current snapshot available. Capture a snapshot or navigate to a new location first.');
|
|
74
|
+
return this._currentTab;
|
|
75
|
+
}
|
|
76
|
+
async newTab() {
|
|
77
|
+
const { browserContext } = await this._ensureBrowserContext();
|
|
78
|
+
const page = await browserContext.newPage();
|
|
79
|
+
this._currentTab = this._tabs.find(t => t.page === page);
|
|
80
|
+
return this._currentTab;
|
|
81
|
+
}
|
|
82
|
+
async selectTab(index) {
|
|
83
|
+
this._currentTab = this._tabs[index - 1];
|
|
84
|
+
await this._currentTab.page.bringToFront();
|
|
85
|
+
}
|
|
86
|
+
async ensureTab() {
|
|
87
|
+
const { browserContext } = await this._ensureBrowserContext();
|
|
88
|
+
if (!this._currentTab)
|
|
89
|
+
await browserContext.newPage();
|
|
90
|
+
return this._currentTab;
|
|
91
|
+
}
|
|
92
|
+
async listTabsMarkdown() {
|
|
93
|
+
if (!this._tabs.length)
|
|
94
|
+
return '### No tabs open';
|
|
95
|
+
const lines = ['### Open tabs'];
|
|
96
|
+
for (let i = 0; i < this._tabs.length; i++) {
|
|
97
|
+
const tab = this._tabs[i];
|
|
98
|
+
const title = await tab.title();
|
|
99
|
+
const url = tab.page.url();
|
|
100
|
+
const current = tab === this._currentTab ? ' (current)' : '';
|
|
101
|
+
lines.push(`- ${i + 1}:${current} [${title}] (${url})`);
|
|
102
|
+
}
|
|
103
|
+
return lines.join('\n');
|
|
104
|
+
}
|
|
105
|
+
async closeTab(index) {
|
|
106
|
+
const tab = index === undefined ? this._currentTab : this._tabs[index - 1];
|
|
107
|
+
await tab?.page.close();
|
|
108
|
+
return await this.listTabsMarkdown();
|
|
109
|
+
}
|
|
110
|
+
async run(tool, params) {
|
|
111
|
+
// Tab management is done outside of the action() call.
|
|
112
|
+
const toolResult = await tool.handle(this, tool.schema.inputSchema.parse(params || {}));
|
|
113
|
+
const { code, action, waitForNetwork, captureSnapshot, resultOverride } = toolResult;
|
|
114
|
+
const racingAction = action ? () => this._raceAgainstModalDialogs(action) : undefined;
|
|
115
|
+
if (resultOverride)
|
|
116
|
+
return resultOverride;
|
|
117
|
+
if (!this._currentTab) {
|
|
118
|
+
return {
|
|
119
|
+
content: [{
|
|
120
|
+
type: 'text',
|
|
121
|
+
text: 'No open pages available. Use the "browser_navigate" tool to navigate to a page first.',
|
|
122
|
+
}],
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
const tab = this.currentTabOrDie();
|
|
126
|
+
// TODO: race against modal dialogs to resolve clicks.
|
|
127
|
+
let actionResult;
|
|
128
|
+
try {
|
|
129
|
+
if (waitForNetwork)
|
|
130
|
+
actionResult = await waitForCompletion(this, tab, async () => racingAction?.()) ?? undefined;
|
|
131
|
+
else
|
|
132
|
+
actionResult = await racingAction?.() ?? undefined;
|
|
133
|
+
}
|
|
134
|
+
finally {
|
|
135
|
+
if (captureSnapshot && !this._javaScriptBlocked())
|
|
136
|
+
await tab.captureSnapshot();
|
|
137
|
+
}
|
|
138
|
+
const result = [];
|
|
139
|
+
result.push(`- Ran Playwright code:
|
|
140
|
+
\`\`\`js
|
|
141
|
+
${code.join('\n')}
|
|
142
|
+
\`\`\`
|
|
143
|
+
`);
|
|
144
|
+
if (this.modalStates().length) {
|
|
145
|
+
result.push(...this.modalStatesMarkdown());
|
|
146
|
+
return {
|
|
147
|
+
content: [{
|
|
148
|
+
type: 'text',
|
|
149
|
+
text: result.join('\n'),
|
|
150
|
+
}],
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
if (this._downloads.length) {
|
|
154
|
+
result.push('', '### Downloads');
|
|
155
|
+
for (const entry of this._downloads) {
|
|
156
|
+
if (entry.finished)
|
|
157
|
+
result.push(`- Downloaded file ${entry.download.suggestedFilename()} to ${entry.outputFile}`);
|
|
158
|
+
else
|
|
159
|
+
result.push(`- Downloading file ${entry.download.suggestedFilename()} ...`);
|
|
160
|
+
}
|
|
161
|
+
result.push('');
|
|
162
|
+
}
|
|
163
|
+
if (this.tabs().length > 1)
|
|
164
|
+
result.push(await this.listTabsMarkdown(), '');
|
|
165
|
+
if (this.tabs().length > 1)
|
|
166
|
+
result.push('### Current tab');
|
|
167
|
+
result.push(`- Page URL: ${tab.page.url()}`, `- Page Title: ${await tab.title()}`);
|
|
168
|
+
if (captureSnapshot && tab.hasSnapshot())
|
|
169
|
+
result.push(tab.snapshotOrDie().text());
|
|
170
|
+
const content = actionResult?.content ?? [];
|
|
171
|
+
return {
|
|
172
|
+
content: [
|
|
173
|
+
...content,
|
|
174
|
+
{
|
|
175
|
+
type: 'text',
|
|
176
|
+
text: result.join('\n'),
|
|
177
|
+
}
|
|
178
|
+
],
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
async waitForTimeout(time) {
|
|
182
|
+
if (!this._currentTab || this._javaScriptBlocked()) {
|
|
183
|
+
await new Promise(f => setTimeout(f, time));
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
await callOnPageNoTrace(this._currentTab.page, page => {
|
|
187
|
+
return page.evaluate(() => new Promise(f => setTimeout(f, 1000)));
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
async _raceAgainstModalDialogs(action) {
|
|
191
|
+
this._pendingAction = {
|
|
192
|
+
dialogShown: new ManualPromise(),
|
|
193
|
+
};
|
|
194
|
+
let result;
|
|
195
|
+
try {
|
|
196
|
+
await Promise.race([
|
|
197
|
+
action().then(r => result = r),
|
|
198
|
+
this._pendingAction.dialogShown,
|
|
199
|
+
]);
|
|
200
|
+
}
|
|
201
|
+
finally {
|
|
202
|
+
this._pendingAction = undefined;
|
|
203
|
+
}
|
|
204
|
+
return result;
|
|
205
|
+
}
|
|
206
|
+
_javaScriptBlocked() {
|
|
207
|
+
return this._modalStates.some(state => state.type === 'dialog');
|
|
208
|
+
}
|
|
209
|
+
dialogShown(tab, dialog) {
|
|
210
|
+
this.setModalState({
|
|
211
|
+
type: 'dialog',
|
|
212
|
+
description: `"${dialog.type()}" dialog with message "${dialog.message()}"`,
|
|
213
|
+
dialog,
|
|
214
|
+
}, tab);
|
|
215
|
+
this._pendingAction?.dialogShown.resolve();
|
|
216
|
+
}
|
|
217
|
+
async downloadStarted(tab, download) {
|
|
218
|
+
const entry = {
|
|
219
|
+
download,
|
|
220
|
+
finished: false,
|
|
221
|
+
outputFile: await outputFile(this.config, download.suggestedFilename())
|
|
222
|
+
};
|
|
223
|
+
this._downloads.push(entry);
|
|
224
|
+
await download.saveAs(entry.outputFile);
|
|
225
|
+
entry.finished = true;
|
|
226
|
+
}
|
|
227
|
+
_onPageCreated(page) {
|
|
228
|
+
const tab = new Tab(this, page, tab => this._onPageClosed(tab));
|
|
229
|
+
this._tabs.push(tab);
|
|
230
|
+
if (!this._currentTab)
|
|
231
|
+
this._currentTab = tab;
|
|
232
|
+
}
|
|
233
|
+
_onPageClosed(tab) {
|
|
234
|
+
this._modalStates = this._modalStates.filter(state => state.tab !== tab);
|
|
235
|
+
const index = this._tabs.indexOf(tab);
|
|
236
|
+
if (index === -1)
|
|
237
|
+
return;
|
|
238
|
+
this._tabs.splice(index, 1);
|
|
239
|
+
if (this._currentTab === tab)
|
|
240
|
+
this._currentTab = this._tabs[Math.min(index, this._tabs.length - 1)];
|
|
241
|
+
if (!this._tabs.length)
|
|
242
|
+
void this.close();
|
|
243
|
+
}
|
|
244
|
+
async close() {
|
|
245
|
+
if (!this._browserContextPromise)
|
|
246
|
+
return;
|
|
247
|
+
testDebug('close context');
|
|
248
|
+
const promise = this._browserContextPromise;
|
|
249
|
+
this._browserContextPromise = undefined;
|
|
250
|
+
await promise.then(async ({ browserContext, close }) => {
|
|
251
|
+
if (this._tracingActive)
|
|
252
|
+
await browserContext.tracing.stop();
|
|
253
|
+
this._tracingActive = false;
|
|
254
|
+
await close();
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
async _setupRequestInterception(context) {
|
|
258
|
+
await context.setOffline(this._networkOffline);
|
|
259
|
+
if (this.config.network?.allowedOrigins?.length) {
|
|
260
|
+
await context.route('**', route => route.abort('blockedbyclient'));
|
|
261
|
+
for (const origin of this.config.network.allowedOrigins)
|
|
262
|
+
await context.route(`*://${origin}/**`, route => route.continue());
|
|
263
|
+
}
|
|
264
|
+
if (this.config.network?.blockedOrigins?.length) {
|
|
265
|
+
for (const origin of this.config.network.blockedOrigins)
|
|
266
|
+
await context.route(`*://${origin}/**`, route => route.abort('blockedbyclient'));
|
|
267
|
+
}
|
|
268
|
+
for (const rule of this._routeRules) {
|
|
269
|
+
await context.route(rule.pattern, rule.handler);
|
|
270
|
+
rule.remove = () => {
|
|
271
|
+
void context.unroute(rule.pattern, rule.handler).catch(() => { });
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
_ensureBrowserContext() {
|
|
276
|
+
if (!this._browserContextPromise) {
|
|
277
|
+
this._browserContextPromise = this._setupBrowserContext();
|
|
278
|
+
this._browserContextPromise.catch(() => {
|
|
279
|
+
this._browserContextPromise = undefined;
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
return this._browserContextPromise;
|
|
283
|
+
}
|
|
284
|
+
async _setupBrowserContext() {
|
|
285
|
+
// TODO: move to the browser context factory to make it based on isolation mode.
|
|
286
|
+
const result = await this._browserContextFactory.createContext();
|
|
287
|
+
const { browserContext } = result;
|
|
288
|
+
await this._setupRequestInterception(browserContext);
|
|
289
|
+
for (const page of browserContext.pages())
|
|
290
|
+
this._onPageCreated(page);
|
|
291
|
+
browserContext.on('page', page => this._onPageCreated(page));
|
|
292
|
+
if (this.config.saveTrace) {
|
|
293
|
+
await browserContext.tracing.start({
|
|
294
|
+
name: 'trace',
|
|
295
|
+
screenshots: false,
|
|
296
|
+
snapshots: true,
|
|
297
|
+
sources: false,
|
|
298
|
+
});
|
|
299
|
+
this._tracingActive = true;
|
|
300
|
+
}
|
|
301
|
+
return result;
|
|
302
|
+
}
|
|
303
|
+
async browserContext() {
|
|
304
|
+
const { browserContext } = await this._ensureBrowserContext();
|
|
305
|
+
return browserContext;
|
|
306
|
+
}
|
|
307
|
+
hasBrowserContext() {
|
|
308
|
+
return !!this._browserContextPromise;
|
|
309
|
+
}
|
|
310
|
+
async addRouteRule(pattern, handler) {
|
|
311
|
+
const rule = { pattern, handler };
|
|
312
|
+
this._routeRules.push(rule);
|
|
313
|
+
if (this._browserContextPromise) {
|
|
314
|
+
const browserContext = await this.browserContext();
|
|
315
|
+
await browserContext.route(pattern, handler);
|
|
316
|
+
rule.remove = () => {
|
|
317
|
+
void browserContext.unroute(pattern, handler).catch(() => { });
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
listRouteRules() {
|
|
322
|
+
return this._routeRules.map(rule => rule.pattern);
|
|
323
|
+
}
|
|
324
|
+
async removeRouteRule(pattern) {
|
|
325
|
+
const rules = pattern ? this._routeRules.filter(rule => rule.pattern === pattern) : [...this._routeRules];
|
|
326
|
+
for (const rule of rules)
|
|
327
|
+
rule.remove?.();
|
|
328
|
+
this._routeRules = pattern ? this._routeRules.filter(rule => rule.pattern !== pattern) : [];
|
|
329
|
+
}
|
|
330
|
+
async setNetworkOffline(offline) {
|
|
331
|
+
this._networkOffline = offline;
|
|
332
|
+
if (this._browserContextPromise) {
|
|
333
|
+
const browserContext = await this.browserContext();
|
|
334
|
+
await browserContext.setOffline(offline);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
async startTracing() {
|
|
338
|
+
const browserContext = await this.browserContext();
|
|
339
|
+
if (this._tracingActive)
|
|
340
|
+
throw new Error('Tracing is already active.');
|
|
341
|
+
await browserContext.tracing.start({
|
|
342
|
+
name: 'trace',
|
|
343
|
+
screenshots: false,
|
|
344
|
+
snapshots: true,
|
|
345
|
+
sources: false,
|
|
346
|
+
});
|
|
347
|
+
this._tracingActive = true;
|
|
348
|
+
}
|
|
349
|
+
async stopTracing(filename) {
|
|
350
|
+
const browserContext = await this.browserContext();
|
|
351
|
+
if (!this._tracingActive)
|
|
352
|
+
throw new Error('Tracing is not active.');
|
|
353
|
+
const tracePath = filename ? await outputFile(this.config, filename) : await outputFile(this.config, `trace-${new Date().toISOString()}.zip`);
|
|
354
|
+
await browserContext.tracing.stop({ path: tracePath });
|
|
355
|
+
this._tracingActive = false;
|
|
356
|
+
return tracePath;
|
|
357
|
+
}
|
|
358
|
+
tracingActive() {
|
|
359
|
+
return this._tracingActive;
|
|
360
|
+
}
|
|
361
|
+
}
|
package/lib/fileUtils.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
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 os from 'node:os';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
export function cacheDir() {
|
|
19
|
+
let cacheDirectory;
|
|
20
|
+
if (process.platform === 'linux')
|
|
21
|
+
cacheDirectory = process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache');
|
|
22
|
+
else if (process.platform === 'darwin')
|
|
23
|
+
cacheDirectory = path.join(os.homedir(), 'Library', 'Caches');
|
|
24
|
+
else if (process.platform === 'win32')
|
|
25
|
+
cacheDirectory = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
|
|
26
|
+
else
|
|
27
|
+
throw new Error('Unsupported platform: ' + process.platform);
|
|
28
|
+
return path.join(cacheDirectory, 'camoufox-mcp');
|
|
29
|
+
}
|
|
30
|
+
export async function userDataDir(browserConfig) {
|
|
31
|
+
return path.join(cacheDir(), `mcp-${browserConfig.launchOptions?.channel ?? browserConfig?.browserName}-profile`);
|
|
32
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
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 { createConnection as createConnectionImpl } from './connection.js';
|
|
17
|
+
import { createMCPHTTPServer } from './mcpHttpServer.js';
|
|
18
|
+
import { resolveConfig } from './config.js';
|
|
19
|
+
import { contextFactory } from './browserContextFactory.js';
|
|
20
|
+
export async function createConnection(userConfig = {}, contextGetter) {
|
|
21
|
+
const config = await resolveConfig(userConfig);
|
|
22
|
+
const factory = contextGetter ? new SimpleBrowserContextFactory(contextGetter) : contextFactory(config.browser);
|
|
23
|
+
const connection = createConnectionImpl(config, factory);
|
|
24
|
+
return bindConnectionLifecycle(connection);
|
|
25
|
+
}
|
|
26
|
+
export { createMCPHTTPServer };
|
|
27
|
+
class SimpleBrowserContextFactory {
|
|
28
|
+
_contextGetter;
|
|
29
|
+
constructor(contextGetter) {
|
|
30
|
+
this._contextGetter = contextGetter;
|
|
31
|
+
}
|
|
32
|
+
async createContext() {
|
|
33
|
+
const browserContext = await this._contextGetter();
|
|
34
|
+
return {
|
|
35
|
+
browserContext,
|
|
36
|
+
close: () => browserContext.close()
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function bindConnectionLifecycle(connection) {
|
|
41
|
+
const server = connection.server;
|
|
42
|
+
const originalConnect = server.connect.bind(server);
|
|
43
|
+
const originalClose = server.close.bind(server);
|
|
44
|
+
let closed = false;
|
|
45
|
+
const closeConnection = async () => {
|
|
46
|
+
if (closed)
|
|
47
|
+
return;
|
|
48
|
+
closed = true;
|
|
49
|
+
await originalClose();
|
|
50
|
+
await connection.context.close();
|
|
51
|
+
};
|
|
52
|
+
server.close = closeConnection;
|
|
53
|
+
server.connect = async (transport) => {
|
|
54
|
+
const previousOnClose = transport.onclose;
|
|
55
|
+
transport.onclose = async () => {
|
|
56
|
+
try {
|
|
57
|
+
await previousOnClose?.();
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
await closeConnection();
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
await originalConnect(transport);
|
|
64
|
+
};
|
|
65
|
+
return server;
|
|
66
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
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
|
+
// adapted from:
|
|
17
|
+
// - https://github.com/microsoft/playwright/blob/76ee48dc9d4034536e3ec5b2c7ce8be3b79418a8/packages/playwright-core/src/utils/isomorphic/stringUtils.ts
|
|
18
|
+
// - https://github.com/microsoft/playwright/blob/76ee48dc9d4034536e3ec5b2c7ce8be3b79418a8/packages/playwright-core/src/server/codegen/javascript.ts
|
|
19
|
+
// NOTE: this function should not be used to escape any selectors.
|
|
20
|
+
export function escapeWithQuotes(text, char = '\'') {
|
|
21
|
+
const stringified = JSON.stringify(text);
|
|
22
|
+
const escapedText = stringified.substring(1, stringified.length - 1).replace(/\\"/g, '"');
|
|
23
|
+
if (char === '\'')
|
|
24
|
+
return char + escapedText.replace(/[']/g, '\\\'') + char;
|
|
25
|
+
if (char === '"')
|
|
26
|
+
return char + escapedText.replace(/["]/g, '\\"') + char;
|
|
27
|
+
if (char === '`')
|
|
28
|
+
return char + escapedText.replace(/[`]/g, '`') + char;
|
|
29
|
+
throw new Error('Invalid escape char');
|
|
30
|
+
}
|
|
31
|
+
export function quote(text) {
|
|
32
|
+
return escapeWithQuotes(text, '\'');
|
|
33
|
+
}
|
|
34
|
+
export function formatObject(value, indent = ' ') {
|
|
35
|
+
if (typeof value === 'string')
|
|
36
|
+
return quote(value);
|
|
37
|
+
if (Array.isArray(value))
|
|
38
|
+
return `[${value.map(o => formatObject(o)).join(', ')}]`;
|
|
39
|
+
if (typeof value === 'object') {
|
|
40
|
+
const keys = Object.keys(value).filter(key => value[key] !== undefined).sort();
|
|
41
|
+
if (!keys.length)
|
|
42
|
+
return '{}';
|
|
43
|
+
const tokens = [];
|
|
44
|
+
for (const key of keys)
|
|
45
|
+
tokens.push(`${key}: ${formatObject(value[key])}`);
|
|
46
|
+
return `{\n${indent}${tokens.join(`,\n${indent}`)}\n}`;
|
|
47
|
+
}
|
|
48
|
+
return String(value);
|
|
49
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
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
|
+
export class ManualPromise extends Promise {
|
|
17
|
+
_resolve;
|
|
18
|
+
_reject;
|
|
19
|
+
_isDone;
|
|
20
|
+
constructor() {
|
|
21
|
+
let resolve;
|
|
22
|
+
let reject;
|
|
23
|
+
super((f, r) => {
|
|
24
|
+
resolve = f;
|
|
25
|
+
reject = r;
|
|
26
|
+
});
|
|
27
|
+
this._isDone = false;
|
|
28
|
+
this._resolve = resolve;
|
|
29
|
+
this._reject = reject;
|
|
30
|
+
}
|
|
31
|
+
isDone() {
|
|
32
|
+
return this._isDone;
|
|
33
|
+
}
|
|
34
|
+
resolve(t) {
|
|
35
|
+
this._isDone = true;
|
|
36
|
+
this._resolve(t);
|
|
37
|
+
}
|
|
38
|
+
reject(e) {
|
|
39
|
+
this._isDone = true;
|
|
40
|
+
this._reject(e);
|
|
41
|
+
}
|
|
42
|
+
static get [Symbol.species]() {
|
|
43
|
+
return Promise;
|
|
44
|
+
}
|
|
45
|
+
get [Symbol.toStringTag]() {
|
|
46
|
+
return 'ManualPromise';
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
export class LongStandingScope {
|
|
50
|
+
_terminateError;
|
|
51
|
+
_closeError;
|
|
52
|
+
_terminatePromises = new Map();
|
|
53
|
+
_isClosed = false;
|
|
54
|
+
reject(error) {
|
|
55
|
+
this._isClosed = true;
|
|
56
|
+
this._terminateError = error;
|
|
57
|
+
for (const p of this._terminatePromises.keys())
|
|
58
|
+
p.resolve(error);
|
|
59
|
+
}
|
|
60
|
+
close(error) {
|
|
61
|
+
this._isClosed = true;
|
|
62
|
+
this._closeError = error;
|
|
63
|
+
for (const [p, frames] of this._terminatePromises)
|
|
64
|
+
p.resolve(cloneError(error, frames));
|
|
65
|
+
}
|
|
66
|
+
isClosed() {
|
|
67
|
+
return this._isClosed;
|
|
68
|
+
}
|
|
69
|
+
static async raceMultiple(scopes, promise) {
|
|
70
|
+
return Promise.race(scopes.map(s => s.race(promise)));
|
|
71
|
+
}
|
|
72
|
+
async race(promise) {
|
|
73
|
+
return this._race(Array.isArray(promise) ? promise : [promise], false);
|
|
74
|
+
}
|
|
75
|
+
async safeRace(promise, defaultValue) {
|
|
76
|
+
return this._race([promise], true, defaultValue);
|
|
77
|
+
}
|
|
78
|
+
async _race(promises, safe, defaultValue) {
|
|
79
|
+
const terminatePromise = new ManualPromise();
|
|
80
|
+
const frames = captureRawStack();
|
|
81
|
+
if (this._terminateError)
|
|
82
|
+
terminatePromise.resolve(this._terminateError);
|
|
83
|
+
if (this._closeError)
|
|
84
|
+
terminatePromise.resolve(cloneError(this._closeError, frames));
|
|
85
|
+
this._terminatePromises.set(terminatePromise, frames);
|
|
86
|
+
try {
|
|
87
|
+
return await Promise.race([
|
|
88
|
+
terminatePromise.then(e => safe ? defaultValue : Promise.reject(e)),
|
|
89
|
+
...promises
|
|
90
|
+
]);
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
this._terminatePromises.delete(terminatePromise);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
function cloneError(error, frames) {
|
|
98
|
+
const clone = new Error();
|
|
99
|
+
clone.name = error.name;
|
|
100
|
+
clone.message = error.message;
|
|
101
|
+
clone.stack = [error.name + ':' + error.message, ...frames].join('\n');
|
|
102
|
+
return clone;
|
|
103
|
+
}
|
|
104
|
+
function captureRawStack() {
|
|
105
|
+
const stackTraceLimit = Error.stackTraceLimit;
|
|
106
|
+
Error.stackTraceLimit = 50;
|
|
107
|
+
const error = new Error();
|
|
108
|
+
const stack = error.stack || '';
|
|
109
|
+
Error.stackTraceLimit = stackTraceLimit;
|
|
110
|
+
return stack.split('\n');
|
|
111
|
+
}
|