Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions scripts/profile/footprint_mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
*
* The script launches the server over stdio, completes the MCP handshake
* (`initialize` and `tools/list`), waits for the process tree to settle and
* then reads the memory of every process in the tree from the OS. The tree
* includes the telemetry watchdog when usage statistics are on.
* then reads the memory of every process in the tree from the OS. The idle
* tree has no telemetry watchdog: it starts on the first tool call.
*/

import {execFile} from 'node:child_process';
Expand Down Expand Up @@ -88,15 +88,16 @@ interface FootprintOptions {
const MiB = 1024 * 1024;

// Budgets are strict: about 3% above the median measured on Linux x64
// (default: 116.8 MiB, no-usage-statistics: 106.6 MiB). Raise a budget only
// (no-usage-statistics: 106.6 MiB). The idle default tree has no watchdog and
// measured 1.5 MiB above no-usage-statistics locally. Raise a budget only
// together with a change that needs the memory.
const CONFIGURATIONS: FootprintConfiguration[] = [
{
name: 'default',
description: 'usage statistics on (server + telemetry watchdog)',
description: 'usage statistics on (server only until the first tool call)',
serverArgs: ['--usage-statistics'],
usageStatistics: true,
maxPrivateBytes: 120 * MiB,
maxPrivateBytes: 112 * MiB,
},
{
name: 'no-usage-statistics',
Expand Down Expand Up @@ -345,7 +346,7 @@ async function launchAndMeasure(
env.CHROME_DEVTOOLS_MCP_NO_CONFIG_DISCOVERY = 'true';
if (configuration.usageStatistics) {
// CI and the env var below force usage statistics off. The flag on the
// command line must win so that the watchdog is part of the measurement.
// command line must win so that telemetry is part of the measurement.
delete env.CI;
delete env.CHROME_DEVTOOLS_MCP_NO_USAGE_STATISTICS;
} else {
Expand Down
3 changes: 3 additions & 0 deletions src/bin/chrome-devtools-mcp-main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,10 @@ async function shutdown(reason: string): Promise<void> {
process.exit(0);
}, 5000).unref();
const server = await serverPromise;
// Runs concurrently with server.close() and never rejects.
const shutdownLogged = ClearcutLogger.get()?.logServerShutdownIfNoWatchdog();
await server.close();
await shutdownLogged;
process.exit(0);
}
process.stdin.on('end', () => {
Expand Down
3 changes: 3 additions & 0 deletions src/daemon/daemon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,11 +279,14 @@ async function cleanup(exitCode = 0): Promise<void> {
isCleaningUp = true;
console.log('Cleaning up daemon...');

// Runs concurrently with mcpServer.close() and never rejects.
const shutdownLogged = ClearcutLogger.get()?.logServerShutdownIfNoWatchdog();
try {
await mcpServer?.close();
} catch (error) {
logger?.('Error closing MCP server:', error);
}
await shutdownLogged;
const activeServer = server;
if (activeServer) {
await new Promise<void>(resolve => {
Expand Down
122 changes: 98 additions & 24 deletions src/telemetry/ClearcutLogger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/

import crypto from 'node:crypto';
import process from 'node:process';

import {DAEMON_CLIENT_NAME} from '../daemon/utils.js';
Expand All @@ -28,10 +29,13 @@ import {
OsType,
type ToolInvocation,
} from './types.js';
import {sendClearcutBatch} from './watchdog/ClearcutSender.js';
import {WatchdogClient} from './WatchdogClient.js';
import type {DevToolsData} from '../tools/ToolDefinition.js';

const MS_PER_DAY = 24 * 60 * 60 * 1000;
// Keeps the shutdown event within the server's 5 s shutdown backstop.
const SHUTDOWN_REQUEST_TIMEOUT_MS = 2_500;

function detectOsType(): OsType {
switch (process.platform) {
Expand Down Expand Up @@ -77,7 +81,8 @@ export interface ClearcutLoggerOptions {
appVersion: string;
persistence: Persistence;
logFile?: string;
watchdogClient?: WatchdogClient;
createWatchdogClient?: () => WatchdogClient;
sendClearcutBatch?: typeof sendClearcutBatch;
clearcutEndpoint?: string;
clearcutForceFlushIntervalMs?: number;
clearcutIncludePidHeader?: boolean;
Expand All @@ -88,10 +93,17 @@ let _clearcut_logger_instance: ClearcutLogger | undefined;

export class ClearcutLogger {
#persistence: Persistence;
#watchdog: WatchdogClient;
#createWatchdogClient: () => WatchdogClient;
#watchdog?: WatchdogClient;
#sendClearcutBatch: typeof sendClearcutBatch;
#clearcutEndpoint?: string;
#appVersion: string;
#osType: OsType;
#sessionId: string;
#mcpClient: McpClient;
#rawClientName?: string;
#state?: LocalState;
#shutDown = false;

static initialize(options: ClearcutLoggerOptions): ClearcutLogger {
if (_clearcut_logger_instance) {
Expand All @@ -111,17 +123,24 @@ export class ClearcutLogger {

private constructor(options: ClearcutLoggerOptions) {
this.#persistence = options.persistence;
this.#watchdog =
options.watchdogClient ??
new WatchdogClient({
parentPid: process.pid,
appVersion: options.appVersion,
osType: detectOsType(),
logFile: options.logFile,
clearcutEndpoint: options.clearcutEndpoint,
clearcutForceFlushIntervalMs: options.clearcutForceFlushIntervalMs,
clearcutIncludePidHeader: options.clearcutIncludePidHeader,
});
this.#sendClearcutBatch = options.sendClearcutBatch ?? sendClearcutBatch;
this.#clearcutEndpoint = options.clearcutEndpoint;
this.#appVersion = options.appVersion;
this.#osType = detectOsType();
this.#sessionId = crypto.randomUUID();
this.#createWatchdogClient =
options.createWatchdogClient ??
(() =>
new WatchdogClient({
parentPid: process.pid,
appVersion: this.#appVersion,
osType: this.#osType,
sessionId: this.#sessionId,
logFile: options.logFile,
clearcutEndpoint: options.clearcutEndpoint,
clearcutForceFlushIntervalMs: options.clearcutForceFlushIntervalMs,
clearcutIncludePidHeader: options.clearcutIncludePidHeader,
}));
this.#mcpClient = McpClient.MCP_CLIENT_UNSPECIFIED;
void this.#persistence
.loadState()
Expand Down Expand Up @@ -182,6 +201,58 @@ export class ClearcutLogger {
return ext;
}

// Spawns the watchdog process on the first event that needs it.
#getWatchdog(): WatchdogClient | undefined {
if (!this.#watchdog && this.#shutDown) {
logger?.('Server is shutting down, dropping telemetry event');
return undefined;
}
this.#watchdog ??= this.#createWatchdogClient();
return this.#watchdog;
}

// Sends one event from this process without going through the watchdog.
async #sendDirectly(
payload: ChromeDevToolsMcpExtension,
options: {requestTimeoutMs?: number} = {},
): Promise<void> {
const event: ChromeDevToolsMcpExtension = {
...payload,
session_id: this.#sessionId,
app_version: this.#appVersion,
os_type: this.#osType,
};
try {
const result = await this.#sendClearcutBatch(
[{event, timestamp: Date.now()}],
{clearcutEndpoint: this.#clearcutEndpoint, ...options},
);
if (!result.success) {
logger?.('Failed to send telemetry event:', JSON.stringify(result));
}
} catch (error) {
logger?.('Error sending telemetry event:', error);
}
}

/**
* Sends `server_shutdown` when the server exits without a watchdog.
*
* The watchdog sends `server_shutdown` when the server exits. If no
* watchdog was started, the logger sends it. After this call, no watchdog
* is started, so later events that need one are dropped.
*/
async logServerShutdownIfNoWatchdog(): Promise<void> {
this.#shutDown = true;
if (this.#watchdog) {
return;
}
await this.#sendDirectly(
{server_shutdown: {}},
{requestTimeoutMs: SHUTDOWN_REQUEST_TIMEOUT_MS},
);
}

async logToolInvocation(args: {
toolName: string;
params: ShapeOutput<zod.ZodRawShape>;
Expand Down Expand Up @@ -214,7 +285,7 @@ export class ClearcutLogger {
};
}

this.#watchdog.send({
this.#getWatchdog()?.send({
type: WatchdogMessageType.LOG_EVENT,
payload: this.#addMcpClient({
tool_invocation,
Expand All @@ -223,14 +294,13 @@ export class ClearcutLogger {
}

async logServerStart(flagUsage: FlagUsage): Promise<void> {
this.#watchdog.send({
type: WatchdogMessageType.LOG_EVENT,
payload: this.#addMcpClient({
await this.#sendDirectly(
this.#addMcpClient({
server_start: {
flag_usage: flagUsage,
},
}),
});
);
}

async logDailyActiveIfNeeded(): Promise<void> {
Expand All @@ -240,17 +310,17 @@ export class ClearcutLogger {
if (shouldLogDailyActive(this.#state)) {
const daysSince = calculateDaysSince(this.#state.lastActive);

this.#watchdog.send({
type: WatchdogMessageType.LOG_EVENT,
payload: this.#addMcpClient({
const sent = this.#sendDirectly(
this.#addMcpClient({
daily_active: {
days_since_last_active: bucketizeDaysSince(daysSince),
},
}),
});
);

this.#state.lastActive = new Date().toISOString();
await this.#persistence.saveState(this.#state);
await sent;
}
} catch (err) {
logger?.('Error in logDailyActiveIfNeeded:', err);
Expand All @@ -261,7 +331,7 @@ export class ClearcutLogger {
errorCode: ErrorCode;
toolName?: string;
}): Promise<void> {
this.#watchdog.send({
this.#getWatchdog()?.send({
type: WatchdogMessageType.LOG_EVENT,
payload: this.#addMcpClient({
server_error: {
Expand Down Expand Up @@ -298,7 +368,11 @@ export class ClearcutLogger {

const daysSinceToolCall = calculateDaysSince(state.lastToolCall, now);

this.#watchdog.send({
const watchdog = this.#getWatchdog();
if (!watchdog) {
return;
}
watchdog.send({
type: WatchdogMessageType.LOG_EVENT,
payload: this.#addMcpClient({
tool_active: {
Expand Down
4 changes: 4 additions & 0 deletions src/telemetry/WatchdogClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export class WatchdogClient {
parentPid: number;
appVersion: string;
osType: OsType;
sessionId?: string;
logFile?: string;
clearcutEndpoint?: string;
clearcutForceFlushIntervalMs?: number;
Expand All @@ -37,6 +38,9 @@ export class WatchdogClient {
`--os-type=${config.osType}`,
];

if (config.sessionId) {
args.push(`--session-id=${config.sessionId}`);
}
if (config.logFile) {
args.push(`--log-file=${config.logFile}`);
}
Expand Down
Loading
Loading