forked from ChromeDevTools/chrome-devtools-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSessionManager.ts
More file actions
205 lines (182 loc) · 5.47 KB
/
SessionManager.ts
File metadata and controls
205 lines (182 loc) · 5.47 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import crypto from 'node:crypto';
import type {Channel} from './browser.js';
import {launch} from './browser.js';
import {logger} from './logger.js';
import {McpContext} from './McpContext.js';
import {Mutex} from './Mutex.js';
import type {Browser} from './third_party/index.js';
export interface SessionInfo {
sessionId: string;
browser: Browser;
context: McpContext;
mutex: Mutex;
createdAt: Date;
label?: string;
}
export interface CreateSessionOptions {
headless?: boolean;
executablePath?: string;
channel?: Channel;
userDataDir?: string;
viewport?: {width: number; height: number};
chromeArgs?: string[];
ignoreDefaultChromeArgs?: string[];
acceptInsecureCerts?: boolean;
devtools?: boolean;
enableExtensions?: boolean;
label?: string;
}
export interface McpContextOptions {
experimentalDevToolsDebugging: boolean;
experimentalIncludeAllPages?: boolean;
performanceCrux: boolean;
}
export class SessionManager {
readonly #sessions = new Map<string, SessionInfo>();
readonly #contextOptions: McpContextOptions;
#shuttingDown = false;
constructor(contextOptions: McpContextOptions) {
this.#contextOptions = contextOptions;
}
async createSession(options: CreateSessionOptions): Promise<SessionInfo> {
if (this.#shuttingDown) {
throw new Error('Server is shutting down. Cannot create new sessions.');
}
const sessionId = crypto.randomUUID().slice(0, 8);
logger(`Creating session ${sessionId}`);
let browser: Browser | undefined;
try {
browser = await launch({
headless: options.headless ?? false,
executablePath: options.executablePath,
channel: options.channel,
userDataDir: options.userDataDir,
// Always isolated to avoid profile conflicts between concurrent sessions
isolated: true,
viewport: options.viewport,
chromeArgs: options.chromeArgs ?? [],
ignoreDefaultChromeArgs: options.ignoreDefaultChromeArgs ?? [],
acceptInsecureCerts: options.acceptInsecureCerts,
devtools: options.devtools ?? false,
enableExtensions: options.enableExtensions,
});
const context = await McpContext.from(
browser,
logger,
this.#contextOptions,
);
const mutex = new Mutex();
const session: SessionInfo = {
sessionId,
browser,
context,
mutex,
createdAt: new Date(),
label: options.label,
};
browser.on('disconnected', () => {
logger(`Session ${sessionId} browser disconnected unexpectedly`);
this.#purgeDisconnectedSession(sessionId);
});
this.#sessions.set(sessionId, session);
logger(`Session ${sessionId} created`);
return session;
} catch (err) {
if (browser?.connected) {
try {
await browser.close();
} catch (closeErr) {
logger(`Failed to close browser after creation failure:`, closeErr);
}
}
throw err;
}
}
getSession(sessionId: string): SessionInfo {
const session = this.#sessions.get(sessionId);
if (!session) {
const available = [...this.#sessions.keys()].join(', ');
throw new Error(
`Session "${sessionId}" not found. Available sessions: ${available || 'none. Create one with create_session.'}`,
);
}
if (!session.browser.connected) {
this.#purgeDisconnectedSession(sessionId);
throw new Error(
`Session "${sessionId}" browser is disconnected. Create a new session.`,
);
}
return session;
}
listSessions(): Array<{
sessionId: string;
createdAt: string;
label?: string;
connected: boolean;
}> {
const result: Array<{
sessionId: string;
createdAt: string;
label?: string;
connected: boolean;
}> = [];
for (const [, session] of this.#sessions) {
result.push({
sessionId: session.sessionId,
createdAt: session.createdAt.toISOString(),
label: session.label,
connected: session.browser.connected,
});
}
return result;
}
async closeSession(sessionId: string): Promise<void> {
const session = this.#sessions.get(sessionId);
if (!session) {
throw new Error(`Session "${sessionId}" not found.`);
}
logger(`Closing session ${sessionId} (acquiring mutex)`);
const guard = await session.mutex.acquire();
try {
session.context.dispose();
if (session.browser.connected) {
await session.browser.close();
}
} catch (err) {
logger(`Error closing session ${sessionId}:`, err);
} finally {
guard.dispose();
this.#sessions.delete(sessionId);
logger(`Session ${sessionId} closed`);
}
}
async closeAllSessions(): Promise<void> {
this.#shuttingDown = true;
const ids = [...this.#sessions.keys()];
await Promise.allSettled(ids.map(id => this.closeSession(id)));
}
get sessionCount(): number {
return this.#sessions.size;
}
get isShuttingDown(): boolean {
return this.#shuttingDown;
}
#purgeDisconnectedSession(sessionId: string): void {
const session = this.#sessions.get(sessionId);
if (!session) {
return;
}
try {
session.context.dispose();
} catch (err) {
logger(`Error disposing context for disconnected session ${sessionId}:`, err);
}
this.#sessions.delete(sessionId);
logger(`Purged disconnected session ${sessionId}`);
}
}