Chrome DevTools for coding agents
refactor(config): simplify watchConfig and start watcher inside connect (#3259)
Nikolay Vitkov878c5f641450
diff --git a/src/bin/chrome-devtools-mcp-main.ts b/src/bin/chrome-devtools-mcp-main.tsindex 8bcd9a5f..8185c467 100644--- a/src/bin/chrome-devtools-mcp-main.ts+++ b/src/bin/chrome-devtools-mcp-main.ts@@ -85,9 +85,6 @@ process.on('SIGHUP', () => {});const server = await serverPromise;-if (args.watchConfig) {- server.watchConfig(() => configParser.reloadConfig());-}const transport = new StdioServerTransport();await server.connect(transport);logger?.('Chrome DevTools MCP Server connected');diff --git a/src/config/ConfigParser.ts b/src/config/ConfigParser.tsindex a0dda3ea..a2ae9c08 100644--- a/src/config/ConfigParser.ts+++ b/src/config/ConfigParser.ts@@ -30,6 +30,7 @@ function isPlainObject(value: unknown): value is Record<string, unknown> {export class ConfigParser {#configPath?: string;+ #cliArgs?: Partial<ParsedArguments>;#usageStatisticsNoticeShown = false;readonly configLocator: ConfigLocator;@@ -84,10 +85,13 @@ export class ConfigParser {* Step 2: reads the JSON config file and runs it through yargs to reject* unknown keys and apply coercions, without applying defaults.*/- parseConfigFile(configPath: string): Partial<ParsedArguments> {+ static parseConfigFile(+ configPath: string,+ rawContent?: string,+ ): Partial<ParsedArguments> {try {const fileContent: unknown = JSON.parse(- readFileSync(configPath, 'utf-8'),+ rawContent ?? readFileSync(configPath, 'utf-8'),);if (!isPlainObject(fileContent)) {throw new Error('Config must be a JSON object');@@ -109,6 +113,13 @@ export class ConfigParser {}}+ parseConfigFile(+ configPath: string,+ rawContent?: string,+ ): Partial<ParsedArguments> {+ return ConfigParser.parseConfigFile(configPath, rawContent);+ }+warnUnknownArgs(cliArgs: Partial<ParsedArguments>): void {const allowedArgs = new Set(Object.keys(mcpOptions));const unknownArgs = Object.keys(cliArgs).filter(@@ -126,6 +137,7 @@ export class ConfigParser {parseConfig(): ServerConfig {try {const cliArgs = this.parseCliArgs();+ this.#cliArgs = cliArgs;this.#configPath = cliArgs.config ?? this.configLocator.locate(this.env);this.warnUnknownArgs(cliArgs);return this.#resolveConfig(cliArgs);@@ -149,7 +161,8 @@ export class ConfigParser {* instead of exiting the process.*/reloadConfig(): ServerConfig {- return this.#resolveConfig(this.parseCliArgs());+ this.#cliArgs ??= this.parseCliArgs();+ return this.#resolveConfig(this.#cliArgs);}/**diff --git a/src/config/ConfigWatcher.ts b/src/config/ConfigWatcher.tsindex 9f234f6b..ac7b749c 100644--- a/src/config/ConfigWatcher.ts+++ b/src/config/ConfigWatcher.ts@@ -26,7 +26,8 @@ function readContent(filePath: string): string | undefined {}/**- * Watches a config file and calls `onChange` after it was modified.+ * Watches a config file and calls `onChange` with the new content after it was+ * modified.** - Symlinks are resolved once on start, and the directory of the real file is* watched. Watching the directory instead of the file keeps working when@@ -39,7 +40,7 @@ function readContent(filePath: string): string | undefined {*/export class ConfigWatcher implements Disposable {readonly #configPath: string;- readonly #onChange: () => Promise<void>;+ readonly #onChange: (content: string) => Promise<void>;readonly #debounceMs: number;#watcher?: fs.FSWatcher;#debounced?: ReturnType<typeof DevTools.Common.Debouncer.debounce>;@@ -48,7 +49,7 @@ export class ConfigWatcher implements Disposable {constructor(configPath: string,- onChange: () => Promise<void>,+ onChange: (content: string) => Promise<void>,options: {debounceMs?: number} = {},) {this.#configPath = configPath;@@ -73,7 +74,7 @@ export class ConfigWatcher implements Disposable {}this.#content = content;this.#pending = this.#pending- .then(() => this.#onChange())+ .then(() => this.#onChange(content)).catch(err => {console.error(`Failed to apply ${this.#configPath}:`, err);});diff --git a/src/config/ServerConfig.ts b/src/config/ServerConfig.tsindex 3c9b2e62..e1b85aed 100644--- a/src/config/ServerConfig.ts+++ b/src/config/ServerConfig.ts@@ -290,6 +290,20 @@ export class ServerConfig implements ReadonlyServerConfig {return this.#resolved;}+ /**+ * Produces a new {@link ServerConfig} with updated config-file arguments,+ * preserving this config's CLI arguments, config path, and environment.+ */+ withFileArgs(fileArgs: Partial<ParsedArguments>): ServerConfig {+ return ServerConfig.create({+ cliArgs: {...this.#cliArgs},+ fileArgs,+ configPath: this.#configPath,+ env: this.#env,+ suppressUsageStatisticsNotice: true,+ });+ }+/*** Produces a new {@link ServerConfig} that takes reloadable options from* `next` and keeps restart-required options from this config, preservingdiff --git a/src/daemon/daemon.ts b/src/daemon/daemon.tsindex 42be3d8f..00f85eb9 100644--- a/src/daemon/daemon.ts+++ b/src/daemon/daemon.ts@@ -152,7 +152,7 @@ async function setupMCPServer(): Promise<void> {logFile,});if (args.watchConfig) {- mcpServer.watchConfig(() => configParser.reloadConfig());+ mcpServer.watchConfig();}ClearcutLogger.get()?.setClientName(DAEMON_CLIENT_NAME);void ClearcutLogger.get()?.logDailyActiveIfNeeded();diff --git a/src/index.ts b/src/index.tsindex 76a22d53..fe196578 100644--- a/src/index.ts+++ b/src/index.ts@@ -9,7 +9,7 @@ import path from 'node:path';import {pathToFileURL} from 'node:url';import {BrowserManager} from './BrowserManager.js';-import type {ParsedArguments} from './config/ConfigParser.js';+import {ConfigParser, type ParsedArguments} from './config/ConfigParser.js';import {ConfigWatcher} from './config/ConfigWatcher.js';import {DEFAULT_FILESYSTEM_ROOT} from './config/mcp-options.js';import {ServerConfig} from './config/ServerConfig.js';@@ -153,6 +153,9 @@ export class McpServer {}async connect(transport: Transport): Promise<void> {+ if (this.#config.resolved.watchConfig) {+ this.watchConfig();+ }return await this.server.connect(transport);}@@ -227,10 +230,8 @@ export class McpServer {/*** Watches the config file and applies its changes to the running server.- *- * @param reload Re-reads the config file and returns the new configuration.*/- watchConfig(reload: () => ServerConfig): void {+ watchConfig(): void {const configPath = this.#config.configPath;if (!configPath) {console.error(@@ -240,8 +241,8 @@ export class McpServer {}this.#configWatcher?.dispose();this.#configWatcher = undefined;- const watcher = new ConfigWatcher(configPath, () =>- this.#reloadConfig(watcher, configPath, reload),+ const watcher = new ConfigWatcher(configPath, content =>+ this.#reloadConfig(watcher, configPath, content),);try {watcher.start();@@ -256,7 +257,7 @@ export class McpServer {async #reloadConfig(watcher: ConfigWatcher,configPath: string,- reload: () => ServerConfig,+ content: string,): Promise<void> {using guard = await this.#taskRunner.pause();if (this.#configWatcher !== watcher) {@@ -265,7 +266,8 @@ export class McpServer {let config: ServerConfig;let nextConfig: ServerConfig;try {- config = reload();+ const fileArgs = ConfigParser.parseConfigFile(configPath, content);+ config = this.#config.withFileArgs(fileArgs);nextConfig = this.#config.mergeReloadable(config);} catch (err) {const message = `Keeping the previous configuration, failed to reload ${configPath}: ${getErrorMessage(err)}`;diff --git a/tests/McpServer.test.ts b/tests/McpServer.test.tsindex 7c27f41a..241bf0a9 100644--- a/tests/McpServer.test.ts+++ b/tests/McpServer.test.ts@@ -571,11 +571,11 @@ describe('McpServer', () => {const clock = sinon.useFakeTimers({toFake: ['setTimeout', 'clearTimeout'],});- const {server, context, config, configParser} = await createTestServer([+ const {server, context, config} = await createTestServer(['--config',configPath,]);- server.watchConfig(() => configParser.reloadConfig());+ server.watchConfig();logStream.write.resetHistory();async function updateConfigFile(content: string) {@@ -597,12 +597,39 @@ describe('McpServer', () => {};}+ it('starts watching on connect only when watchConfig is enabled', async () => {+ using configFile = createTempFile('{}', 'cd4a.watch.connect.json');+ const watchConfigSpy = sinon.spy(McpServer.prototype, 'watchConfig');+ const startStub = sinon.stub(ConfigWatcher.prototype, 'start');+ sinon.stub(ConfigWatcher.prototype, 'dispose');++ const {server: disabledServer} = await createTestServer(+ ['--config', configFile.path],+ {mockContext: false},+ );+ const [, disabledTransport] = InMemoryTransport.createLinkedPair();+ await disabledServer.connect(disabledTransport);+ sinon.assert.notCalled(watchConfigSpy);+ sinon.assert.notCalled(startStub);+ await disabledServer.close();++ const {server: enabledServer} = await createTestServer(+ ['--config', configFile.path, '--watchConfig'],+ {mockContext: false},+ );+ const [, enabledTransport] = InMemoryTransport.createLinkedPair();+ await enabledServer.connect(enabledTransport);+ sinon.assert.calledOnceWithExactly(watchConfigSpy);+ sinon.assert.calledOnceWithExactly(startStub);+ await enabledServer.close();+ });+it('does not start a watcher when no config file was resolved', async () => {const startStub = sinon.stub(ConfigWatcher.prototype, 'start');- const {server, configParser} = await createTestServer();+ const {server} = await createTestServer();const consoleError = sinon.stub(console, 'error');- server.watchConfig(() => configParser.reloadConfig());+ server.watchConfig();sinon.assert.notCalled(startStub);sinon.assert.calledOnceWithExactly(@@ -617,13 +644,10 @@ describe('McpServer', () => {.stub(ConfigWatcher.prototype, 'start').throws(new Error('watch limit reached'));const disposeStub = sinon.stub(ConfigWatcher.prototype, 'dispose');- const {server, configParser} = await createTestServer([- '--config',- configFile.path,- ]);+ const {server} = await createTestServer(['--config', configFile.path]);const consoleError = sinon.stub(console, 'error');- server.watchConfig(() => configParser.reloadConfig());+ server.watchConfig();sinon.assert.calledOnceWithExactly(disposeStub);sinon.assert.calledOnceWithExactly(@@ -636,16 +660,13 @@ describe('McpServer', () => {using configFile = createTempFile('{}', 'cd4a.watch.lifecycle.json');const startStub = sinon.stub(ConfigWatcher.prototype, 'start');const disposeStub = sinon.stub(ConfigWatcher.prototype, 'dispose');- const {server, configParser} = await createTestServer([- '--config',- configFile.path,- ]);+ const {server} = await createTestServer(['--config', configFile.path]);- server.watchConfig(() => configParser.reloadConfig());+ server.watchConfig();sinon.assert.calledOnceWithExactly(startStub);sinon.assert.notCalled(disposeStub);- server.watchConfig(() => configParser.reloadConfig());+ server.watchConfig();sinon.assert.calledTwice(startStub);sinon.assert.calledOnceWithExactly(disposeStub);diff --git a/tests/config/ConfigWatcher.test.ts b/tests/config/ConfigWatcher.test.tsindex 3fa9af0b..10edccbe 100644--- a/tests/config/ConfigWatcher.test.ts+++ b/tests/config/ConfigWatcher.test.ts@@ -68,7 +68,7 @@ async function waitForWatchReady(dir: string): Promise<fs.FSWatcher> {async function startWatcher(watchedPath: string,- onChange: () => Promise<void> = sinon.stub().resolves(),+ onChange: (content: string) => Promise<void> = sinon.stub().resolves(),): Promise<{watcher: ConfigWatcher} & Disposable> {const watcher = new ConfigWatcher(watchedPath, onChange, {debounceMs: DEBOUNCE_MS,@@ -97,7 +97,7 @@ describe('ConfigWatcher', () => {fs.writeFileSync(configPath, '{"headless": false}');await waitForCall(onChange);- sinon.assert.calledOnceWithExactly(onChange);+ sinon.assert.calledOnceWithExactly(onChange, '{"headless": false}');});it('detects atomic replacements', async () => {@@ -111,7 +111,7 @@ describe('ConfigWatcher', () => {fs.renameSync(tempPath, configPath);await waitForCall(onChange);- sinon.assert.calledOnceWithExactly(onChange);+ sinon.assert.calledOnceWithExactly(onChange, '{"headless": true}');});it('ignores other files in the directory', async () => {@@ -138,7 +138,7 @@ describe('ConfigWatcher', () => {fs.writeFileSync(configPath, '{"headless": true}');await waitForCall(onChange);- sinon.assert.calledOnceWithExactly(onChange);+ sinon.assert.calledOnceWithExactly(onChange, '{"headless": true}');});it('does not call onChange if the content did not change', async () => {@@ -209,7 +209,7 @@ describe('ConfigWatcher', () => {fs.writeFileSync(configPath, '{"headless": true}');await waitForCall(onChange);- sinon.assert.calledOnce(onChange);+ sinon.assert.calledOnceWithExactly(onChange, '{"headless": true}');fs.writeFileSync(configPath, '{"headless": false}');await wait(SETTLE_MS);@@ -218,5 +218,6 @@ describe('ConfigWatcher', () => {firstCall.resolve();await secondCall.promise;sinon.assert.calledTwice(onChange);+ sinon.assert.calledWithExactly(onChange.secondCall, '{"headless": false}');});});diff --git a/tests/config/ServerConfig.test.ts b/tests/config/ServerConfig.test.tsindex 46c70cc8..85d977f3 100644--- a/tests/config/ServerConfig.test.ts+++ b/tests/config/ServerConfig.test.ts@@ -364,6 +364,25 @@ describe('ServerConfig', () => {});});+ describe('ServerConfig.withFileArgs()', () => {+ it('creates a new ServerConfig with updated fileArgs and preserved cliArgs', () => {+ const initial = ServerConfig.create({+ cliArgs: {headless: true},+ fileArgs: {memoryDebugging: false},+ configPath: '/tmp/cd4a.config.json',+ env: {CI: 'true'},+ suppressUsageStatisticsNotice: true,+ });++ const updated = initial.withFileArgs({memoryDebugging: true});++ assert.strictEqual(updated.resolved.headless, true);+ assert.strictEqual(updated.resolved.memoryDebugging, true);+ assert.strictEqual(updated.resolved.usageStatistics, false);+ assert.strictEqual(updated.configPath, '/tmp/cd4a.config.json');+ });+ });+describe('getRestartRequiredChanges', () => {it('ignores reloadable option changes', () => {const previous = parseConfig();