@mcpjam/cli 3.1.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,17 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command, CommanderError } from 'commander';
3
- import { realpathSync, readFileSync, existsSync, closeSync, statSync, renameSync, openSync } from 'fs';
3
+ import { realpathSync, readFileSync, existsSync, closeSync, mkdirSync, writeFileSync, renameSync, statSync, openSync } from 'fs';
4
4
  import { pathToFileURL, fileURLToPath } from 'url';
5
5
  import { probeMcpServer, runServerDoctor, collectServerSnapshot, serializeStableServerSnapshot, serializeServerSnapshot, buildServerDiffReport, validateToolCallResult, buildToolCallValidationReport, isCallToolResultError, listResources, readResource, listPrompts, getPrompt, MCPAppsConformanceTest, MCPAppsConformanceSuite, runOAuthLogin, OAuthConformanceTest, OAuthConformanceSuite, MCPConformanceTest, MCPConformanceSuite, redactSensitiveValue, withEphemeralClient, diffServerSnapshots, ServerSnapshotFormatError, renderStructuredRunJUnitXml, renderStructuredRunJson, MCP_UI_RESOURCE_MIME_TYPE, injectOpenAICompat, buildCspHeader, buildChatGptRuntimeHead, buildCspMetaContent, injectScripts, toConformanceReport, renderConformanceReportJUnitXml, renderConformanceReportJson, formatOAuthConformanceHuman, formatOAuthConformanceSuiteHuman, fetchOAuthMetadata, executeOAuthProxy, executeDebugOAuthProxy, MCP_APPS_CHECK_CATEGORIES, MCP_APPS_CHECK_IDS, OAuthProxyError, MCP_CHECK_CATEGORIES, MCP_CHECK_IDS } from '@mcpjam/sdk';
6
6
  import { mkdir, writeFile, readFile, chmod, rename, rm } from 'fs/promises';
7
- import path2, { join } from 'path';
7
+ import path2, { join, dirname } from 'path';
8
8
  import { randomUUID } from 'crypto';
9
9
  import { spawn } from 'child_process';
10
10
  import os, { homedir } from 'os';
11
+ import { PostHog } from 'posthog-node';
11
12
 
12
13
  // package.json
13
14
  var package_default = {
14
- version: "3.1.0"};
15
+ version: "3.2.0"};
15
16
 
16
17
  // src/lib/output.ts
17
18
  var DEFAULT_OUTPUT_FORMAT = "json";
@@ -950,7 +951,8 @@ function getGlobalOptions(command) {
950
951
  ),
951
952
  timeout: options.timeout ?? 3e4,
952
953
  rpc: options.rpc ?? false,
953
- quiet: options.quiet ?? false
954
+ quiet: options.quiet ?? false,
955
+ telemetry: options.telemetry ?? true
954
956
  };
955
957
  }
956
958
  function parsePositiveInteger(value, label = "Value") {
@@ -1124,7 +1126,7 @@ function addGlobalOptions(program) {
1124
1126
  "Request timeout in milliseconds",
1125
1127
  (value) => parsePositiveInteger(value, "Timeout"),
1126
1128
  3e4
1127
- ).option("--rpc", "Include RPC logs in JSON output").option("--quiet", "Suppress non-result progress output").option("--format <format>", "Output format");
1129
+ ).option("--rpc", "Include RPC logs in JSON output").option("--quiet", "Suppress non-result progress output").option("--no-telemetry", "Disable anonymous usage telemetry").option("--format <format>", "Output format");
1128
1130
  }
1129
1131
  function describeTarget(options) {
1130
1132
  return options.url?.trim() || options.command?.trim() || "__cli__";
@@ -3921,6 +3923,638 @@ function createServerDiffResult(left, right, failOn) {
3921
3923
  throw error;
3922
3924
  }
3923
3925
  }
