-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathindex.ts
More file actions
256 lines (233 loc) · 8.54 KB
/
Copy pathindex.ts
File metadata and controls
256 lines (233 loc) · 8.54 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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type fs from 'node:fs';
import {type ParsedArguments} from './config/mcp-options.js';
import type {Channel} from './browser.js';
import {ensureBrowserConnected, ensureBrowserLaunched} from './browser.js';
import {loadIssueDescriptions} from './devtools/issueDescriptions.js';
import {McpContext} from './McpContext.js';
import {ClearcutLogger} from './telemetry/ClearcutLogger.js';
import {FilePersistence} from './telemetry/persistence.js';
import {
McpServer,
type CallToolResult,
type Root,
SetLevelRequestSchema,
ListRootsResultSchema,
RootsListChangedNotificationSchema,
} from './third_party/index.js';
import {ToolHandler} from './ToolHandler.js';
import type {DefinedPageTool, ToolDefinition} from './tools/ToolDefinition.js';
import {createTools} from './tools/tools.js';
import {logger} from './utils/logger.js';
import {Mutex, puppeteer} from './third_party/index.js';
import {VERSION} from './version.js';
export {buildFlag} from './ToolHandler.js';
puppeteer.setFollowSymlinks(false);
/**
* Timeout for a `roots/list` that a tool call is waiting on, matching the 5s
* default used for page operations. `getContext()` awaits it while
* `ToolHandler` holds the tool mutex, so leaving it unbounded lets a client
* that negotiates `roots` but does not answer block every tool for the SDK's
* default of 60s. Background refreshes are not bounded by this, so roots a
* slow client sends late still land.
*/
const ROOTS_REQUEST_TIMEOUT = 5_000;
export async function createMcpServer(
serverArgs: ParsedArguments,
options: {
logFile?: fs.WriteStream;
},
) {
if (serverArgs.usageStatistics) {
ClearcutLogger.initialize({
persistence: new FilePersistence(),
logFile: serverArgs.logFile,
appVersion: VERSION,
clearcutEndpoint: serverArgs.clearcutEndpoint,
clearcutForceFlushIntervalMs: serverArgs.clearcutForceFlushIntervalMs,
clearcutIncludePidHeader: serverArgs.clearcutIncludePidHeader,
});
}
const server = new McpServer(
{
name: 'chrome_devtools',
title: 'Chrome DevTools MCP server',
version: VERSION,
},
{capabilities: {logging: {}}},
);
server.server.setRequestHandler(SetLevelRequestSchema, () => {
return {};
});
// Roots are client state rather than browser state, so the last listing stays
// valid across browser reconnects and only the client can invalidate it, via
// the `roots/list_changed` notification handled below
let lastRoots: Root[] | undefined;
// `timeout` is only passed where a tool call is waiting on the result – the
// background refreshes below block nobody, so bounding them would just discard
// roots a slow client was about to send
const updateRoots = async (timeout?: number) => {
if (!server.server.getClientCapabilities()?.roots) {
return;
}
try {
const roots = await server.server.request(
{method: 'roots/list'},
ListRootsResultSchema,
timeout === undefined ? undefined : {timeout},
);
lastRoots = roots.roots;
context?.setRoots(lastRoots);
} catch (e) {
logger?.('Failed to list roots', e);
}
};
server.server.oninitialized = () => {
const clientName = server.server.getClientVersion()?.name;
if (clientName) {
ClearcutLogger.get()?.setClientName(clientName);
}
if (server.server.getClientCapabilities()?.roots) {
void updateRoots();
server.server.setNotificationHandler(
RootsListChangedNotificationSchema,
() => {
void updateRoots();
},
);
} else if (!serverArgs.allowUnrestrictedPaths) {
console.warn(
'[chrome-devtools-mcp] The connecting client did not negotiate the MCP roots ' +
'capability. File-writing tools will be restricted to the OS temp directory. ' +
'To restore the previous unrestricted behavior, start the server with ' +
'--allow-unrestricted-paths.',
);
}
};
let context: McpContext;
async function getContext(): Promise<McpContext> {
const chromeArgs: string[] = (serverArgs.chromeArg ?? []).map(String);
const ignoreDefaultChromeArgs: string[] = (
serverArgs.ignoreDefaultChromeArg ?? []
).map(String);
if (serverArgs.proxyServer) {
chromeArgs.push(`--proxy-server=${serverArgs.proxyServer}`);
}
const devtools = serverArgs.experimentalDevtools ?? false;
const blocklist = serverArgs.blockedUrlPattern
? serverArgs.blockedUrlPattern.map(String)
: undefined;
const allowlist = serverArgs.allowedUrlPattern
? serverArgs.allowedUrlPattern.map(String)
: undefined;
const browser =
serverArgs.browserUrl || serverArgs.wsEndpoint || serverArgs.autoConnect
? await ensureBrowserConnected({
browserURL: serverArgs.browserUrl,
wsEndpoint: serverArgs.wsEndpoint,
wsHeaders: serverArgs.wsHeaders,
// Important: only pass channel, if autoConnect is true.
channel: serverArgs.autoConnect
? (serverArgs.channel as Channel)
: undefined,
userDataDir: serverArgs.userDataDir,
devtools,
blocklist,
allowlist,
})
: await ensureBrowserLaunched({
headless: serverArgs.headless,
executablePath: serverArgs.executablePath,
channel: serverArgs.channel as Channel,
isolated: serverArgs.isolated ?? false,
userDataDir: serverArgs.userDataDir,
logFile: options.logFile,
viewport: serverArgs.viewport,
chromeArgs,
ignoreDefaultChromeArgs,
acceptInsecureCerts: serverArgs.acceptInsecureCerts,
devtools,
enableExtensions: serverArgs.categoryExtensions,
viaCli: serverArgs.viaCli,
blocklist,
allowlist,
});
if (context?.browser !== browser) {
context?.dispose();
context = await McpContext.from(browser, logger, {
experimentalDevToolsDebugging: devtools,
experimentalIncludeAllPages: serverArgs.experimentalIncludeAllPages,
performanceCrux: serverArgs.performanceCrux,
sourceMaps: serverArgs.sourceMaps,
allowList: allowlist,
blocklist: blocklist,
allowUnrestrictedPaths: serverArgs.allowUnrestrictedPaths,
// Surfaces a one-time note in the next response after a reconnect.
reconnected: context !== undefined,
});
if (lastRoots === undefined) {
// Nothing listed yet, so this call has to wait – bounded, since it is
// holding the tool mutex, and a later background refresh still lands
await updateRoots(ROOTS_REQUEST_TIMEOUT);
} else {
// Carry the known roots over and refresh out of band, so a reconnect
// never pays for a client round-trip
context.setRoots(lastRoots);
void updateRoots();
}
}
return context;
}
const toolMutex = new Mutex();
function registerTool(tool: ToolDefinition | DefinedPageTool): void {
const toolHandler = new ToolHandler(
tool,
serverArgs,
getContext,
toolMutex,
);
if (!toolHandler.shouldRegister) {
return;
}
server.registerTool(
tool.name,
{
description: tool.description,
inputSchema: toolHandler.registeredInputSchema,
annotations: tool.annotations,
},
async (params): Promise<CallToolResult> => {
return await toolHandler.handle(params);
},
);
}
const tools = createTools(serverArgs);
for (const tool of tools) {
registerTool(tool);
}
await loadIssueDescriptions();
return {server};
}
export const logDisclaimers = (args: ParsedArguments) => {
console.error(
`chrome-devtools-mcp exposes content of the browser instance to the MCP clients allowing them to inspect,
debug, and modify any data in the browser or DevTools.
Avoid sharing sensitive or personal information that you do not want to share with MCP clients.`,
);
if (!args.slim && args.performanceCrux) {
console.error(
`Performance tools may send trace URLs to the Google CrUX API to fetch real-user experience data. To disable, run with --no-performance-crux.`,
);
}
if (!args.slim && args.usageStatistics) {
console.error(
`
Google collects usage statistics to improve Chrome DevTools MCP. To opt-out, run with --no-usage-statistics.
For more details, visit: https://github.com/ChromeDevTools/chrome-devtools-mcp#usage-statistics`,
);
}
};