forked from ChromeDevTools/chrome-devtools-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.ts
More file actions
98 lines (84 loc) · 2.28 KB
/
context.ts
File metadata and controls
98 lines (84 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {ensureBrowserConnected} from './browser.js';
import {logger} from './logger.js';
import {McpContext} from './McpContext.js';
let context: McpContext | undefined;
export interface SetContextOptions {
browserURL?: string;
wsEndpoint?: string;
devtools?: boolean;
experimentalIncludeAllPages?: boolean;
timeout?: number;
}
export async function setContext(
options: SetContextOptions,
): Promise<McpContext> {
const {
browserURL,
wsEndpoint,
devtools = false,
experimentalIncludeAllPages = false,
timeout,
} = options;
logger('setContext called with:', {
browserURL,
wsEndpoint,
devtools,
timeout,
});
const connectPromise = ensureBrowserConnected({
browserURL,
wsEndpoint,
devtools,
});
let browser;
logger('Starting browser connection, timeout:', timeout);
if (timeout) {
let timeoutId: NodeJS.Timeout | undefined;
const timeoutPromise = new Promise<never>((_, reject) => {
timeoutId = setTimeout(
() =>
reject(
new Error(
`Failed to connect to browser within ${timeout}ms. Please check that the browser is running and accessible at the provided URL.`,
),
),
timeout,
);
});
try {
browser = await Promise.race([connectPromise, timeoutPromise]);
} finally {
// Clear timeout to prevent it from firing after connection succeeds
if (timeoutId) {
clearTimeout(timeoutId);
}
}
} else {
browser = await connectPromise;
}
logger('Browser connection completed, browser type:', typeof browser);
logger('Browser connected status:', browser?.connected);
if (!browser) {
throw new Error(
'Failed to connect to browser: browser object is undefined',
);
}
logger('Creating McpContext from browser...');
context = await McpContext.from(browser, logger, {
experimentalDevToolsDebugging: devtools,
experimentalIncludeAllPages,
});
logger('McpContext created successfully');
return context;
}
export function getContext(): McpContext | undefined {
return context;
}
export function setContextInstance(newContext: McpContext | undefined): void {
context = newContext;
}