3926
+ var DEFAULT_UPDATE_PACKAGE_NAME = "@mcpjam/cli";
3927
+ var UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
3928
+ var UPDATE_CACHE_FILE = "update-check.json";
3929
+ var BACKGROUND_FETCH_SCRIPT = `
3930
+ const fs = require("node:fs");
3931
+ const https = require("node:https");
3932
+ const path = require("node:path");
3933
+
3934
+ const cachePath = process.argv[1];
3935
+ const packageName = process.argv[2];
3936
+
3937
+ if (!cachePath || !packageName) {
3938
+ process.exit(0);
3939
+ }
3940
+
3941
+ const maxResponseBytes = 1024 * 1024;
3942
+ const registryPackageName = encodeURIComponent(packageName);
3943
+ const request = https.get(
3944
+ "https://registry.npmjs.org/" + registryPackageName + "/latest",
3945
+ {
3946
+ headers: {
3947
+ accept: "application/json",
3948
+ "user-agent": packageName + " update notifier",
3949
+ },
3950
+ },
3951
+ (response) => {
3952
+ if (response.statusCode !== 200) {
3953
+ response.resume();
3954
+ return;
3955
+ }
3956
+
3957
+ const chunks = [];
3958
+ let bytes = 0;
3959
+
3960
+ response.on("error", () => {});
3961
+ response.on("data", (chunk) => {
3962
+ bytes += chunk.length;
3963
+ if (bytes > maxResponseBytes) {
3964
+ request.destroy();
3965
+ return;
3966
+ }
3967
+ chunks.push(chunk);
3968
+ });
3969
+
3970
+ response.on("end", () => {
3971
+ try {
3972
+ const body = Buffer.concat(chunks, bytes).toString("utf8");
3973
+ const payload = JSON.parse(body);
3974
+ if (typeof payload.version !== "string") {
3975
+ return;
3976
+ }
3977
+
3978
+ fs.mkdirSync(path.dirname(cachePath), { recursive: true });
3979
+ const temporaryPath = cachePath + "." + process.pid + ".tmp";
3980
+ fs.writeFileSync(
3981
+ temporaryPath,
3982
+ JSON.stringify({
3983
+ latestVersion: payload.version,
3984
+ checkedAt: Date.now(),
3985
+ }),
3986
+ "utf8",
3987
+ );
3988
+ fs.renameSync(temporaryPath, cachePath);
3989
+ } catch {
3990
+ // Silently ignore: update cache refresh is best-effort.
3991
+ }
3992
+ });
3993
+ },
3994
+ );
3995
+
3996
+ request.setTimeout(2500, () => {
3997
+ request.destroy();
3998
+ });
3999
+ request.on("error", () => {});
4000
+ `;
4001
+ function getUpdateCacheDir(options = {}) {
4002
+ const env = options.env ?? process.env;
4003
+ const platform = options.platform ?? process.platform;
4004
+ const homeDirectory = options.homeDirectory ?? homedir();
4005
+ if (platform === "win32") {
4006
+ return join(
4007
+ env.LOCALAPPDATA || join(homeDirectory, "AppData", "Local"),
4008
+ "mcpjam",
4009
+ "Cache"
4010
+ );
4011
+ }
4012
+ if (platform === "darwin") {
4013
+ return join(homeDirectory, "Library", "Caches", "mcpjam");
4014
+ }
4015
+ return join(env.XDG_CACHE_HOME || join(homeDirectory, ".cache"), "mcpjam");
4016
+ }
4017
+ function getUpdateCachePath(options = {}) {
4018
+ return join(getUpdateCacheDir(options), UPDATE_CACHE_FILE);
4019
+ }
4020
+ function readUpdateCache(cachePath) {
4021
+ try {
4022
+ const payload = JSON.parse(readFileSync(cachePath, "utf8"));
4023
+ if (!payload || typeof payload !== "object" || Array.isArray(payload) || typeof payload.latestVersion !== "string" || typeof payload.checkedAt !== "number" || !Number.isFinite(payload.checkedAt)) {
4024
+ return null;
4025
+ }
4026
+ return {
4027
+ latestVersion: payload.latestVersion,
4028
+ checkedAt: payload.checkedAt
4029
+ };
4030
+ } catch {
4031
+ return null;
4032
+ }
4033
+ }
4034
+ function isUpdateCacheFresh(cache, now = Date.now()) {
4035
+ return now - cache.checkedAt < UPDATE_CHECK_INTERVAL_MS;
4036
+ }
4037
+ function shouldSkipUpdateCheck(options = {}) {
4038
+ const env = options.env ?? process.env;
4039
+ const isStderrTTY = options.isStderrTTY ?? Boolean(process.stderr.isTTY);
4040
+ return Boolean(
4041
+ env.CI || env.NO_UPDATE_NOTIFIER || env.MCPJAM_NO_UPDATE_CHECK || !isStderrTTY
4042
+ );
4043
+ }
4044
+ function isNewerVersion(latest, current) {
4045
+ const latestVersion = parseStableVersion(latest);
4046
+ const currentVersion = parseStableVersion(current);
4047
+ if (!latestVersion || !currentVersion) {
4048
+ return false;
4049
+ }
4050
+ for (let index = 0; index < latestVersion.length; index += 1) {
4051
+ if (latestVersion[index] > currentVersion[index]) {
4052
+ return true;
4053
+ }
4054
+ if (latestVersion[index] < currentVersion[index]) {
4055
+ return false;
4056
+ }
4057
+ }
4058
+ return false;
4059
+ }
4060
+ function spawnBackgroundFetch(cachePath, packageName = DEFAULT_UPDATE_PACKAGE_NAME, options = {}) {
4061
+ try {
4062
+ const spawn2 = options.spawn ?? spawn;
4063
+ const child = spawn2(
4064
+ options.execPath ?? process.execPath,
4065
+ ["-e", BACKGROUND_FETCH_SCRIPT, cachePath, packageName],
4066
+ {
4067
+ detached: true,
4068
+ stdio: "ignore"
4069
+ }
4070
+ );
4071
+ child.on("error", () => {
4072
+ });
4073
+ child.unref();
4074
+ } catch {
4075
+ }
4076
+ }
4077
+ function printUpdateNotification(currentVersion, latestVersion, packageName = DEFAULT_UPDATE_PACKAGE_NAME, stderr = process.stderr) {
4078
+ stderr.write(
4079
+ `Update available: ${packageName} ${currentVersion} -> ${latestVersion}
4080
+ Run npm install -g ${packageName} to update
4081
+ `
4082
+ );
4083
+ }
4084
+ function checkForUpdates(currentVersion, options = {}) {
4085
+ try {
4086
+ const env = options.env ?? process.env;
4087
+ if (shouldSkipUpdateCheck({
4088
+ env,
4089
+ isStderrTTY: options.isStderrTTY
4090
+ })) {
4091
+ return;
4092
+ }
4093
+ const now = typeof options.now === "function" ? options.now() : options.now ?? Date.now();
4094
+ const packageName = options.packageName ?? DEFAULT_UPDATE_PACKAGE_NAME;
4095
+ const cachePath = options.cachePath ?? getUpdateCachePath({
4096
+ env
4097
+ });
4098
+ const cache = readUpdateCache(cachePath);
4099
+ if (cache) {
4100
+ const hasNewerCachedVersion = isNewerVersion(
4101
+ cache.latestVersion,
4102
+ currentVersion
4103
+ );
4104
+ if (hasNewerCachedVersion) {
4105
+ printUpdateNotification(
4106
+ currentVersion,
4107
+ cache.latestVersion,
4108
+ packageName,
4109
+ options.stderr
4110
+ );
4111
+ }
4112
+ if (isUpdateCacheFresh(cache, now)) {
4113
+ return;
4114
+ }
4115
+ }
4116
+ const fetchSpawner = options.spawnBackgroundFetch ?? spawnBackgroundFetch;
4117
+ fetchSpawner(cachePath, packageName);
4118
+ } catch {
4119
+ }
4120
+ }
4121
+ function parseStableVersion(value) {
4122
+ if (typeof value !== "string") {
4123
+ return null;
4124
+ }
4125
+ const normalized = value.startsWith("v") ? value.slice(1) : value;
4126
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(normalized);
4127
+ if (!match) {
4128
+ return null;
4129
+ }
4130
+ const parts = match.slice(1).map((part) => Number(part));
4131
+ if (!parts.every((part) => Number.isSafeInteger(part) && part >= 0)) {
4132
+ return null;
4133
+ }
4134
+ return [parts[0], parts[1], parts[2]];
4135
+ }
4136
+
4137
+ // src/lib/telemetry.ts
4138
+ var POSTHOG_KEY = "phc_dTOPniyUNU2kD8Jx8yHMXSqiZHM8I91uWopTMX6EBE9";
4139
+ var POSTHOG_HOST = "https://us.i.posthog.com";
4140
+ var TELEMETRY_STATE_FILE = "telemetry.json";
4141
+ var TELEMETRY_EVENT_NAME = "cli_command";
4142
+ var TELEMETRY_STATE_VERSION = 1;
4143
+ var DEFAULT_FLUSH_TIMEOUT_MS = 3e3;
4144
+ var SAFE_ERROR_CODES = /* @__PURE__ */ new Set([
4145
+ "USAGE_ERROR",
4146
+ "TIMEOUT",
4147
+ "AUTH_FAILED",
4148
+ "TRANSPORT_ERROR",
4149
+ "SERVER_ERROR",
4150
+ "NETWORK_ERROR",
4151
+ "UNKNOWN_ERROR"
4152
+ ]);
4153
+ var activeRun = null;
4154
+ function getTelemetryStatePath(options = {}) {
4155
+ return options.statePath ?? join(getUpdateCacheDir(options), TELEMETRY_STATE_FILE);
4156
+ }
4157
+ function readTelemetryState(options = {}) {
4158
+ try {
4159
+ const payload = JSON.parse(readFileSync(getTelemetryStatePath(options), "utf8"));
4160
+ return parseTelemetryState(payload);
4161
+ } catch {
4162
+ return null;
4163
+ }
4164
+ }
4165
+ function getTelemetryStatus(options = {}) {
4166
+ const decision = resolveTelemetryDecision({
4167
+ ...options,
4168
+ commandOptOut: options.commandOptOut ?? false
4169
+ });
4170
+ return {
4171
+ enabled: decision.enabled,
4172
+ installId: decision.state?.installId ?? null,
4173
+ installIdCreated: Boolean(decision.state?.installId),
4174
+ stateFile: decision.stateFile,
4175
+ debugMode: decision.debugMode,
4176
+ disableReason: decision.disableReason
4177
+ };
4178
+ }
4179
+ function setTelemetryEnabled(enabled, options = {}) {
4180
+ const stateFile = getTelemetryStatePath(options);
4181
+ const existing = readTelemetryState(options);
4182
+ const now = getNow(options);
4183
+ const createdAt = existing?.createdAt ?? now;
4184
+ const installId = enabled ? existing?.installId ?? createInstallId(options) : existing?.installId;
4185
+ const nextState = {
4186
+ version: TELEMETRY_STATE_VERSION,
4187
+ enabled,
4188
+ ...installId ? { installId } : {},
4189
+ createdAt,
4190
+ updatedAt: now
4191
+ };
4192
+ writeTelemetryState(stateFile, nextState);
4193
+ return nextState;
4194
+ }
4195
+ function formatTelemetryStatusHuman(status) {
4196
+ const lines = [
4197
+ `Telemetry: ${status.enabled ? "enabled" : "disabled"}`,
4198
+ `Install ID: ${status.installId ?? "not created yet"}`,
4199
+ `State file: ${status.stateFile}`,
4200
+ `Debug mode: ${status.debugMode ? "on" : "off"}`
4201
+ ];
4202
+ if (status.disableReason) {
4203
+ lines.push(`Disable reason: ${status.disableReason}`);
4204
+ }
4205
+ return `${lines.join("\n")}
4206
+ `;
4207
+ }
4208
+ function initTelemetry(program, cliVersion, options = {}) {
4209
+ const run = {
4210
+ cliVersion,
4211
+ options,
4212
+ commandOptOut: false,
4213
+ shouldCapture: false,
4214
+ captured: false,
4215
+ pendingCaptures: []
4216
+ };
4217
+ activeRun = run;
4218
+ program.hook("preAction", (_thisCommand, actionCommand) => {
4219
+ if (activeRun !== run) {
4220
+ return;
4221
+ }
4222
+ const commandPath = getCommandPath(actionCommand);
4223
+ run.command = commandPath.join(" ");
4224
+ run.commandOptOut = isCommandTelemetryOptedOut(actionCommand);
4225
+ run.startedAtMs = Date.now();
4226
+ run.transport = detectTransport(actionCommand);
4227
+ run.shouldCapture = commandPath[0] !== "telemetry";
4228
+ run.captured = false;
4229
+ });
4230
+ return {
4231
+ async flush() {
4232
+ const client = run.client;
4233
+ if (!client) {
4234
+ return;
4235
+ }
4236
+ try {
4237
+ const timeoutMs = options.flushTimeoutMs ?? DEFAULT_FLUSH_TIMEOUT_MS;
4238
+ await withTimeout(
4239
+ flushClient(run, client, timeoutMs),
4240
+ timeoutMs
4241
+ );
4242
+ } catch {
4243
+ }
4244
+ }
4245
+ };
4246
+ }
4247
+ async function flushClient(run, client, timeoutMs) {
4248
+ const pendingCaptures = run.pendingCaptures.splice(0);
4249
+ if (pendingCaptures.length > 0) {
4250
+ await Promise.allSettled(pendingCaptures);
4251
+ }
4252
+ await client.flush(timeoutMs);
4253
+ }
4254
+ function captureCommandEvent(exitCode, errorCode) {
4255
+ const run = activeRun;
4256
+ if (!run || !run.shouldCapture || run.captured || !run.startedAtMs || !run.command) {
4257
+ return;
4258
+ }
4259
+ run.captured = true;
4260
+ try {
4261
+ const decision = resolveTelemetryDecision({
4262
+ ...run.options,
4263
+ commandOptOut: run.commandOptOut
4264
+ });
4265
+ if (!decision.enabled) {
4266
+ return;
4267
+ }
4268
+ const distinctId = resolveInstallId(run, decision.state);
4269
+ const isCiRun = isCi(run.options.env);
4270
+ const properties = {
4271
+ platform: "cli",
4272
+ command: run.command,
4273
+ success: exitCode === 0,
4274
+ exit_code: exitCode,
4275
+ duration_ms: Math.max(0, Date.now() - run.startedAtMs),
4276
+ cli_version: run.cliVersion,
4277
+ os: process.platform,
4278
+ arch: process.arch,
4279
+ node_version: process.version,
4280
+ is_ci: isCiRun
4281
+ };
4282
+ if (isCiRun) {
4283
+ properties.ci_name = detectCiName(run.options.env);
4284
+ }
4285
+ if (run.transport) {
4286
+ properties.transport = run.transport;
4287
+ }
4288
+ const safeErrorCode = exitCode === 0 ? void 0 : normalizeTelemetryErrorCode(errorCode);
4289
+ if (safeErrorCode) {
4290
+ properties.error_code = safeErrorCode;
4291
+ }
4292
+ if (decision.debugMode) {
4293
+ writeDebugPayload(run.options, distinctId, properties);
4294
+ return;
4295
+ }
4296
+ const client = getOrCreateClient(run);
4297
+ const pendingCapture = client.capture({
4298
+ distinctId,
4299
+ event: TELEMETRY_EVENT_NAME,
4300
+ properties
4301
+ });
4302
+ if (pendingCapture) {
4303
+ run.pendingCaptures.push(pendingCapture.catch(() => {
4304
+ }));
4305
+ }
4306
+ } catch {
4307
+ }
4308
+ }
4309
+ function resolveTelemetryDecision(options) {
4310
+ const stateFile = getTelemetryStatePath(options);
4311
+ const state = readTelemetryState(options);
4312
+ const envDisableReason = getEnvDisableReason(options.env);
4313
+ const disableReason = options.commandOptOut ? "--no-telemetry" : envDisableReason ?? (state?.enabled === false ? "state" : null);
4314
+ return {
4315
+ enabled: disableReason === null,
4316
+ disableReason,
4317
+ state,
4318
+ stateFile,
4319
+ debugMode: isDebugMode(options.env)
4320
+ };
4321
+ }
4322
+ function getEnvDisableReason(env = process.env) {
4323
+ if (env.DO_NOT_TRACK === "1") {
4324
+ return "DO_NOT_TRACK";
4325
+ }
4326
+ if (env.MCPJAM_TELEMETRY_DISABLED === "1") {
4327
+ return "MCPJAM_TELEMETRY_DISABLED";
4328
+ }
4329
+ return null;
4330
+ }
4331
+ function resolveInstallId(run, state) {
4332
+ if (state?.installId) {
4333
+ return state.installId;
4334
+ }
4335
+ try {
4336
+ const nextState = setTelemetryEnabled(true, run.options);
4337
+ if (nextState.installId) {
4338
+ return nextState.installId;
4339
+ }
4340
+ } catch {
4341
+ }
4342
+ run.fallbackInstallId ??= createInstallId(run.options);
4343
+ return run.fallbackInstallId;
4344
+ }
4345
+ function getOrCreateClient(run) {
4346
+ run.client ??= run.options.createClient?.() ?? new PostHogTelemetryClient(
4347
+ new PostHog(POSTHOG_KEY, {
4348
+ host: POSTHOG_HOST
4349
+ })
4350
+ );
4351
+ return run.client;
4352
+ }
4353
+ var PostHogTelemetryClient = class {
4354
+ constructor(client) {
4355
+ this.client = client;
4356
+ }
4357
+ capture(event) {
4358
+ return this.client.captureImmediate(event);
4359
+ }
4360
+ async flush(timeoutMs = DEFAULT_FLUSH_TIMEOUT_MS) {
4361
+ await this.client.shutdown(timeoutMs);
4362
+ }
4363
+ };
4364
+ function writeDebugPayload(options, distinctId, properties) {
4365
+ const stderr = options.stderr ?? process.stderr;
4366
+ stderr.write(
4367
+ `MCPJam telemetry debug: ${JSON.stringify({
4368
+ event: TELEMETRY_EVENT_NAME,
4369
+ distinct_id: distinctId,
4370
+ properties
4371
+ })}
4372
+ `
4373
+ );
4374
+ }
4375
+ function getCommandPath(actionCommand) {
4376
+ const names = [];
4377
+ let current = actionCommand;
4378
+ while (current) {
4379
+ const name = current.name();
4380
+ if (name && name !== "mcpjam") {
4381
+ names.unshift(name);
4382
+ }
4383
+ current = current.parent ?? null;
4384
+ }
4385
+ return names;
4386
+ }
4387
+ function isCommandTelemetryOptedOut(actionCommand) {
4388
+ const options = actionCommand.optsWithGlobals();
4389
+ return options.telemetry === false;
4390
+ }
4391
+ function detectTransport(actionCommand) {
4392
+ const options = actionCommand.optsWithGlobals();
4393
+ if (typeof options.url === "string" && options.url.trim().length > 0) {
4394
+ return "http";
4395
+ }
4396
+ if (typeof options.command === "string" && options.command.trim().length > 0) {
4397
+ return "stdio";
4398
+ }
4399
+ return void 0;
4400
+ }
4401
+ function normalizeTelemetryErrorCode(value) {
4402
+ if (value && SAFE_ERROR_CODES.has(value)) {
4403
+ return value;
4404
+ }
4405
+ if (value === "SERVER_UNREACHABLE") {
4406
+ return "NETWORK_ERROR";
4407
+ }
4408
+ if (value?.includes("AUTH") || value?.includes("UNAUTHORIZED")) {
4409
+ return "AUTH_FAILED";
4410
+ }
4411
+ if (value?.includes("TIMEOUT")) {
4412
+ return "TIMEOUT";
4413
+ }
4414
+ if (value?.includes("TRANSPORT")) {
4415
+ return "TRANSPORT_ERROR";
4416
+ }
4417
+ if (value?.includes("NETWORK") || value?.includes("UNREACHABLE")) {
4418
+ return "NETWORK_ERROR";
4419
+ }
4420
+ if (value?.includes("SERVER")) {
4421
+ return "SERVER_ERROR";
4422
+ }
4423
+ return "UNKNOWN_ERROR";
4424
+ }
4425
+ function isCi(env = process.env) {
4426
+ return Boolean(
4427
+ env.CI || env.GITHUB_ACTIONS || env.GITLAB_CI || env.CIRCLECI || env.BUILDKITE || env.JENKINS_URL || env.JENKINS_HOME || env.VERCEL || env.NETLIFY
4428
+ );
4429
+ }
4430
+ function isDebugMode(env = process.env) {
4431
+ return env.MCPJAM_TELEMETRY_DEBUG === "1";
4432
+ }
4433
+ function detectCiName(env = process.env) {
4434
+ if (env.GITHUB_ACTIONS) {
4435
+ return "github_actions";
4436
+ }
4437
+ if (env.GITLAB_CI) {
4438
+ return "gitlab_ci";
4439
+ }
4440
+ if (env.CIRCLECI) {
4441
+ return "circleci";
4442
+ }
4443
+ if (env.BUILDKITE) {
4444
+ return "buildkite";
4445
+ }
4446
+ if (env.JENKINS_URL || env.JENKINS_HOME) {
4447
+ return "jenkins";
4448
+ }
4449
+ if (env.VERCEL) {
4450
+ return "vercel";
4451
+ }
4452
+ if (env.NETLIFY) {
4453
+ return "netlify";
4454
+ }
4455
+ return "unknown";
4456
+ }
4457
+ function parseTelemetryState(value) {
4458
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
4459
+ return null;
4460
+ }
4461
+ const payload = value;
4462
+ if (payload.version !== TELEMETRY_STATE_VERSION || typeof payload.enabled !== "boolean" || typeof payload.createdAt !== "string" || typeof payload.updatedAt !== "string") {
4463
+ return null;
4464
+ }
4465
+ if (payload.installId !== void 0 && (typeof payload.installId !== "string" || !isValidUuid(payload.installId))) {
4466
+ return null;
4467
+ }
4468
+ return {
4469
+ version: TELEMETRY_STATE_VERSION,
4470
+ enabled: payload.enabled,
4471
+ ...typeof payload.installId === "string" ? { installId: payload.installId } : {},
4472
+ createdAt: payload.createdAt,
4473
+ updatedAt: payload.updatedAt
4474
+ };
4475
+ }
4476
+ function isValidUuid(value) {
4477
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
4478
+ value
4479
+ );
4480
+ }
4481
+ function writeTelemetryState(stateFile, state) {
4482
+ mkdirSync(dirname(stateFile), { recursive: true });
4483
+ const temporaryPath = `${stateFile}.${process.pid}.${Date.now()}.tmp`;
4484
+ writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
4485
+ `, {
4486
+ encoding: "utf8",
4487
+ mode: 384
4488
+ });
4489
+ renameSync(temporaryPath, stateFile);
4490
+ }
4491
+ function getNow(options) {
4492
+ return (options.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
4493
+ }
4494
+ function createInstallId(options) {
4495
+ return options.createId?.() ?? randomUUID();
4496
+ }
4497
+ async function withTimeout(promise, timeoutMs) {
4498
+ let timeout;
4499
+ try {
4500
+ return await Promise.race([
4501
+ promise,
4502
+ new Promise((resolve) => {
4503
+ timeout = setTimeout(resolve, timeoutMs);
4504
+ timeout.unref?.();
4505
+ })
4506
+ ]);
4507
+ } finally {
4508
+ if (timeout) {
4509
+ clearTimeout(timeout);
4510
+ }
4511
+ }
4512
+ }
4513
+
4514
+ // src/commands/telemetry.ts
4515
+ function registerTelemetryCommands(program, telemetryOptions = {}) {
4516
+ const telemetry = program.command("telemetry").description("Inspect and configure anonymous CLI telemetry");
4517
+ telemetry.command("status").description("Show the current telemetry status").action((_options, command) => {
4518
+ writeTelemetryStatus(
4519
+ resolveTelemetryStatus(command, telemetryOptions),
4520
+ getGlobalOptions(command).format
4521
+ );
4522
+ });
4523
+ telemetry.command("disable").description("Disable anonymous CLI telemetry").action((_options, command) => {
4524
+ setTelemetryEnabled(false, telemetryOptions);
4525
+ writeTelemetryStatus(
4526
+ resolveTelemetryStatus(command, telemetryOptions),
4527
+ getGlobalOptions(command).format
4528
+ );
4529
+ });
4530
+ telemetry.command("enable").description("Enable anonymous CLI telemetry").action((_options, command) => {
4531
+ setTelemetryEnabled(true, telemetryOptions);
4532
+ writeTelemetryStatus(
4533
+ resolveTelemetryStatus(command, telemetryOptions),
4534
+ getGlobalOptions(command).format
4535
+ );
4536
+ });
4537
+ }
4538
+ function resolveTelemetryStatus(command, telemetryOptions) {
4539
+ const options = command.optsWithGlobals();
4540
+ return getTelemetryStatus({
4541
+ ...telemetryOptions,
4542
+ commandOptOut: options.telemetry === false
4543
+ });
4544
+ }
4545
+ function writeTelemetryStatus(status, format) {
4546
+ if (format === "human") {
4547
+ process.stdout.write(formatTelemetryStatusHuman(status));
4548
+ return;
4549
+ }
4550
+ writeResult(
4551
+ {
4552
+ success: true,
4553
+ telemetry: status
4554
+ },
4555
+ format
4556
+ );
4557
+ }
3924
4558
  function registerToolsCommands(program) {
3925
4559
  const tools = program.command("tools").description("List and invoke MCP server tools");
3926
4560
  addRetryOptions(
@@ -4157,220 +4791,10 @@ function registerInspectorCommands(program) {
4157
4791
  );
4158
4792
  });
4159
4793
  }
4160
- var DEFAULT_UPDATE_PACKAGE_NAME = "@mcpjam/cli";
4161
- var UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
4162
- var UPDATE_CACHE_FILE = "update-check.json";
4163
- var BACKGROUND_FETCH_SCRIPT = `
4164
- const fs = require("node:fs");
4165
- const https = require("node:https");
4166
- const path = require("node:path");
4167
-
4168
- const cachePath = process.argv[1];
4169
- const packageName = process.argv[2];
4170
-
4171
- if (!cachePath || !packageName) {
4172
- process.exit(0);
4173
- }
4174
-
4175
- const maxResponseBytes = 1024 * 1024;
4176
- const registryPackageName = encodeURIComponent(packageName);
4177
- const request = https.get(
4178
- "https://registry.npmjs.org/" + registryPackageName + "/latest",
4179
- {
4180
- headers: {
4181
- accept: "application/json",
4182
- "user-agent": packageName + " update notifier",
4183
- },
4184
- },
4185
- (response) => {
4186
- if (response.statusCode !== 200) {
4187
- response.resume();
4188
- return;
4189
- }
4190
-
4191
- const chunks = [];
4192
- let bytes = 0;
4193
-
4194
- response.on("error", () => {});
4195
- response.on("data", (chunk) => {
4196
- bytes += chunk.length;
4197
- if (bytes > maxResponseBytes) {
4198
- request.destroy();
4199
- return;
4200
- }
4201
- chunks.push(chunk);
4202
- });
4203
-
4204
- response.on("end", () => {
4205
- try {
4206
- const body = Buffer.concat(chunks, bytes).toString("utf8");
4207
- const payload = JSON.parse(body);
4208
- if (typeof payload.version !== "string") {
4209
- return;
4210
- }
4211
-
4212
- fs.mkdirSync(path.dirname(cachePath), { recursive: true });
4213
- const temporaryPath = cachePath + "." + process.pid + ".tmp";
4214
- fs.writeFileSync(
4215
- temporaryPath,
4216
- JSON.stringify({
4217
- latestVersion: payload.version,
4218
- checkedAt: Date.now(),
4219
- }),
4220
- "utf8",
4221
- );
4222
- fs.renameSync(temporaryPath, cachePath);
4223
- } catch {
4224
- // Silently ignore: update cache refresh is best-effort.
4225
- }
4226
- });
4227
- },
4228
- );
4229
-
4230
- request.setTimeout(2500, () => {
4231
- request.destroy();
4232
- });
4233
- request.on("error", () => {});
4234
- `;
4235
- function getUpdateCacheDir(options = {}) {
4236
- const env = options.env ?? process.env;
4237
- const platform = options.platform ?? process.platform;
4238
- const homeDirectory = options.homeDirectory ?? homedir();
4239
- if (platform === "win32") {
4240
- return join(
4241
- env.LOCALAPPDATA || join(homeDirectory, "AppData", "Local"),
4242
- "mcpjam",
4243
- "Cache"
4244
- );
4245
- }
4246
- if (platform === "darwin") {
4247
- return join(homeDirectory, "Library", "Caches", "mcpjam");
4248
- }
4249
- return join(env.XDG_CACHE_HOME || join(homeDirectory, ".cache"), "mcpjam");
4250
- }
4251
- function getUpdateCachePath(options = {}) {
4252
- return join(getUpdateCacheDir(options), UPDATE_CACHE_FILE);
4253
- }
4254
- function readUpdateCache(cachePath) {
4255
- try {
4256
- const payload = JSON.parse(readFileSync(cachePath, "utf8"));
4257
- if (!payload || typeof payload !== "object" || Array.isArray(payload) || typeof payload.latestVersion !== "string" || typeof payload.checkedAt !== "number" || !Number.isFinite(payload.checkedAt)) {
4258
- return null;
4259
- }
4260
- return {
4261
- latestVersion: payload.latestVersion,
4262
- checkedAt: payload.checkedAt
4263
- };
4264
- } catch {
4265
- return null;
4266
- }
4267
- }
4268
- function isUpdateCacheFresh(cache, now = Date.now()) {
4269
- return now - cache.checkedAt < UPDATE_CHECK_INTERVAL_MS;
4270
- }
4271
- function shouldSkipUpdateCheck(options = {}) {
4272
- const env = options.env ?? process.env;
4273
- const isStderrTTY = options.isStderrTTY ?? Boolean(process.stderr.isTTY);
4274
- return Boolean(
4275
- env.CI || env.NO_UPDATE_NOTIFIER || env.MCPJAM_NO_UPDATE_CHECK || !isStderrTTY
4276
- );
4277
- }
4278
- function isNewerVersion(latest, current) {
4279
- const latestVersion = parseStableVersion(latest);
4280
- const currentVersion = parseStableVersion(current);
4281
- if (!latestVersion || !currentVersion) {
4282
- return false;
4283
- }
4284
- for (let index = 0; index < latestVersion.length; index += 1) {
4285
- if (latestVersion[index] > currentVersion[index]) {
4286
- return true;
4287
- }
4288
- if (latestVersion[index] < currentVersion[index]) {
4289
- return false;
4290
- }
4291
- }
4292
- return false;
4293
- }
4294
- function spawnBackgroundFetch(cachePath, packageName = DEFAULT_UPDATE_PACKAGE_NAME, options = {}) {
4295
- try {
4296
- const spawn2 = options.spawn ?? spawn;
4297
- const child = spawn2(
4298
- options.execPath ?? process.execPath,
4299
- ["-e", BACKGROUND_FETCH_SCRIPT, cachePath, packageName],
4300
- {
4301
- detached: true,
4302
- stdio: "ignore"
4303
- }
4304
- );
4305
- child.on("error", () => {
4306
- });
4307
- child.unref();
4308
- } catch {
4309
- }
4310
- }
4311
- function printUpdateNotification(currentVersion, latestVersion, packageName = DEFAULT_UPDATE_PACKAGE_NAME, stderr = process.stderr) {
4312
- stderr.write(
4313
- `Update available: ${packageName} ${currentVersion} -> ${latestVersion}
4314
- Run npm install -g ${packageName} to update
4315
- `
4316
- );
4317
- }
4318
- function checkForUpdates(currentVersion, options = {}) {
4319
- try {
4320
- const env = options.env ?? process.env;
4321
- if (shouldSkipUpdateCheck({
4322
- env,
4323
- isStderrTTY: options.isStderrTTY
4324
- })) {
4325
- return;
4326
- }
4327
- const now = typeof options.now === "function" ? options.now() : options.now ?? Date.now();
4328
- const packageName = options.packageName ?? DEFAULT_UPDATE_PACKAGE_NAME;
4329
- const cachePath = options.cachePath ?? getUpdateCachePath({
4330
- env
4331
- });
4332
- const cache = readUpdateCache(cachePath);
4333
- if (cache) {
4334
- const hasNewerCachedVersion = isNewerVersion(
4335
- cache.latestVersion,
4336
- currentVersion
4337
- );
4338
- if (hasNewerCachedVersion) {
4339
- printUpdateNotification(
4340
- currentVersion,
4341
- cache.latestVersion,
4342
- packageName,
4343
- options.stderr
4344
- );
4345
- }
4346
- if (isUpdateCacheFresh(cache, now)) {
4347
- return;
4348
- }
4349
- }
4350
- const fetchSpawner = options.spawnBackgroundFetch ?? spawnBackgroundFetch;
4351
- fetchSpawner(cachePath, packageName);
4352
- } catch {
4353
- }
4354
- }
4355
- function parseStableVersion(value) {
4356
- if (typeof value !== "string") {
4357
- return null;
4358
- }
4359
- const normalized = value.startsWith("v") ? value.slice(1) : value;
4360
- const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(normalized);
4361
- if (!match) {
4362
- return null;
4363
- }
4364
- const parts = match.slice(1).map((part) => Number(part));
4365
- if (!parts.every((part) => Number.isSafeInteger(part) && part >= 0)) {
4366
- return null;
4367
- }
4368
- return [parts[0], parts[1], parts[2]];
4369
- }
4370
4794
 
4371
4795
  // src/index.ts
4372
4796
  var pkgVersion = package_default.version;
4373
- async function main(argv = process.argv) {
4797
+ async function main(argv = process.argv, dependencies = {}) {
4374
4798
  const program = addGlobalOptions(
4375
4799
  new Command().name("mcpjam").version(pkgVersion, "-v, --version", "output the CLI version").description(
4376
4800
  "Test, debug, and validate MCP servers. Health checks, OAuth conformance, tool-surface diffing, and structured triage from the terminal or CI."
@@ -4380,6 +4804,7 @@ async function main(argv = process.argv) {
4380
4804
  }
4381
4805
  })
4382
4806
  );
4807
+ const telemetry = initTelemetry(program, pkgVersion, dependencies.telemetry);
4383
4808
  registerServerCommands(program);
4384
4809
  registerToolsCommands(program);
4385
4810
  registerResourcesCommands(program);
@@ -4388,6 +4813,7 @@ async function main(argv = process.argv) {
4388
4813
  registerOAuthCommands(program);
4389
4814
  registerProtocolCommands(program);
4390
4815
  registerInspectorCommands(program);
4816
+ registerTelemetryCommands(program, dependencies.telemetry);
4391
4817
  if (argv.length <= 2) {
4392
4818
  program.outputHelp();
4393
4819
  return {
@@ -4397,27 +4823,29 @@ async function main(argv = process.argv) {
4397
4823
  }
4398
4824
  try {
4399
4825
  await program.parseAsync(argv);
4400
- const exitCode = process.exitCode;
4401
- if (typeof exitCode === "number") {
4402
- return {
4403
- exitCode,
4404
- shouldCheckForUpdates: true
4405
- };
4406
- }
4826
+ const normalizedExitCode = typeof process.exitCode === "number" ? process.exitCode : 0;
4827
+ captureCommandEvent(
4828
+ normalizedExitCode,
4829
+ normalizedExitCode === 0 ? void 0 : "UNKNOWN_ERROR"
4830
+ );
4831
+ await telemetry.flush();
4407
4832
  return {
4408
- exitCode: Number(exitCode ?? 0) || 0,
4833
+ exitCode: normalizedExitCode,
4409
4834
  shouldCheckForUpdates: true
4410
4835
  };
4411
4836
  } catch (error) {
4412
4837
  const format = detectOutputFormatFromArgv(argv);
4413
4838
  if (error instanceof CommanderError) {
4414
4839
  if (error.code === "commander.helpDisplayed" || error.code === "commander.version") {
4840
+ await telemetry.flush();
4415
4841
  return {
4416
4842
  exitCode: 0,
4417
4843
  shouldCheckForUpdates: false
4418
4844
  };
4419
4845
  }
4420
4846
  writeError(usageError(error.message), format);
4847
+ captureCommandEvent(2, "USAGE_ERROR");
4848
+ await telemetry.flush();
4421
4849
  return {
4422
4850
  exitCode: 2,
4423
4851
  shouldCheckForUpdates: false
@@ -4425,6 +4853,8 @@ async function main(argv = process.argv) {
4425
4853
  }
4426
4854
  const normalizedError = normalizeCliError(error);
4427
4855
  writeError(normalizedError, format);
4856
+ captureCommandEvent(normalizedError.exitCode, normalizedError.code);
4857
+ await telemetry.flush();
4428
4858
  return {
4429
4859
  exitCode: normalizedError.exitCode,
4430
4860
  shouldCheckForUpdates: false
@@ -4432,7 +4862,7 @@ async function main(argv = process.argv) {
4432
4862
  }
4433
4863
  }
4434
4864
  async function runCliEntrypoint(argv = process.argv, dependencies = {}) {
4435
- const result = await main(argv);
4865
+ const result = await main(argv, dependencies);
4436
4866
  process.exitCode = result.exitCode;
4437
4867
  if (result.exitCode === 0 && result.shouldCheckForUpdates) {
4438
4868
  (dependencies.checkForUpdates ?? checkForUpdates)(pkgVersion);