@mcpjam/cli 2.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,18 +1,18 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';
3
-
4
- var commander = require('commander');
5
- var sdk = require('@mcpjam/sdk');
6
- var fs = require('fs');
7
- var promises = require('fs/promises');
8
- var path = require('path');
9
-
10
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
-
12
- var path__default = /*#__PURE__*/_interopDefault(path);
2
+ import { Command, CommanderError } from 'commander';
3
+ import { realpathSync, readFileSync, existsSync, closeSync, mkdirSync, writeFileSync, renameSync, statSync, openSync } from 'fs';
4
+ import { pathToFileURL, fileURLToPath } from 'url';
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
+ import { mkdir, writeFile, readFile, chmod, rename, rm } from 'fs/promises';
7
+ import path2, { join, dirname } from 'path';
8
+ import { randomUUID } from 'crypto';
9
+ import { spawn } from 'child_process';
10
+ import os, { homedir } from 'os';
11
+ import { PostHog } from 'posthog-node';
13
12
 
14
13
  // package.json
15
- var version = "2.1.0";
14
+ var package_default = {
15
+ version: "3.2.0"};
16
16
 
17
17
  // src/lib/output.ts
18
18
  var DEFAULT_OUTPUT_FORMAT = "json";
@@ -93,8 +93,16 @@ function parseOutputFormat(value) {
93
93
  if (value === "json" || value === "human") {
94
94
  return value;
95
95
  }
96
+ rejectReporterFormatAsOutputFormat(value);
96
97
  throw usageError(`Invalid output format "${value}". Use "json" or "human".`);
97
98
  }
99
+ function rejectReporterFormatAsOutputFormat(value) {
100
+ if (value === "junit-xml" || value === "json-summary") {
101
+ throw usageError(
102
+ `Invalid output format "${value}". Use --reporter ${value} for CI reporter output.`
103
+ );
104
+ }
105
+ }
98
106
  function resolveOutputFormat(value, isTTY) {
99
107
  return parseOutputFormat(value ?? (isTTY ? "human" : "json"));
100
108
  }
@@ -118,12 +126,18 @@ function setProcessExitCode(code) {
118
126
  }
119
127
 
120
128
  // src/lib/apps.ts
129
+ function parseTheme(value) {
130
+ if (value === void 0) {
131
+ return void 0;
132
+ }
133
+ if (value === "light" || value === "dark") {
134
+ return value;
135
+ }
136
+ throw usageError(`Invalid theme "${value}". Use "light" or "dark".`);
137
+ }
121
138
  async function buildMcpWidgetContent(manager, serverId, options) {
122
139
  if (options.template && !options.template.startsWith("ui://")) {
123
- throw cliError(
124
- "VALIDATION_ERROR",
125
- "Template must use ui:// protocol"
126
- );
140
+ throw cliError("VALIDATION_ERROR", "Template must use ui:// protocol");
127
141
  }
128
142
  const resolvedResourceUri = options.template || options.resourceUri;
129
143
  const effectiveCspMode = options.cspMode ?? "permissive";
@@ -136,14 +150,14 @@ async function buildMcpWidgetContent(manager, serverId, options) {
136
150
  throw cliError("NOT_FOUND", "No content in resource");
137
151
  }
138
152
  const contentMimeType = content.mimeType;
139
- const mimeTypeValid = contentMimeType === sdk.MCP_UI_RESOURCE_MIME_TYPE;
140
- const mimeTypeWarning = !mimeTypeValid ? contentMimeType ? `Invalid mimetype "${contentMimeType}" - SEP-1865 requires "${sdk.MCP_UI_RESOURCE_MIME_TYPE}"` : `Missing mimetype - SEP-1865 requires "${sdk.MCP_UI_RESOURCE_MIME_TYPE}"` : null;
153
+ const mimeTypeValid = contentMimeType === MCP_UI_RESOURCE_MIME_TYPE;
154
+ const mimeTypeWarning = !mimeTypeValid ? contentMimeType ? `Invalid mimetype "${contentMimeType}" - SEP-1865 requires "${MCP_UI_RESOURCE_MIME_TYPE}"` : `Missing mimetype - SEP-1865 requires "${MCP_UI_RESOURCE_MIME_TYPE}"` : null;
141
155
  let html = extractHtmlFromResourceContent(content);
142
156
  if (!html) {
143
157
  throw cliError("NOT_FOUND", "No HTML content in resource");
144
158
  }
145
159
  const uiMeta = content._meta?.ui;
146
- html = sdk.injectOpenAICompat(html, {
160
+ html = injectOpenAICompat(html, {
147
161
  toolId: options.toolId,
148
162
  toolName: options.toolName,
149
163
  toolInput: options.toolInput ?? {},
@@ -178,8 +192,8 @@ async function buildChatGptWidgetContent(manager, serverId, options) {
178
192
  const resourceMeta = firstContent?._meta;
179
193
  const widgetCspRaw = resourceMeta?.["openai/widgetCSP"];
180
194
  const effectiveCspMode = options.cspMode ?? "permissive";
181
- const cspConfig = sdk.buildCspHeader(effectiveCspMode, widgetCspRaw);
182
- const runtimeHeadContent = sdk.buildChatGptRuntimeHead({
195
+ const cspConfig = buildCspHeader(effectiveCspMode, widgetCspRaw);
196
+ const runtimeHeadContent = buildChatGptRuntimeHead({
183
197
  htmlContent,
184
198
  runtimeConfig: {
185
199
  toolId: options.toolId,
@@ -197,11 +211,14 @@ async function buildChatGptWidgetContent(manager, serverId, options) {
197
211
  });
198
212
  let cspMetaTag = "";
199
213
  if (cspConfig.headerString) {
200
- const metaCspContent = sdk.buildCspMetaContent(cspConfig.headerString);
201
- cspMetaTag = `<meta http-equiv="Content-Security-Policy" content="${metaCspContent.replace(/"/g, "&quot;")}">`;
214
+ const metaCspContent = buildCspMetaContent(cspConfig.headerString);
215
+ cspMetaTag = `<meta http-equiv="Content-Security-Policy" content="${metaCspContent.replace(
216
+ /"/g,
217
+ "&quot;"
218
+ )}">`;
202
219
  }
203
220
  return {
204
- html: sdk.injectScripts(htmlContent, cspMetaTag + runtimeHeadContent),
221
+ html: injectScripts(htmlContent, cspMetaTag + runtimeHeadContent),
205
222
  csp: {
206
223
  mode: cspConfig.mode,
207
224
  connectDomains: cspConfig.connectDomains,
@@ -228,8 +245,389 @@ function extractHtmlFromResourceContent(content) {
228
245
  }
229
246
  return "";
230
247
  }
248
+
249
+ // src/lib/oauth-enums.ts
250
+ var VALID_PROTOCOL_VERSIONS = /* @__PURE__ */ new Set([
251
+ "2025-03-26",
252
+ "2025-06-18",
253
+ "2025-11-25"
254
+ ]);
255
+ var VALID_REGISTRATION_STRATEGIES = /* @__PURE__ */ new Set([
256
+ "cimd",
257
+ "dcr",
258
+ "preregistered"
259
+ ]);
260
+ var VALID_AUTH_MODES = /* @__PURE__ */ new Set([
261
+ "headless",
262
+ "interactive",
263
+ "client_credentials"
264
+ ]);
265
+
266
+ // src/lib/config-file.ts
267
+ function readConfigFile(filePath) {
268
+ let raw;
269
+ try {
270
+ raw = readFileSync(filePath, "utf-8");
271
+ } catch (error) {
272
+ throw usageError(
273
+ `Cannot read config file "${filePath}": ${error instanceof Error ? error.message : String(error)}`
274
+ );
275
+ }
276
+ let config;
277
+ try {
278
+ config = JSON.parse(raw);
279
+ } catch {
280
+ throw usageError(`Config file "${filePath}" is not valid JSON`);
281
+ }
282
+ if (typeof config !== "object" || config === null || Array.isArray(config)) {
283
+ throw usageError("Config file must be a JSON object");
284
+ }
285
+ return config;
286
+ }
287
+ function assertObject(value, label) {
288
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
289
+ throw usageError(`${label} must be a JSON object`);
290
+ }
291
+ }
292
+ function assertValidUrl(value, label) {
293
+ if (typeof value !== "string" || !value.trim()) {
294
+ throw usageError(`${label} is required and must be a non-empty string`);
295
+ }
296
+ let parsed;
297
+ try {
298
+ parsed = new URL(value);
299
+ } catch {
300
+ throw usageError(`Invalid ${label}: ${value}`);
301
+ }
302
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
303
+ throw usageError(`Invalid ${label}: ${value}`);
304
+ }
305
+ }
306
+ function assertEnum(value, allowed, label) {
307
+ if (typeof value !== "string" || !allowed.has(value)) {
308
+ throw usageError(
309
+ `Invalid ${label} "${String(value)}". Allowed: ${[...allowed].join(", ")}`
310
+ );
311
+ }
312
+ }
313
+ function validateOptionalString(value, label) {
314
+ if (value !== void 0 && typeof value !== "string") {
315
+ throw usageError(`${label} must be a string`);
316
+ }
317
+ }
318
+ function validateEnumArray(value, allowedValues, label) {
319
+ if (value === void 0) {
320
+ return;
321
+ }
322
+ if (!Array.isArray(value)) {
323
+ throw usageError(`${label} must be an array`);
324
+ }
325
+ for (let index = 0; index < value.length; index += 1) {
326
+ assertEnum(value[index], new Set(allowedValues), `${label}[${index}]`);
327
+ }
328
+ }
329
+ function validateOptionalStringArray(value, label) {
330
+ if (value === void 0) {
331
+ return;
332
+ }
333
+ if (!Array.isArray(value)) {
334
+ throw usageError(`${label} must be an array`);
335
+ }
336
+ for (let index = 0; index < value.length; index += 1) {
337
+ if (typeof value[index] !== "string") {
338
+ throw usageError(`${label}[${index}] must be a string`);
339
+ }
340
+ }
341
+ }
342
+ function validateOptionalStringRecord(value, label) {
343
+ if (value === void 0) {
344
+ return;
345
+ }
346
+ assertObject(value, label);
347
+ for (const [key, entry] of Object.entries(value)) {
348
+ if (typeof entry !== "string") {
349
+ throw usageError(`${label}.${key} must be a string`);
350
+ }
351
+ }
352
+ }
353
+ function validateProtocolRun(run, label) {
354
+ validateOptionalString(run.label, `${label}.label`);
355
+ validateEnumArray(run.categories, MCP_CHECK_CATEGORIES, `${label}.categories`);
356
+ validateEnumArray(run.checkIds, MCP_CHECK_IDS, `${label}.checkIds`);
357
+ }
358
+ function validateOAuthFlow(flow, defaults, index) {
359
+ validateOptionalString(flow.label, `flows[${index}].label`);
360
+ const protocolVersion = flow.protocolVersion ?? defaults?.protocolVersion;
361
+ if (!protocolVersion) {
362
+ throw usageError(
363
+ `flows[${index}]: protocolVersion is required (not set in flow or defaults)`
364
+ );
365
+ }
366
+ assertEnum(
367
+ protocolVersion,
368
+ VALID_PROTOCOL_VERSIONS,
369
+ `flows[${index}].protocolVersion`
370
+ );
371
+ const registrationStrategy = flow.registrationStrategy ?? defaults?.registrationStrategy;
372
+ if (!registrationStrategy) {
373
+ throw usageError(
374
+ `flows[${index}]: registrationStrategy is required (not set in flow or defaults)`
375
+ );
376
+ }
377
+ assertEnum(
378
+ registrationStrategy,
379
+ VALID_REGISTRATION_STRATEGIES,
380
+ `flows[${index}].registrationStrategy`
381
+ );
382
+ const auth = flow.auth ?? defaults?.auth;
383
+ if (auth?.mode) {
384
+ assertEnum(auth.mode, VALID_AUTH_MODES, `flows[${index}].auth.mode`);
385
+ }
386
+ }
387
+ function validateAppsTarget(value, label) {
388
+ assertObject(value, label);
389
+ const hasUrl = typeof value.url === "string" && value.url.trim().length > 0;
390
+ const hasCommand = typeof value.command === "string" && value.command.trim().length > 0;
391
+ if (hasUrl === hasCommand) {
392
+ throw usageError(
393
+ `${label} must provide exactly one of "url" or "command"`
394
+ );
395
+ }
396
+ if (hasUrl) {
397
+ assertValidUrl(value.url, `${label}.url`);
398
+ }
399
+ if (hasCommand) {
400
+ validateOptionalString(value.command, `${label}.command`);
401
+ }
402
+ validateOptionalStringArray(value.args, `${label}.args`);
403
+ validateOptionalStringRecord(value.env, `${label}.env`);
404
+ validateOptionalString(value.cwd, `${label}.cwd`);
405
+ }
406
+ function validateAppsRun(run, label) {
407
+ validateOptionalString(run.label, `${label}.label`);
408
+ validateEnumArray(run.checkIds, MCP_APPS_CHECK_IDS, `${label}.checkIds`);
409
+ }
410
+ function loadOAuthSuiteConfig(filePath) {
411
+ const config = readConfigFile(filePath);
412
+ assertValidUrl(config.serverUrl, "serverUrl");
413
+ const flows = config.flows;
414
+ if (!Array.isArray(flows) || flows.length === 0) {
415
+ throw usageError('Config file must have a non-empty "flows" array');
416
+ }
417
+ const defaults = config.defaults;
418
+ if (defaults !== void 0) {
419
+ assertObject(defaults, "defaults");
420
+ }
421
+ for (let index = 0; index < flows.length; index += 1) {
422
+ const flow = flows[index];
423
+ assertObject(flow, `flows[${index}]`);
424
+ validateOAuthFlow(flow, defaults, index);
425
+ }
426
+ return config;
427
+ }
428
+ function loadProtocolSuiteConfig(filePath) {
429
+ const config = readConfigFile(filePath);
430
+ assertValidUrl(config.serverUrl, "serverUrl");
431
+ const runs = config.runs;
432
+ if (!Array.isArray(runs) || runs.length === 0) {
433
+ throw usageError('Config file must have a non-empty "runs" array');
434
+ }
435
+ if (config.defaults !== void 0) {
436
+ assertObject(config.defaults, "defaults");
437
+ validateProtocolRun(config.defaults, "defaults");
438
+ }
439
+ for (let index = 0; index < runs.length; index += 1) {
440
+ const run = runs[index];
441
+ assertObject(run, `runs[${index}]`);
442
+ validateProtocolRun(run, `runs[${index}]`);
443
+ }
444
+ return config;
445
+ }
446
+ function loadAppsSuiteConfig(filePath) {
447
+ const config = readConfigFile(filePath);
448
+ if (config.name !== void 0) {
449
+ validateOptionalString(config.name, "name");
450
+ }
451
+ if (config.target === void 0) {
452
+ throw usageError('Config file must include a "target" object');
453
+ }
454
+ validateAppsTarget(config.target, "target");
455
+ const runs = config.runs;
456
+ if (!Array.isArray(runs) || runs.length === 0) {
457
+ throw usageError('Config file must have a non-empty "runs" array');
458
+ }
459
+ if (config.defaults !== void 0) {
460
+ assertObject(config.defaults, "defaults");
461
+ validateAppsRun(config.defaults, "defaults");
462
+ }
463
+ for (let index = 0; index < runs.length; index += 1) {
464
+ const run = runs[index];
465
+ assertObject(run, `runs[${index}]`);
466
+ validateAppsRun(run, `runs[${index}]`);
467
+ }
468
+ return config;
469
+ }
470
+ function parseConformanceOutputFormat(value) {
471
+ if (value === "json" || value === "human") {
472
+ return value;
473
+ }
474
+ rejectReporterFormatAsOutputFormat(value);
475
+ throw usageError(
476
+ `Invalid output format "${value}". Use "json" or "human".`
477
+ );
478
+ }
479
+ function resolveConformanceOutputFormat(value, isTTY) {
480
+ return parseConformanceOutputFormat(value ?? (isTTY ? "human" : "json"));
481
+ }
482
+ function resolveConformanceOutputFormatForCli(value, isTTY, reporter) {
483
+ if (reporter === void 0 || value === void 0) {
484
+ return resolveConformanceOutputFormat(value, isTTY);
485
+ }
486
+ if (value === "json" || value === "human") {
487
+ return value;
488
+ }
489
+ if (value === "junit-xml" || value === "json-summary") {
490
+ return "json";
491
+ }
492
+ throw usageError(
493
+ `Invalid output format "${value}". Use "json" or "human".`
494
+ );
495
+ }
496
+ function renderConformanceResult(result, format) {
497
+ switch (format) {
498
+ case "human":
499
+ return JSON.stringify(result, null, 2);
500
+ case "json":
501
+ return JSON.stringify(result);
502
+ }
503
+ }
504
+ function renderConformanceReporterResult(result, reporter) {
505
+ const report = toConformanceReport(result);
506
+ switch (reporter) {
507
+ case "json-summary":
508
+ return JSON.stringify(renderConformanceReportJson(report));
509
+ case "junit-xml":
510
+ return renderConformanceReportJUnitXml(report);
511
+ }
512
+ }
513
+ function renderConformanceForCli(result, reporter, format) {
514
+ return reporter ? renderConformanceReporterResult(result, reporter) : renderConformanceResult(result, format);
515
+ }
516
+ var readTextFile = (path6, encoding) => readFileSync(path6, encoding);
517
+ var JsonInputContext = class {
518
+ constructor(readFile2 = readTextFile) {
519
+ this.readFile = readFile2;
520
+ }
521
+ stdinConsumer;
522
+ readInputSource(value, label) {
523
+ if (value === "-") {
524
+ if (this.stdinConsumer) {
525
+ throw usageError(
526
+ `Cannot read ${label} from stdin because stdin was already consumed by ${this.stdinConsumer}. Use @file for one of the JSON inputs.`
527
+ );
528
+ }
529
+ try {
530
+ const contents = this.readFile(0, "utf8");
531
+ this.stdinConsumer = label;
532
+ return contents;
533
+ } catch (error) {
534
+ throw usageError(`Failed to read ${label} from stdin.`, {
535
+ source: error instanceof Error ? error.message : String(error)
536
+ });
537
+ }
538
+ }
539
+ if (!value.startsWith("@")) {
540
+ return value;
541
+ }
542
+ const filePath = value.slice(1);
543
+ if (!filePath) {
544
+ throw usageError(`${label} file path is required after @.`);
545
+ }
546
+ try {
547
+ return this.readFile(filePath, "utf8");
548
+ } catch (error) {
549
+ throw usageError(`Failed to read ${label} file "${filePath}".`, {
550
+ source: error instanceof Error ? error.message : String(error)
551
+ });
552
+ }
553
+ }
554
+ parseJsonInputValue(value, label) {
555
+ if (value === void 0) {
556
+ return void 0;
557
+ }
558
+ const source = this.readInputSource(value, label);
559
+ if (source.trim() === "") {
560
+ throw usageError(`${label} input is empty.`);
561
+ }
562
+ try {
563
+ return JSON.parse(source);
564
+ } catch (error) {
565
+ throw usageError(`${label} must be valid JSON.`, {
566
+ source: error instanceof Error ? error.message : String(error)
567
+ });
568
+ }
569
+ }
570
+ parseJsonInputRecord(value, label) {
571
+ const parsed = this.parseJsonInputValue(value, label);
572
+ if (parsed === void 0) {
573
+ return void 0;
574
+ }
575
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
576
+ throw usageError(`${label} must be a JSON object.`);
577
+ }
578
+ return parsed;
579
+ }
580
+ };
581
+ var defaultJsonInputContext = new JsonInputContext();
582
+ function readInputSource(value, label) {
583
+ return defaultJsonInputContext.readInputSource(value, label);
584
+ }
585
+ function parseJsonInputValue(value, label) {
586
+ return defaultJsonInputContext.parseJsonInputValue(value, label);
587
+ }
588
+ function parseJsonInputRecord(value, label) {
589
+ return defaultJsonInputContext.parseJsonInputRecord(value, label);
590
+ }
591
+ function parseReporterFormat(value) {
592
+ if (value === void 0) {
593
+ return void 0;
594
+ }
595
+ if (value === "json-summary" || value === "junit-xml") {
596
+ return value;
597
+ }
598
+ throw usageError(
599
+ `Invalid reporter "${value}". Use "json-summary" or "junit-xml".`
600
+ );
601
+ }
602
+ function writeReporterResult(reporter, report) {
603
+ if (reporter === "junit-xml") {
604
+ process.stdout.write(renderStructuredRunJUnitXml(report));
605
+ return;
606
+ }
607
+ writeResult(renderStructuredRunJson(report), "json");
608
+ }
609
+ async function writeJsonArtifact(outputPath, payload) {
610
+ const resolvedPath = path2.resolve(process.cwd(), outputPath);
611
+ try {
612
+ await mkdir(path2.dirname(resolvedPath), { recursive: true });
613
+ await writeFile(
614
+ resolvedPath,
615
+ `${JSON.stringify(payload, null, 2)}
616
+ `,
617
+ "utf8"
618
+ );
619
+ } catch (error) {
620
+ throw operationalError(
621
+ `Failed to write JSON artifact to "${resolvedPath}".`,
622
+ {
623
+ source: error instanceof Error ? error.message : String(error)
624
+ }
625
+ );
626
+ }
627
+ return resolvedPath;
628
+ }
231
629
  async function withEphemeralManager(config, fn, options) {
232
- return sdk.withEphemeralClient(config, fn, {
630
+ return withEphemeralClient(config, fn, {
233
631
  serverId: "__cli__",
234
632
  clientName: "mcpjam",
235
633
  timeout: options?.timeout ?? 3e4,
@@ -278,7 +676,7 @@ function getCliRpcLogEvents(collectors) {
278
676
  function redactCliRpcLogs(logs) {
279
677
  return logs.map((event) => ({
280
678
  ...event,
281
- message: sdk.redactSensitiveValue(event.message)
679
+ message: redactSensitiveValue(event.message)
282
680
  }));
283
681
  }
284
682
 
@@ -289,25 +687,241 @@ function withRpcLogsIfRequested(value, collector, options) {
289
687
  }
290
688
  return attachCliRpcLogs(value, collector);
291
689
  }
292
-
293
- // src/lib/server-config.ts
294
- var DEFAULT_CLI_RETRY_POLICY = {
295
- retries: 0,
296
- retryDelayMs: 3e3
297
- };
298
- function collectString(value, previous = []) {
299
- return [...previous, value];
300
- }
301
- function addSharedServerOptions(command) {
302
- return command.option(
303
- "--transport <transport>",
304
- 'Explicit transport type: "http" or "stdio"'
305
- ).option("--url <url>", "HTTP MCP server URL").option("--access-token <token>", "Bearer access token for HTTP servers").option(
306
- "--oauth-access-token <token>",
690
+ var CREDENTIALS_FILE_VERSION = 1;
691
+ var ACCESS_TOKEN_EXPIRY_SKEW_MS = 6e4;
692
+ async function writeCredentialsFile(outputPath, result, now = /* @__PURE__ */ new Date()) {
693
+ const resolvedPath = path2.resolve(process.cwd(), outputPath);
694
+ const contents = validateCredentialsFileContents(
695
+ { ...buildCredentialsFileContents(result, now) },
696
+ resolvedPath
697
+ );
698
+ const outputDirectory = path2.dirname(resolvedPath);
699
+ const temporaryPath = path2.join(
700
+ outputDirectory,
701
+ `.${path2.basename(resolvedPath)}.${randomUUID()}.tmp`
702
+ );
703
+ try {
704
+ await mkdir(outputDirectory, { recursive: true });
705
+ await writeFile(
706
+ temporaryPath,
707
+ `${JSON.stringify(contents, null, 2)}
708
+ `,
709
+ {
710
+ encoding: "utf8",
711
+ mode: 384
712
+ }
713
+ );
714
+ await chmod(temporaryPath, 384);
715
+ await rename(temporaryPath, resolvedPath);
716
+ } catch (error) {
717
+ await rm(temporaryPath, { force: true }).catch(() => void 0);
718
+ throw operationalError(
719
+ `Failed to write credentials file to "${resolvedPath}".`,
720
+ {
721
+ source: error instanceof Error ? error.message : String(error)
722
+ }
723
+ );
724
+ }
725
+ return resolvedPath;
726
+ }
727
+ function readCredentialsFile(filePath) {
728
+ let raw;
729
+ try {
730
+ raw = readFileSync(filePath, "utf8");
731
+ } catch (error) {
732
+ throw usageError(
733
+ `Cannot read credentials file "${filePath}": ${error instanceof Error ? error.message : String(error)}`
734
+ );
735
+ }
736
+ let parsed;
737
+ try {
738
+ parsed = JSON.parse(raw);
739
+ } catch {
740
+ throw usageError(`Credentials file "${filePath}" is not valid JSON`);
741
+ }
742
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
743
+ throw usageError("Credentials file must be a JSON object");
744
+ }
745
+ return validateCredentialsFileContents(
746
+ parsed,
747
+ filePath
748
+ );
749
+ }
750
+ function resolveCredentialsFileAuth(filePath, serverUrl, now = /* @__PURE__ */ new Date()) {
751
+ const contents = readCredentialsFile(filePath);
752
+ assertMatchingServerUrl(contents.serverUrl, serverUrl, filePath);
753
+ if (contents.accessToken && isAccessTokenUsable(contents, now)) {
754
+ return { accessToken: contents.accessToken };
755
+ }
756
+ if (contents.refreshToken && contents.clientId) {
757
+ return {
758
+ refreshToken: contents.refreshToken,
759
+ clientId: contents.clientId,
760
+ ...contents.clientSecret ? { clientSecret: contents.clientSecret } : {}
761
+ };
762
+ }
763
+ if (contents.accessToken) {
764
+ throw usageError(
765
+ `Credentials file "${filePath}" has an expired access token and no refresh token credentials.`
766
+ );
767
+ }
768
+ throw usageError(`Credentials file "${filePath}" does not contain usable OAuth credentials.`);
769
+ }
770
+ function resolveCredentialsFileAccessToken(filePath, serverUrl, now = /* @__PURE__ */ new Date()) {
771
+ const contents = readCredentialsFile(filePath);
772
+ assertMatchingServerUrl(contents.serverUrl, serverUrl, filePath);
773
+ if (contents.accessToken && isAccessTokenUsable(contents, now)) {
774
+ return contents.accessToken;
775
+ }
776
+ throw usageError(
777
+ `Credentials file "${filePath}" does not contain a non-expired access token for this command.`
778
+ );
779
+ }
780
+ function assertNoCredentialsFileAuthConflicts(options) {
781
+ if (!options.credentialsFile || !(options.accessToken?.trim() || options.oauthAccessToken?.trim() || options.refreshToken?.trim() || options.clientId?.trim() || options.clientSecret?.trim())) {
782
+ return;
783
+ }
784
+ throw usageError(
785
+ "--credentials-file cannot be used together with --access-token, --oauth-access-token, --refresh-token, --client-id, or --client-secret."
786
+ );
787
+ }
788
+ function redactCredentialsFromResult(result, credentialsFilePath) {
789
+ const redacted = redactSensitiveValue(result);
790
+ const credentials = result.credentials;
791
+ const secretMarker = credentialsFilePath ? "[SAVED_TO_FILE]" : "[REDACTED]";
792
+ const redactedCredentials = {
793
+ ...redacted.credentials ?? {},
794
+ ...credentials.clientId ? { clientId: credentials.clientId } : {},
795
+ ...credentials.tokenType ? { tokenType: credentials.tokenType } : {},
796
+ ...credentials.expiresIn !== void 0 ? { expiresIn: credentials.expiresIn } : {},
797
+ ...credentials.accessToken ? { accessToken: secretMarker } : {},
798
+ ...credentials.refreshToken ? { refreshToken: secretMarker } : {},
799
+ ...credentials.clientSecret ? { clientSecret: secretMarker } : {}
800
+ };
801
+ return {
802
+ ...redacted,
803
+ credentials: redactedCredentials,
804
+ ...credentialsFilePath ? { credentialsFile: credentialsFilePath } : {}
805
+ };
806
+ }
807
+ function hasCredentialsToSave(result) {
808
+ return Boolean(result.credentials.accessToken || result.credentials.refreshToken);
809
+ }
810
+ function buildCredentialsFileContents(result, now) {
811
+ if (!hasCredentialsToSave(result)) {
812
+ throw usageError("OAuth login did not return usable credentials to save.");
813
+ }
814
+ const expiresAt = typeof result.credentials.expiresIn === "number" && Number.isFinite(result.credentials.expiresIn) ? new Date(now.getTime() + result.credentials.expiresIn * 1e3).toISOString() : void 0;
815
+ return {
816
+ version: CREDENTIALS_FILE_VERSION,
817
+ serverUrl: result.serverUrl,
818
+ ...result.credentials.accessToken ? { accessToken: result.credentials.accessToken } : {},
819
+ ...result.credentials.refreshToken ? { refreshToken: result.credentials.refreshToken } : {},
820
+ ...result.credentials.clientId ? { clientId: result.credentials.clientId } : {},
821
+ ...result.credentials.clientSecret ? { clientSecret: result.credentials.clientSecret } : {},
822
+ ...result.credentials.tokenType ? { tokenType: result.credentials.tokenType } : {},
823
+ ...expiresAt ? { expiresAt } : {},
824
+ ...result.protocolVersion ? { protocolVersion: result.protocolVersion } : {}
825
+ };
826
+ }
827
+ function validateCredentialsFileContents(value, filePath) {
828
+ if (value.version !== CREDENTIALS_FILE_VERSION) {
829
+ throw usageError(
830
+ `Unsupported credentials file version "${String(value.version)}".`
831
+ );
832
+ }
833
+ const contents = {
834
+ version: CREDENTIALS_FILE_VERSION,
835
+ serverUrl: requireString(value.serverUrl, "serverUrl"),
836
+ ...optionalStringField(value, "accessToken"),
837
+ ...optionalStringField(value, "refreshToken"),
838
+ ...optionalStringField(value, "clientId"),
839
+ ...optionalStringField(value, "clientSecret"),
840
+ ...optionalStringField(value, "tokenType"),
841
+ ...optionalStringField(value, "expiresAt"),
842
+ ...optionalStringField(value, "protocolVersion")
843
+ };
844
+ normalizeUrl(contents.serverUrl, "serverUrl");
845
+ if (!contents.accessToken && !contents.refreshToken) {
846
+ throw usageError(`Credentials file "${filePath}" does not contain OAuth tokens.`);
847
+ }
848
+ if (contents.refreshToken && !contents.clientId) {
849
+ throw usageError(
850
+ `Credentials file "${filePath}" with refreshToken requires clientId.`
851
+ );
852
+ }
853
+ if (contents.expiresAt) {
854
+ assertValidDate(contents.expiresAt, "expiresAt");
855
+ }
856
+ return contents;
857
+ }
858
+ function optionalStringField(value, key) {
859
+ const entry = value[key];
860
+ if (entry === void 0) {
861
+ return {};
862
+ }
863
+ return { [key]: requireString(entry, key) };
864
+ }
865
+ function requireString(value, label) {
866
+ if (typeof value !== "string" || !value.trim()) {
867
+ throw usageError(`${label} must be a non-empty string.`);
868
+ }
869
+ return value.trim();
870
+ }
871
+ function assertValidDate(value, label) {
872
+ if (Number.isNaN(Date.parse(value))) {
873
+ throw usageError(`${label} must be a valid ISO timestamp.`);
874
+ }
875
+ }
876
+ function assertMatchingServerUrl(credentialsServerUrl, serverUrl, filePath) {
877
+ if (normalizeUrl(credentialsServerUrl, "credentials file serverUrl") === normalizeUrl(serverUrl, "server URL")) {
878
+ return;
879
+ }
880
+ throw usageError(
881
+ `Credentials file "${filePath}" was issued for ${credentialsServerUrl}, not ${serverUrl}.`
882
+ );
883
+ }
884
+ function normalizeUrl(value, label) {
885
+ let parsed;
886
+ try {
887
+ parsed = new URL(value);
888
+ } catch {
889
+ throw usageError(`Invalid ${label}: ${value}`);
890
+ }
891
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
892
+ throw usageError(`${label} must use http or https: ${value}`);
893
+ }
894
+ const normalizedPathname = parsed.pathname.replace(/\/+$/u, "") || "/";
895
+ return `${parsed.origin}${normalizedPathname}${parsed.search}`;
896
+ }
897
+ function isAccessTokenUsable(contents, now) {
898
+ if (!contents.expiresAt) {
899
+ return true;
900
+ }
901
+ return Date.parse(contents.expiresAt) - now.getTime() > ACCESS_TOKEN_EXPIRY_SKEW_MS;
902
+ }
903
+
904
+ // src/lib/server-config.ts
905
+ var DEFAULT_CLI_RETRY_POLICY = {
906
+ retries: 0,
907
+ retryDelayMs: 3e3
908
+ };
909
+ function collectString(value, previous = []) {
910
+ return [...previous, value];
911
+ }
912
+ function addSharedServerOptions(command) {
913
+ return command.option(
914
+ "--transport <transport>",
915
+ 'Explicit transport type: "http" or "stdio"'
916
+ ).option("--url <url>", "HTTP MCP server URL").option("--access-token <token>", "Bearer access token for HTTP servers").option(
917
+ "--oauth-access-token <token>",
307
918
  "OAuth bearer access token for HTTP servers"
308
919
  ).option("--refresh-token <token>", "OAuth refresh token for HTTP servers").option("--client-id <id>", "OAuth client ID used with --refresh-token").option(
309
920
  "--client-secret <secret>",
310
921
  "OAuth client secret used with --refresh-token"
922
+ ).option(
923
+ "--credentials-file <path>",
924
+ "Load OAuth credentials from a file created by oauth login --credentials-out"
311
925
  ).option(
312
926
  "--header <header>",
313
927
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
@@ -315,7 +929,7 @@ function addSharedServerOptions(command) {
315
929
  []
316
930
  ).option(
317
931
  "--client-capabilities <json>",
318
- "Client capabilities advertised to the server as a JSON object"
932
+ "Client capabilities as JSON, @path, or - for stdin"
319
933
  ).option("--command <command>", "Command for a stdio MCP server").option(
320
934
  "--args <arg...>",
321
935
  "Preferred stdio command arguments. Pass multiple values or repeat the flag."
@@ -336,7 +950,9 @@ function getGlobalOptions(command) {
336
950
  process.stdout.isTTY
337
951
  ),
338
952
  timeout: options.timeout ?? 3e4,
339
- rpc: options.rpc ?? false
953
+ rpc: options.rpc ?? false,
954
+ quiet: options.quiet ?? false,
955
+ telemetry: options.telemetry ?? true
340
956
  };
341
957
  }
342
958
  function parsePositiveInteger(value, label = "Value") {
@@ -384,21 +1000,7 @@ function parseHeadersOption(headers) {
384
1000
  return Object.fromEntries(headers.map(parseHeader));
385
1001
  }
386
1002
  function parseJsonRecord(value, label) {
387
- if (value === void 0) {
388
- return void 0;
389
- }
390
- let parsed;
391
- try {
392
- parsed = JSON.parse(value);
393
- } catch (error) {
394
- throw usageError(`${label} must be valid JSON.`, {
395
- source: error instanceof Error ? error.message : String(error)
396
- });
397
- }
398
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
399
- throw usageError(`${label} must be a JSON object.`);
400
- }
401
- return parsed;
1003
+ return parseJsonInputRecord(value, label);
402
1004
  }
403
1005
  function parseUnknownRecord(value, label) {
404
1006
  if (value === void 0) {
@@ -470,10 +1072,12 @@ function parseServerConfig(options) {
470
1072
  throw usageError(`Invalid URL: ${url}`);
471
1073
  }
472
1074
  const headers = parseHeadersOption(options.header);
473
- const accessToken = resolveHttpAccessToken(options);
474
- const refreshToken = options.refreshToken?.trim();
475
- const clientId = options.clientId?.trim();
476
- const clientSecret = options.clientSecret?.trim();
1075
+ assertNoCredentialsFileAuthConflicts(options);
1076
+ const fileCredentials = options.credentialsFile ? resolveCredentialsFileAuth(options.credentialsFile, url) : void 0;
1077
+ const accessToken = resolveHttpAccessToken(options) ?? fileCredentials?.accessToken;
1078
+ const refreshToken = normalizeOptionalAuthValue(options.refreshToken) ?? fileCredentials?.refreshToken;
1079
+ const clientId = normalizeOptionalAuthValue(options.clientId) ?? fileCredentials?.clientId;
1080
+ const clientSecret = normalizeOptionalAuthValue(options.clientSecret) ?? fileCredentials?.clientSecret;
477
1081
  if (refreshToken && accessToken) {
478
1082
  throw usageError(
479
1083
  "--refresh-token cannot be used together with --access-token or --oauth-access-token."
@@ -501,9 +1105,9 @@ function parseServerConfig(options) {
501
1105
  if (!command) {
502
1106
  throw usageError("Missing stdio command.");
503
1107
  }
504
- if (options.accessToken || options.oauthAccessToken || options.refreshToken || options.clientId || options.clientSecret || (options.header?.length ?? 0) > 0) {
1108
+ if (options.accessToken || options.oauthAccessToken || options.refreshToken || options.clientId || options.clientSecret || options.credentialsFile || (options.header?.length ?? 0) > 0) {
505
1109
  throw usageError(
506
- "--access-token, --oauth-access-token, --refresh-token, --client-id, --client-secret, and --header can only be used together with --url."
1110
+ "--access-token, --oauth-access-token, --refresh-token, --client-id, --client-secret, --credentials-file, and --header can only be used together with --url."
507
1111
  );
508
1112
  }
509
1113
  return {
@@ -522,7 +1126,7 @@ function addGlobalOptions(program) {
522
1126
  "Request timeout in milliseconds",
523
1127
  (value) => parsePositiveInteger(value, "Timeout"),
524
1128
  3e4
525
- ).option("--rpc", "Include RPC logs in JSON 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");
526
1130
  }
527
1131
  function describeTarget(options) {
528
1132
  return options.url?.trim() || options.command?.trim() || "__cli__";
@@ -617,8 +1221,8 @@ function resolveTransportOption(value) {
617
1221
  );
618
1222
  }
619
1223
  function resolveHttpAccessToken(options) {
620
- const accessToken = options.accessToken?.trim();
621
- const oauthAccessToken = options.oauthAccessToken?.trim();
1224
+ const accessToken = normalizeOptionalAuthValue(options.accessToken);
1225
+ const oauthAccessToken = normalizeOptionalAuthValue(options.oauthAccessToken);
622
1226
  if (accessToken && oauthAccessToken && accessToken !== oauthAccessToken) {
623
1227
  throw usageError(
624
1228
  "--access-token and --oauth-access-token must match when both are provided."
@@ -626,140 +1230,941 @@ function resolveHttpAccessToken(options) {
626
1230
  }
627
1231
  return accessToken ?? oauthAccessToken;
628
1232
  }
629
-
630
- // src/commands/apps.ts
631
- var APPS_CHECK_IDS_BY_CATEGORY = {
632
- tools: [
633
- "ui-tools-present",
634
- "ui-tool-metadata-valid",
635
- "ui-tool-input-schema-valid"
636
- ],
637
- resources: [
638
- "ui-listed-resources-valid",
639
- "ui-resources-readable",
640
- "ui-resource-contents-valid",
641
- "ui-resource-meta-valid"
642
- ]
643
- };
644
- function registerAppsCommands(program) {
645
- const apps = program.command("apps").description(
646
- "MCP Apps utilities, widget extraction, and conformance checks"
647
- );
648
- addSharedServerOptions(
649
- apps.command("conformance").description("Run MCP Apps server conformance checks").option(
650
- "--category <category>",
651
- "Check category to run. Repeat for multiple. Default: all.",
652
- (value, previous = []) => [...previous, value],
653
- []
654
- ).option(
655
- "--check-id <id>",
656
- "Specific check ID to run. Repeat for multiple. Default: all.",
657
- (value, previous = []) => [...previous, value],
658
- []
659
- )
660
- ).action(async (options, command) => {
661
- const globalOptions = getGlobalOptions(command);
662
- const target = describeTarget(options);
663
- const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
664
- const config = {
665
- ...buildAppsConformanceConfig({
666
- ...options,
667
- timeout: globalOptions.timeout
668
- }),
669
- ...collector ? { rpcLogger: collector.rpcLogger } : {}
670
- };
671
- const result = await new sdk.MCPAppsConformanceTest(config).run();
672
- writeResult(
673
- withRpcLogsIfRequested(result, collector, globalOptions),
674
- globalOptions.format
1233
+ function normalizeOptionalAuthValue(value) {
1234
+ const trimmed = value?.trim();
1235
+ return trimmed ? trimmed : void 0;
1236
+ }
1237
+ var FALLBACK_INSPECTOR_BASE_URL = "http://127.0.0.1:6274";
1238
+ var DEFAULT_START_TIMEOUT_MS = 3e4;
1239
+ var DEFAULT_COMMAND_TIMEOUT_MS = 3e4;
1240
+ var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
1241
+ var COMMAND_FETCH_TIMEOUT_BUFFER_MS = 2e3;
1242
+ var HEALTH_FETCH_TIMEOUT_MS = 2e3;
1243
+ var SESSION_TOKEN_TIMEOUT_MS = 3e3;
1244
+ var STOP_FETCH_TIMEOUT_MS = 3e3;
1245
+ var STARTUP_LOG_MAX_BYTES = 1024 * 1024;
1246
+ var TOKEN_TTL_MS = 5 * 6e4;
1247
+ var tokenCache = /* @__PURE__ */ new Map();
1248
+ var tokenRequests = /* @__PURE__ */ new Map();
1249
+ function normalizeInspectorBaseUrl(baseUrl) {
1250
+ const value = baseUrl?.trim() || process.env.MCPJAM_INSPECTOR_URL?.trim() || FALLBACK_INSPECTOR_BASE_URL;
1251
+ try {
1252
+ const parsed = new URL(value);
1253
+ parsed.hash = "";
1254
+ parsed.search = "";
1255
+ return parsed.href.replace(/\/$/, "");
1256
+ } catch (error) {
1257
+ throw operationalError(
1258
+ `Invalid Inspector URL "${value}".`,
1259
+ error instanceof Error ? error.message : String(error)
675
1260
  );
676
- if (!result.passed) {
677
- setProcessExitCode(1);
1261
+ }
1262
+ }
1263
+ function buildInspectorUrl(baseUrl, tab) {
1264
+ if (!tab || !tab.trim()) {
1265
+ return baseUrl;
1266
+ }
1267
+ return `${baseUrl}/#${tab.trim()}`;
1268
+ }
1269
+ async function ensureInspector(options = {}) {
1270
+ const baseUrl = normalizeInspectorBaseUrl(options.baseUrl);
1271
+ const health = await getInspectorHealth(baseUrl);
1272
+ if (health.healthy) {
1273
+ if (options.openBrowser && !health.hasActiveClient) {
1274
+ openUrl(buildInspectorUrl(baseUrl, options.tab));
678
1275
  }
679
- });
680
- addRetryOptions(
681
- addSharedServerOptions(
682
- apps.command("mcp-widget").description("Fetch hosted-style MCP App widget content").option("--resource-uri <uri>", "Widget resource URI").option("--uri <uri>", "Alias for --resource-uri").requiredOption(
683
- "--tool-id <id>",
684
- "Tool call id used for runtime injection"
685
- ).requiredOption(
686
- "--tool-name <name>",
687
- "Tool name used for runtime injection"
688
- ).option("--tool-input <json>", "Tool input payload as JSON").option("--tool-output <json>", "Tool output payload as JSON").option("--theme <theme>", "Widget theme: light or dark").option("--csp-mode <mode>", "CSP mode: permissive or widget-declared").option("--template <uri>", "Optional ui:// template override").option("--view-mode <mode>", "Widget view mode").option("--view-params <json>", "Widget view params as JSON")
689
- )
690
- ).action(async (options, command) => {
691
- const globalOptions = getGlobalOptions(command);
692
- const retryPolicy = parseRetryPolicy(options);
693
- const target = describeTarget(options);
694
- const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
695
- const resourceUri = resolveAliasedStringOption(
696
- options,
697
- [
698
- { key: "resourceUri", flag: "--resource-uri" },
699
- { key: "uri", flag: "--uri" }
700
- ],
701
- "Widget resource URI",
702
- { required: true }
1276
+ return { baseUrl, started: false };
1277
+ }
1278
+ if (!options.startIfNeeded) {
1279
+ throw operationalError(
1280
+ "Inspector is not running. Run `mcpjam inspector open` first or pass an Inspector-backed option that starts it."
703
1281
  );
704
- const config = parseServerConfig({
705
- ...options,
706
- timeout: globalOptions.timeout
1282
+ }
1283
+ await startInspector(baseUrl, options.timeoutMs ?? DEFAULT_START_TIMEOUT_MS);
1284
+ clearInspectorSessionTokenCache(baseUrl);
1285
+ if (options.openBrowser) {
1286
+ openUrl(buildInspectorUrl(baseUrl, options.tab));
1287
+ }
1288
+ return { baseUrl, started: true };
1289
+ }
1290
+ async function stopInspector(baseUrl) {
1291
+ const normalized = normalizeInspectorBaseUrl(baseUrl);
1292
+ if (!await isInspectorHealthy(normalized)) {
1293
+ return { stopped: false, baseUrl: normalized };
1294
+ }
1295
+ const fetchShutdown = async () => {
1296
+ const token = await fetchInspectorSessionToken(normalized);
1297
+ return await fetch(`${normalized}/api/shutdown`, {
1298
+ method: "POST",
1299
+ headers: {
1300
+ "X-MCP-Session-Auth": `Bearer ${token}`
1301
+ },
1302
+ signal: AbortSignal.timeout(STOP_FETCH_TIMEOUT_MS)
707
1303
  });
708
- const result = await withEphemeralManager(
709
- config,
710
- (manager, serverId) => buildMcpWidgetContent(manager, serverId, {
711
- resourceUri,
712
- toolId: options.toolId,
713
- toolName: options.toolName,
714
- toolInput: parseJsonRecord(options.toolInput, "Tool input") ?? {},
715
- toolOutput: parseJsonValue(options.toolOutput),
716
- theme: parseTheme(options.theme),
717
- cspMode: parseCspMode(options.cspMode),
718
- template: options.template,
719
- viewMode: options.viewMode,
720
- viewParams: parseJsonRecord(options.viewParams, "View params")
721
- }),
722
- {
723
- timeout: globalOptions.timeout,
724
- rpcLogger: collector?.rpcLogger,
725
- retryPolicy
726
- }
1304
+ };
1305
+ try {
1306
+ let response = await fetchShutdown();
1307
+ if (isAuthFailure(response)) {
1308
+ clearInspectorSessionTokenCache(normalized);
1309
+ response = await fetchShutdown();
1310
+ }
1311
+ if (response.ok) {
1312
+ clearInspectorSessionTokenCache(normalized);
1313
+ }
1314
+ return { stopped: response.ok, baseUrl: normalized };
1315
+ } catch {
1316
+ return { stopped: false, baseUrl: normalized };
1317
+ }
1318
+ }
1319
+ var InspectorApiClient = class {
1320
+ baseUrl;
1321
+ constructor(options = {}) {
1322
+ this.baseUrl = normalizeInspectorBaseUrl(options.baseUrl);
1323
+ }
1324
+ async ensure(options = {}) {
1325
+ return ensureInspector({ ...options, baseUrl: this.baseUrl });
1326
+ }
1327
+ async connectServer(serverId, serverConfig) {
1328
+ return this.request("/api/mcp/connect", {
1329
+ method: "POST",
1330
+ body: { serverId, serverConfig }
1331
+ });
1332
+ }
1333
+ async listServers() {
1334
+ return this.request("/api/mcp/servers");
1335
+ }
1336
+ async getServerStatus(serverId) {
1337
+ return this.request(
1338
+ `/api/mcp/servers/status/${encodeURIComponent(serverId)}`
727
1339
  );
728
- writeResult(
729
- withRpcLogsIfRequested(result, collector, globalOptions),
730
- globalOptions.format
1340
+ }
1341
+ async getInitInfo(serverId) {
1342
+ return this.request(
1343
+ `/api/mcp/servers/init-info/${encodeURIComponent(serverId)}`
731
1344
  );
732
- });
733
- addRetryOptions(
734
- addSharedServerOptions(
735
- apps.command("chatgpt-widget").description("Fetch hosted-style ChatGPT App widget content").option("--resource-uri <uri>", "Widget resource URI").option("--uri <uri>", "Alias for --resource-uri").requiredOption(
736
- "--tool-id <id>",
737
- "Tool call id used for runtime injection"
738
- ).requiredOption(
739
- "--tool-name <name>",
740
- "Tool name used for runtime injection"
741
- ).option("--tool-input <json>", "Tool input payload as JSON").option("--tool-output <json>", "Tool output payload as JSON").option(
742
- "--tool-response-metadata <json>",
743
- "Tool response metadata as a JSON object"
744
- ).option("--theme <theme>", "Widget theme: light or dark").option("--csp-mode <mode>", "CSP mode: permissive or widget-declared").option("--locale <locale>", "Locale override").option(
745
- "--device-type <type>",
746
- "Device type: mobile, tablet, or desktop"
747
- )
748
- )
749
- ).action(async (options, command) => {
750
- const globalOptions = getGlobalOptions(command);
751
- const retryPolicy = parseRetryPolicy(options);
752
- const target = describeTarget(options);
753
- const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
754
- const resourceUri = resolveAliasedStringOption(
755
- options,
756
- [
757
- { key: "resourceUri", flag: "--resource-uri" },
758
- { key: "uri", flag: "--uri" }
759
- ],
760
- "Widget resource URI",
761
- { required: true }
1345
+ }
1346
+ async listTools(serverId, options = {}) {
1347
+ return this.request("/api/mcp/tools/list", {
1348
+ method: "POST",
1349
+ body: { serverId, ...options }
1350
+ });
1351
+ }
1352
+ async executeTool(serverId, toolName, parameters = {}) {
1353
+ return this.request("/api/mcp/tools/execute", {
1354
+ method: "POST",
1355
+ body: { serverId, toolName, parameters }
1356
+ });
1357
+ }
1358
+ async respondToElicitation(executionId, requestId, response) {
1359
+ return this.request("/api/mcp/tools/respond", {
1360
+ method: "POST",
1361
+ body: { executionId, requestId, response }
1362
+ });
1363
+ }
1364
+ async executeCommand(request) {
1365
+ const commandTimeoutMs = typeof request.timeoutMs === "number" && request.timeoutMs > 0 ? request.timeoutMs : DEFAULT_COMMAND_TIMEOUT_MS;
1366
+ const fetchCommand = async () => {
1367
+ const token = await fetchInspectorSessionToken(this.baseUrl);
1368
+ return await fetch(`${this.baseUrl}/api/mcp/command`, {
1369
+ method: "POST",
1370
+ headers: {
1371
+ "Content-Type": "application/json",
1372
+ "X-MCP-Session-Auth": `Bearer ${token}`
1373
+ },
1374
+ body: JSON.stringify(request),
1375
+ signal: AbortSignal.timeout(
1376
+ commandTimeoutMs + COMMAND_FETCH_TIMEOUT_BUFFER_MS
1377
+ )
1378
+ });
1379
+ };
1380
+ let response;
1381
+ try {
1382
+ response = await fetchCommand();
1383
+ if (isAuthFailure(response)) {
1384
+ clearInspectorSessionTokenCache(this.baseUrl);
1385
+ response = await fetchCommand();
1386
+ }
1387
+ } catch (error) {
1388
+ throw operationalError(
1389
+ `Failed to contact Inspector at ${this.baseUrl}.`,
1390
+ error instanceof Error ? error.message : String(error)
1391
+ );
1392
+ }
1393
+ if (isAuthFailure(response)) {
1394
+ throw operationalError(
1395
+ `Inspector command request failed authentication with ${response.status}.`
1396
+ );
1397
+ }
1398
+ const payload = await readResponsePayload(response);
1399
+ if (isInspectorCommandResponse(payload)) {
1400
+ return payload;
1401
+ }
1402
+ if (!response.ok) {
1403
+ throw operationalError(
1404
+ getErrorMessage(payload) ?? `Inspector command request failed with ${response.status}.`,
1405
+ payload
1406
+ );
1407
+ }
1408
+ throw operationalError("Inspector command response was invalid.", payload);
1409
+ }
1410
+ async request(path6, init = {}) {
1411
+ const fetchRequest = async () => {
1412
+ const token = await fetchInspectorSessionToken(this.baseUrl);
1413
+ const { body: initBody, timeoutMs, ...fetchInit } = init;
1414
+ const headers = new Headers(fetchInit.headers);
1415
+ headers.set("X-MCP-Session-Auth", `Bearer ${token}`);
1416
+ let body;
1417
+ if (initBody !== void 0) {
1418
+ headers.set("Content-Type", "application/json");
1419
+ body = JSON.stringify(initBody);
1420
+ }
1421
+ return await fetch(`${this.baseUrl}${path6}`, {
1422
+ ...fetchInit,
1423
+ signal: fetchInit.signal ?? AbortSignal.timeout(timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS),
1424
+ headers,
1425
+ body
1426
+ });
1427
+ };
1428
+ let response;
1429
+ try {
1430
+ response = await fetchRequest();
1431
+ if (isAuthFailure(response)) {
1432
+ clearInspectorSessionTokenCache(this.baseUrl);
1433
+ response = await fetchRequest();
1434
+ }
1435
+ } catch (error) {
1436
+ throw operationalError(
1437
+ `Failed to contact Inspector at ${this.baseUrl}.`,
1438
+ error instanceof Error ? error.message : String(error)
1439
+ );
1440
+ }
1441
+ const payload = await readResponsePayload(response);
1442
+ if (!response.ok) {
1443
+ throw operationalError(
1444
+ getErrorMessage(payload) ?? `Inspector request ${path6} failed with ${response.status}.`,
1445
+ payload
1446
+ );
1447
+ }
1448
+ return payload;
1449
+ }
1450
+ };
1451
+ async function fetchInspectorSessionToken(baseUrl) {
1452
+ const normalizedBaseUrl = normalizeInspectorBaseUrl(baseUrl);
1453
+ const cached = tokenCache.get(normalizedBaseUrl);
1454
+ if (cached && Date.now() - cached.fetchedAt < TOKEN_TTL_MS) {
1455
+ return cached.token;
1456
+ }
1457
+ const pending = tokenRequests.get(normalizedBaseUrl);
1458
+ if (pending) {
1459
+ return pending;
1460
+ }
1461
+ const request = fetchFreshInspectorSessionToken(normalizedBaseUrl).finally(
1462
+ () => {
1463
+ tokenRequests.delete(normalizedBaseUrl);
1464
+ }
1465
+ );
1466
+ tokenRequests.set(normalizedBaseUrl, request);
1467
+ return request;
1468
+ }
1469
+ function clearInspectorSessionTokenCache(baseUrl) {
1470
+ if (!baseUrl) {
1471
+ tokenCache.clear();
1472
+ tokenRequests.clear();
1473
+ return;
1474
+ }
1475
+ const normalizedBaseUrl = normalizeInspectorBaseUrl(baseUrl);
1476
+ tokenCache.delete(normalizedBaseUrl);
1477
+ tokenRequests.delete(normalizedBaseUrl);
1478
+ }
1479
+ async function fetchFreshInspectorSessionToken(normalizedBaseUrl) {
1480
+ let response;
1481
+ try {
1482
+ response = await fetch(`${normalizedBaseUrl}/api/session-token`, {
1483
+ signal: AbortSignal.timeout(SESSION_TOKEN_TIMEOUT_MS)
1484
+ });
1485
+ } catch (error) {
1486
+ throw operationalError(
1487
+ "Failed to contact the local Inspector session-token endpoint.",
1488
+ error instanceof Error ? error.message : String(error)
1489
+ );
1490
+ }
1491
+ if (!response.ok) {
1492
+ throw operationalError(
1493
+ `Inspector session-token request failed with ${response.status}.`
762
1494
  );
1495
+ }
1496
+ const body = await response.json();
1497
+ if (typeof body.token !== "string" || !body.token) {
1498
+ throw operationalError("Inspector session-token response was invalid.");
1499
+ }
1500
+ tokenCache.set(normalizedBaseUrl, {
1501
+ token: body.token,
1502
+ fetchedAt: Date.now()
1503
+ });
1504
+ return body.token;
1505
+ }
1506
+ function getInspectorStartScriptPath() {
1507
+ return fileURLToPath(
1508
+ new URL("../../../mcpjam-inspector/bin/start.js", import.meta.url)
1509
+ );
1510
+ }
1511
+ async function getInspectorHealth(baseUrl, timeoutMs = HEALTH_FETCH_TIMEOUT_MS) {
1512
+ try {
1513
+ const response = await fetch(`${baseUrl}/health`, {
1514
+ signal: AbortSignal.timeout(timeoutMs)
1515
+ });
1516
+ if (!response.ok) {
1517
+ return { healthy: false, hasActiveClient: false };
1518
+ }
1519
+ const body = await response.json();
1520
+ return {
1521
+ healthy: true,
1522
+ hasActiveClient: body.hasActiveClient === true
1523
+ };
1524
+ } catch {
1525
+ return { healthy: false, hasActiveClient: false };
1526
+ }
1527
+ }
1528
+ async function isInspectorHealthy(baseUrl) {
1529
+ const status = await getInspectorHealth(baseUrl);
1530
+ return status.healthy;
1531
+ }
1532
+ function getNpxExecutable(platform = process.platform) {
1533
+ return platform === "win32" ? "npx.cmd" : "npx";
1534
+ }
1535
+ async function startInspector(baseUrl, timeoutMs) {
1536
+ const parsedUrl = new URL(baseUrl);
1537
+ const port = parsedUrl.port || "6274";
1538
+ const startScriptPath = getInspectorStartScriptPath();
1539
+ const hasStartScript = existsSync(startScriptPath);
1540
+ const args = hasStartScript ? [startScriptPath, "--port", port] : ["-y", "@mcpjam/inspector@latest", "--port", port];
1541
+ const executable = hasStartScript ? process.execPath : getNpxExecutable();
1542
+ const logPath = getInspectorStartupLogPath();
1543
+ const logFd = openStartupLogFile(logPath);
1544
+ let child;
1545
+ try {
1546
+ child = spawn(executable, args, {
1547
+ cwd: hasStartScript ? path2.dirname(startScriptPath) : process.cwd(),
1548
+ detached: true,
1549
+ stdio: ["ignore", logFd, logFd],
1550
+ env: {
1551
+ ...process.env,
1552
+ HOST: parsedUrl.hostname
1553
+ }
1554
+ });
1555
+ } finally {
1556
+ closeSync(logFd);
1557
+ }
1558
+ child.unref();
1559
+ const startedAt = Date.now();
1560
+ while (Date.now() - startedAt < timeoutMs) {
1561
+ if (await isInspectorHealthy(baseUrl)) {
1562
+ return;
1563
+ }
1564
+ await delay(250);
1565
+ }
1566
+ throw operationalError(
1567
+ `Inspector did not become ready within ${timeoutMs}ms. Startup log: ${logPath}`
1568
+ );
1569
+ }
1570
+ function isAuthFailure(response) {
1571
+ return response.status === 401 || response.status === 403;
1572
+ }
1573
+ function getInspectorStartupLogPath() {
1574
+ return path2.join(os.tmpdir(), "mcpjam-inspector-startup.log");
1575
+ }
1576
+ function openStartupLogFile(logPath) {
1577
+ try {
1578
+ if (existsSync(logPath) && statSync(logPath).size > STARTUP_LOG_MAX_BYTES) {
1579
+ renameSync(logPath, `${logPath}.1`);
1580
+ }
1581
+ } catch {
1582
+ }
1583
+ return openSync(logPath, "a");
1584
+ }
1585
+ function openUrl(url) {
1586
+ if (process.env.MCPJAM_CLI_DISABLE_BROWSER_OPEN === "1") {
1587
+ return;
1588
+ }
1589
+ const platform = process.platform;
1590
+ const child = platform === "darwin" ? spawn("open", [url], { detached: true, stdio: "ignore" }) : platform === "win32" ? spawn("cmd", ["/c", "start", "", url], {
1591
+ detached: true,
1592
+ stdio: "ignore"
1593
+ }) : spawn("xdg-open", [url], { detached: true, stdio: "ignore" });
1594
+ child.on("error", () => {
1595
+ });
1596
+ child.unref();
1597
+ }
1598
+ function delay(ms) {
1599
+ return new Promise((resolve) => {
1600
+ setTimeout(resolve, ms);
1601
+ });
1602
+ }
1603
+ async function readResponsePayload(response) {
1604
+ const text = await response.text();
1605
+ if (!text) {
1606
+ return null;
1607
+ }
1608
+ try {
1609
+ return JSON.parse(text);
1610
+ } catch {
1611
+ return text;
1612
+ }
1613
+ }
1614
+ function getErrorMessage(payload) {
1615
+ if (!payload || typeof payload !== "object") {
1616
+ return typeof payload === "string" ? payload : void 0;
1617
+ }
1618
+ const record = payload;
1619
+ if (typeof record.error === "string") {
1620
+ return record.error;
1621
+ }
1622
+ if (typeof record.message === "string") {
1623
+ return record.message;
1624
+ }
1625
+ return void 0;
1626
+ }
1627
+ function isInspectorCommandResponse(value) {
1628
+ if (!value || typeof value !== "object") {
1629
+ return false;
1630
+ }
1631
+ const record = value;
1632
+ if (typeof record.id !== "string") {
1633
+ return false;
1634
+ }
1635
+ if (record.status === "success") {
1636
+ return true;
1637
+ }
1638
+ if (record.status !== "error") {
1639
+ return false;
1640
+ }
1641
+ const error = record.error;
1642
+ return Boolean(
1643
+ error && typeof error === "object" && typeof error.code === "string" && typeof error.message === "string"
1644
+ );
1645
+ }
1646
+ async function listToolsWithMetadata(manager, params) {
1647
+ const result = await manager.listTools(
1648
+ params.serverId,
1649
+ params.cursor ? { cursor: params.cursor } : void 0
1650
+ );
1651
+ const tools = result.tools ?? [];
1652
+ const toolsMetadata = manager.getAllToolsMetadata(params.serverId);
1653
+ const tokenCount = params.modelId ? estimateTokensFromChars(JSON.stringify(tools)) : void 0;
1654
+ return {
1655
+ tools,
1656
+ nextCursor: result.nextCursor,
1657
+ toolsMetadata,
1658
+ ...tokenCount === void 0 ? {} : { tokenCount }
1659
+ };
1660
+ }
1661
+ function estimateTokensFromChars(text) {
1662
+ return Math.ceil(text.length / 4);
1663
+ }
1664
+
1665
+ // src/commands/apps-debug.ts
1666
+ function registerAppsDebugCommand(parent) {
1667
+ addRetryOptions(
1668
+ addSharedServerOptions(
1669
+ parent.command("debug").description("Debug an MCP App tool call from the CLI").requiredOption("--tool-name <name>", "Tool name to execute").option(
1670
+ "--params <json>",
1671
+ "Tool parameters as JSON, @path, or - for stdin"
1672
+ ).option(
1673
+ "--ui",
1674
+ "Open the Inspector UI to render the App after execution"
1675
+ ).option("--inspector-url <url>", "Local Inspector base URL (with --ui)").option(
1676
+ "--server-name <name>",
1677
+ "Server name inside Inspector (with --ui)"
1678
+ ).option(
1679
+ "--protocol <protocol>",
1680
+ 'Render protocol: "mcp-apps" or "openai-sdk" (with --ui)'
1681
+ ).option(
1682
+ "--device <device>",
1683
+ 'Render device: "mobile", "tablet", "desktop", or "custom" (with --ui)'
1684
+ ).option(
1685
+ "--theme <theme>",
1686
+ 'Render theme: "light" or "dark" (with --ui)'
1687
+ ).option("--locale <locale>", "Render locale (with --ui)").option("--time-zone <iana>", "Render IANA timezone (with --ui)").option("--out <path>", "Write the full debug artifact to a JSON file")
1688
+ )
1689
+ ).action(async (options, command) => {
1690
+ const globalOptions = getGlobalOptions(command);
1691
+ const retryPolicy = parseRetryPolicy(options);
1692
+ const target = describeTarget(options);
1693
+ const toolName = options.toolName;
1694
+ const params = parseJsonRecord(options.params, "Tool parameters") ?? {};
1695
+ const serverName = typeof options.serverName === "string" && options.serverName.trim() ? options.serverName.trim() : buildInspectorServerName(options);
1696
+ const config = parseServerConfig({
1697
+ ...options,
1698
+ timeout: globalOptions.timeout
1699
+ });
1700
+ const sdkResult = await runSdkAppsDebug({
1701
+ config,
1702
+ params,
1703
+ retryPolicy,
1704
+ toolName
1705
+ });
1706
+ const uiResult = options.ui ? await runUiRender({
1707
+ baseUrl: options.inspectorUrl,
1708
+ config,
1709
+ params,
1710
+ renderContext: {
1711
+ protocol: parseRenderProtocol(options.protocol),
1712
+ deviceType: parseRenderDevice(options.device),
1713
+ theme: parseTheme(options.theme),
1714
+ locale: trimOptional(options.locale),
1715
+ timeZone: trimOptional(options.timeZone)
1716
+ },
1717
+ serverName,
1718
+ timeoutMs: globalOptions.timeout,
1719
+ toolName,
1720
+ toolResult: sdkResult.execution
1721
+ }) : void 0;
1722
+ const inspectorRenderError = uiResult ? findInspectorRenderError(uiResult) : void 0;
1723
+ const sdkExecutionError = normalizeSdkExecutionError(sdkResult.execution);
1724
+ const payload = {
1725
+ success: !inspectorRenderError && !sdkExecutionError,
1726
+ command: "apps debug",
1727
+ inspectorUi: Boolean(options.ui),
1728
+ target,
1729
+ toolName,
1730
+ params,
1731
+ ...sdkResult,
1732
+ ...uiResult ? { inspectorRender: uiResult } : {},
1733
+ ...inspectorRenderError ? { error: inspectorRenderError } : sdkExecutionError ? { error: sdkExecutionError } : {}
1734
+ };
1735
+ if (inspectorRenderError || sdkExecutionError) {
1736
+ setProcessExitCode(1);
1737
+ }
1738
+ if (options.out) {
1739
+ const artifactPath = await writeJsonArtifact(options.out, payload);
1740
+ writeResult({ ...payload, artifactPath }, globalOptions.format);
1741
+ return;
1742
+ }
1743
+ writeResult(payload, globalOptions.format);
1744
+ });
1745
+ }
1746
+ async function runSdkAppsDebug(options) {
1747
+ return withEphemeralManager(
1748
+ options.config,
1749
+ async (manager, serverId) => {
1750
+ const toolsData = await listToolsWithMetadata(manager, { serverId });
1751
+ const execution = await manager.executeTool(
1752
+ serverId,
1753
+ options.toolName,
1754
+ options.params
1755
+ );
1756
+ return buildAppsDebugResult({
1757
+ execution,
1758
+ toolsData,
1759
+ toolName: options.toolName
1760
+ });
1761
+ },
1762
+ {
1763
+ retryPolicy: options.retryPolicy
1764
+ }
1765
+ );
1766
+ }
1767
+ async function runUiRender(options) {
1768
+ const client = new InspectorApiClient({ baseUrl: options.baseUrl });
1769
+ const ensureResult = await client.ensure({
1770
+ openBrowser: true,
1771
+ startIfNeeded: true,
1772
+ tab: "app-builder",
1773
+ timeoutMs: options.timeoutMs
1774
+ });
1775
+ await client.connectServer(options.serverName, options.config);
1776
+ const renderResult = await runInspectorAppRender({
1777
+ client,
1778
+ params: options.params,
1779
+ renderContext: options.renderContext,
1780
+ serverName: options.serverName,
1781
+ timeoutMs: options.timeoutMs,
1782
+ toolName: options.toolName,
1783
+ toolResult: options.toolResult
1784
+ });
1785
+ return {
1786
+ baseUrl: ensureResult.baseUrl,
1787
+ inspectorStarted: ensureResult.started,
1788
+ ...renderResult
1789
+ };
1790
+ }
1791
+ async function runInspectorAppRender(options) {
1792
+ const openAppBuilder = await executeInspectorCommandWithClient(options, {
1793
+ type: "openAppBuilder",
1794
+ payload: { serverName: options.serverName },
1795
+ timeoutMs: options.timeoutMs
1796
+ });
1797
+ if (openAppBuilder.status === "error") {
1798
+ return { openAppBuilder };
1799
+ }
1800
+ const contextPayload = compactRecord(options.renderContext);
1801
+ const setAppContext = Object.keys(contextPayload).length > 0 ? await executeInspectorCommandWithClient(options, {
1802
+ type: "setAppContext",
1803
+ payload: contextPayload,
1804
+ timeoutMs: options.timeoutMs
1805
+ }) : void 0;
1806
+ if (setAppContext?.status === "error") {
1807
+ return { openAppBuilder, setAppContext };
1808
+ }
1809
+ const renderToolResult = await executeInspectorCommandWithClient(options, {
1810
+ type: "renderToolResult",
1811
+ payload: {
1812
+ surface: "app-builder",
1813
+ serverName: options.serverName,
1814
+ toolName: options.toolName,
1815
+ parameters: options.params,
1816
+ result: options.toolResult
1817
+ },
1818
+ timeoutMs: options.timeoutMs
1819
+ });
1820
+ if (renderToolResult.status === "error") {
1821
+ return {
1822
+ openAppBuilder,
1823
+ ...setAppContext ? { setAppContext } : {},
1824
+ renderToolResult
1825
+ };
1826
+ }
1827
+ const snapshotApp = await executeInspectorCommandWithClient(options, {
1828
+ type: "snapshotApp",
1829
+ payload: { surface: "app-builder" },
1830
+ timeoutMs: options.timeoutMs
1831
+ });
1832
+ return {
1833
+ openAppBuilder,
1834
+ ...setAppContext ? { setAppContext } : {},
1835
+ renderToolResult,
1836
+ snapshot: snapshotApp
1837
+ };
1838
+ }
1839
+ async function executeInspectorCommandWithClient(options, request) {
1840
+ const startedAt = Date.now();
1841
+ const deadline = startedAt + options.timeoutMs;
1842
+ do {
1843
+ const response = await options.client.executeCommand(request);
1844
+ const retryable = response.status === "error" && (response.error.code === "no_active_client" || response.error.code === "unsupported_in_mode" || response.error.code === "disconnected_server");
1845
+ if (!retryable || Date.now() >= deadline) {
1846
+ return response;
1847
+ }
1848
+ await delay(500);
1849
+ } while (true);
1850
+ }
1851
+ function findInspectorRenderError(renderResult) {
1852
+ const priority = [
1853
+ "renderToolResult",
1854
+ "setAppContext",
1855
+ "openAppBuilder",
1856
+ "snapshot",
1857
+ "snapshotApp"
1858
+ ];
1859
+ for (const key of priority) {
1860
+ const value = renderResult[key];
1861
+ if (value && typeof value === "object" && value.status === "error") {
1862
+ return value.error;
1863
+ }
1864
+ }
1865
+ return void 0;
1866
+ }
1867
+ function normalizeSdkExecutionError(execution) {
1868
+ if (!execution || typeof execution !== "object") {
1869
+ return void 0;
1870
+ }
1871
+ const record = execution;
1872
+ const result = record.result && typeof record.result === "object" ? record.result : record;
1873
+ if (result.isError !== true) {
1874
+ return void 0;
1875
+ }
1876
+ const message = extractSdkErrorMessage(result) ?? "Tool execution failed.";
1877
+ return {
1878
+ code: "tool_execution_failed",
1879
+ message,
1880
+ details: execution
1881
+ };
1882
+ }
1883
+ function extractSdkErrorMessage(result) {
1884
+ if (typeof result.error === "string") {
1885
+ return result.error;
1886
+ }
1887
+ if (typeof result.message === "string") {
1888
+ return result.message;
1889
+ }
1890
+ const content = result.content;
1891
+ if (!Array.isArray(content)) {
1892
+ return void 0;
1893
+ }
1894
+ const text = content.map(
1895
+ (entry) => entry && typeof entry === "object" && typeof entry.text === "string" ? entry.text : void 0
1896
+ ).filter((entry) => Boolean(entry?.trim())).join("\n");
1897
+ return text || void 0;
1898
+ }
1899
+ function buildAppsDebugResult(options) {
1900
+ const toolsData = normalizeToolsData(options.toolsData);
1901
+ const tool = toolsData.tools.find((entry) => entry.name === options.toolName);
1902
+ const toolMetadata = toolsData.toolsMetadata[options.toolName] ?? {};
1903
+ const ui = extractToolUiMetadata(toolMetadata);
1904
+ return {
1905
+ tools: {
1906
+ count: toolsData.tools.length,
1907
+ matched: Boolean(tool),
1908
+ ...tool ? { tool } : {}
1909
+ },
1910
+ toolsMetadata: toolsData.toolsMetadata,
1911
+ toolMetadata,
1912
+ ui,
1913
+ execution: options.execution
1914
+ };
1915
+ }
1916
+ function normalizeToolsData(value) {
1917
+ if (!value || typeof value !== "object") {
1918
+ return { tools: [], toolsMetadata: {} };
1919
+ }
1920
+ const record = value;
1921
+ const tools = Array.isArray(record.tools) ? record.tools.filter(
1922
+ (tool) => Boolean(
1923
+ tool && typeof tool === "object" && typeof tool.name === "string"
1924
+ )
1925
+ ) : [];
1926
+ const toolsMetadata = record.toolsMetadata && typeof record.toolsMetadata === "object" && !Array.isArray(record.toolsMetadata) ? record.toolsMetadata : {};
1927
+ return { tools, toolsMetadata };
1928
+ }
1929
+ function extractToolUiMetadata(meta) {
1930
+ const nested = meta.ui;
1931
+ const mcpAppsResourceUri = nested && typeof nested === "object" ? nested.resourceUri : void 0;
1932
+ const legacyResourceUri = meta["ui/resourceUri"];
1933
+ const openAiOutputTemplate = meta["openai/outputTemplate"];
1934
+ return {
1935
+ resourceUri: typeof mcpAppsResourceUri === "string" ? mcpAppsResourceUri : typeof legacyResourceUri === "string" ? legacyResourceUri : typeof openAiOutputTemplate === "string" ? openAiOutputTemplate : null,
1936
+ mcpAppsResourceUri: typeof mcpAppsResourceUri === "string" ? mcpAppsResourceUri : null,
1937
+ legacyResourceUri: typeof legacyResourceUri === "string" ? legacyResourceUri : null,
1938
+ openAiOutputTemplate: typeof openAiOutputTemplate === "string" ? openAiOutputTemplate : null
1939
+ };
1940
+ }
1941
+ function parseRenderProtocol(value) {
1942
+ if (value === void 0) return void 0;
1943
+ if (value === "mcp-apps" || value === "openai-sdk") return value;
1944
+ throw usageError(
1945
+ `Invalid protocol "${value}". Use "mcp-apps" or "openai-sdk".`
1946
+ );
1947
+ }
1948
+ function parseRenderDevice(value) {
1949
+ if (value === void 0) return void 0;
1950
+ if (value === "mobile" || value === "tablet" || value === "desktop" || value === "custom") {
1951
+ return value;
1952
+ }
1953
+ throw usageError(
1954
+ `Invalid device "${value}". Use "mobile", "tablet", "desktop", or "custom".`
1955
+ );
1956
+ }
1957
+ function compactRecord(record) {
1958
+ return Object.fromEntries(
1959
+ Object.entries(record).filter(([, value]) => value !== void 0)
1960
+ );
1961
+ }
1962
+ function trimOptional(value) {
1963
+ const trimmed = value?.trim();
1964
+ return trimmed ? trimmed : void 0;
1965
+ }
1966
+ function buildInspectorServerName(options) {
1967
+ if (typeof options.url === "string" && options.url.trim()) {
1968
+ try {
1969
+ const parsed = new URL(options.url);
1970
+ const host = parsed.port ? `${parsed.hostname}-${parsed.port}` : parsed.hostname;
1971
+ const raw = `${host}${parsed.pathname}`.replace(/\/+$/, "").replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-+|-+$/g, "") || parsed.hostname;
1972
+ return raw || "inspector-server";
1973
+ } catch {
1974
+ return "inspector-server";
1975
+ }
1976
+ }
1977
+ if (typeof options.command === "string" && options.command.trim()) {
1978
+ return path2.basename(options.command.trim()).replace(/\.[a-z0-9]+$/i, "").replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "inspector-server";
1979
+ }
1980
+ return "inspector-server";
1981
+ }
1982
+
1983
+ // src/commands/apps.ts
1984
+ var APPS_CHECK_IDS_BY_CATEGORY = {
1985
+ tools: [
1986
+ "ui-tools-present",
1987
+ "ui-tool-metadata-valid",
1988
+ "ui-tool-input-schema-valid"
1989
+ ],
1990
+ resources: [
1991
+ "ui-listed-resources-valid",
1992
+ "ui-resources-readable",
1993
+ "ui-resource-contents-valid",
1994
+ "ui-resource-meta-valid"
1995
+ ]
1996
+ };
1997
+ function getConformanceGlobals(command, reporter) {
1998
+ const globalOptions = command.optsWithGlobals();
1999
+ return {
2000
+ format: resolveConformanceOutputFormatForCli(
2001
+ globalOptions.format,
2002
+ process.stdout.isTTY,
2003
+ reporter
2004
+ ),
2005
+ timeout: globalOptions.timeout ?? 3e4,
2006
+ rpc: globalOptions.rpc ?? false,
2007
+ quiet: globalOptions.quiet ?? false
2008
+ };
2009
+ }
2010
+ function writeConformanceOutput(output) {
2011
+ process.stdout.write(output.endsWith("\n") ? output : `${output}
2012
+ `);
2013
+ }
2014
+ function registerAppsCommands(program) {
2015
+ const apps = program.command("apps").description(
2016
+ "MCP Apps utilities, widget extraction, and conformance checks"
2017
+ );
2018
+ addSharedServerOptions(
2019
+ apps.command("conformance").description("Run MCP Apps server conformance checks").option(
2020
+ "--category <category>",
2021
+ "Check category to run. Repeat for multiple. Default: all.",
2022
+ (value, previous = []) => [...previous, value],
2023
+ []
2024
+ ).option(
2025
+ "--check-id <id>",
2026
+ "Specific check ID to run. Repeat for multiple. Default: all.",
2027
+ (value, previous = []) => [...previous, value],
2028
+ []
2029
+ ).option(
2030
+ "--reporter <reporter>",
2031
+ "Structured reporter output: json-summary or junit-xml"
2032
+ )
2033
+ ).action(async (options, command) => {
2034
+ const reporter = parseReporterFormat(options.reporter);
2035
+ const globalOptions = getConformanceGlobals(command, reporter);
2036
+ const target = describeTarget(options);
2037
+ const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2038
+ const config = {
2039
+ ...buildAppsConformanceConfig({
2040
+ ...options,
2041
+ timeout: globalOptions.timeout
2042
+ }),
2043
+ ...collector ? { rpcLogger: collector.rpcLogger } : {}
2044
+ };
2045
+ const result = await new MCPAppsConformanceTest(config).run();
2046
+ const outputResult = reporter ? result : withRpcLogsIfRequested(
2047
+ result,
2048
+ collector,
2049
+ globalOptions
2050
+ );
2051
+ writeConformanceOutput(
2052
+ renderConformanceForCli(outputResult, reporter, globalOptions.format)
2053
+ );
2054
+ if (!result.passed) {
2055
+ setProcessExitCode(1);
2056
+ }
2057
+ });
2058
+ apps.command("conformance-suite").description("Run MCP Apps conformance runs from a JSON config file").requiredOption("--config <path>", "Path to JSON config file").option(
2059
+ "--reporter <reporter>",
2060
+ "Structured reporter output: json-summary or junit-xml"
2061
+ ).action(async (options, command) => {
2062
+ const reporter = parseReporterFormat(options.reporter);
2063
+ const globalOptions = getConformanceGlobals(command, reporter);
2064
+ const config = loadAppsSuiteConfig(options.config);
2065
+ const target = config.target.command ?? config.target.url ?? "apps-suite";
2066
+ const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2067
+ const suite = new MCPAppsConformanceSuite({
2068
+ ...config,
2069
+ target: {
2070
+ ...config.target,
2071
+ ...collector ? { rpcLogger: collector.rpcLogger } : {}
2072
+ }
2073
+ });
2074
+ const result = await suite.run();
2075
+ const outputResult = reporter ? result : withRpcLogsIfRequested(
2076
+ result,
2077
+ collector,
2078
+ globalOptions
2079
+ );
2080
+ writeConformanceOutput(
2081
+ renderConformanceForCli(outputResult, reporter, globalOptions.format)
2082
+ );
2083
+ if (!result.passed) {
2084
+ setProcessExitCode(1);
2085
+ }
2086
+ });
2087
+ registerAppsDebugCommand(apps);
2088
+ addRetryOptions(
2089
+ addSharedServerOptions(
2090
+ apps.command("mcp-widget").description("Fetch hosted-style MCP App widget content").requiredOption("--resource-uri <uri>", "Widget resource URI").requiredOption(
2091
+ "--tool-id <id>",
2092
+ "Tool call id used for runtime injection"
2093
+ ).requiredOption(
2094
+ "--tool-name <name>",
2095
+ "Tool name used for runtime injection"
2096
+ ).option(
2097
+ "--tool-input <json>",
2098
+ "Tool input payload as JSON, @path, or - for stdin"
2099
+ ).option(
2100
+ "--tool-output <json>",
2101
+ "Tool output payload as JSON, @path, or - for stdin"
2102
+ ).option("--theme <theme>", "Widget theme: light or dark").option("--csp-mode <mode>", "CSP mode: permissive or widget-declared").option("--template <uri>", "Optional ui:// template override").option("--view-mode <mode>", "Widget view mode").option(
2103
+ "--view-params <json>",
2104
+ "Widget view params as JSON, @path, or - for stdin"
2105
+ )
2106
+ )
2107
+ ).action(async (options, command) => {
2108
+ const globalOptions = getGlobalOptions(command);
2109
+ const retryPolicy = parseRetryPolicy(options);
2110
+ const target = describeTarget(options);
2111
+ const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2112
+ const config = parseServerConfig({
2113
+ ...options,
2114
+ timeout: globalOptions.timeout
2115
+ });
2116
+ const result = await withEphemeralManager(
2117
+ config,
2118
+ (manager, serverId) => buildMcpWidgetContent(manager, serverId, {
2119
+ resourceUri: options.resourceUri,
2120
+ toolId: options.toolId,
2121
+ toolName: options.toolName,
2122
+ toolInput: parseJsonRecord(options.toolInput, "Tool input") ?? {},
2123
+ toolOutput: parseJsonInputValue(options.toolOutput, "Tool output"),
2124
+ theme: parseTheme(options.theme),
2125
+ cspMode: parseCspMode(options.cspMode),
2126
+ template: options.template,
2127
+ viewMode: options.viewMode,
2128
+ viewParams: parseJsonRecord(options.viewParams, "View params")
2129
+ }),
2130
+ {
2131
+ timeout: globalOptions.timeout,
2132
+ rpcLogger: collector?.rpcLogger,
2133
+ retryPolicy
2134
+ }
2135
+ );
2136
+ writeResult(
2137
+ withRpcLogsIfRequested(result, collector, globalOptions),
2138
+ globalOptions.format
2139
+ );
2140
+ });
2141
+ addRetryOptions(
2142
+ addSharedServerOptions(
2143
+ apps.command("chatgpt-widget").description("Fetch hosted-style ChatGPT App widget content").requiredOption("--resource-uri <uri>", "Widget resource URI").requiredOption(
2144
+ "--tool-id <id>",
2145
+ "Tool call id used for runtime injection"
2146
+ ).requiredOption(
2147
+ "--tool-name <name>",
2148
+ "Tool name used for runtime injection"
2149
+ ).option(
2150
+ "--tool-input <json>",
2151
+ "Tool input payload as JSON, @path, or - for stdin"
2152
+ ).option(
2153
+ "--tool-output <json>",
2154
+ "Tool output payload as JSON, @path, or - for stdin"
2155
+ ).option(
2156
+ "--tool-response-metadata <json>",
2157
+ "Tool response metadata as JSON, @path, or - for stdin"
2158
+ ).option("--theme <theme>", "Widget theme: light or dark").option("--csp-mode <mode>", "CSP mode: permissive or widget-declared").option("--locale <locale>", "Locale override").option(
2159
+ "--device-type <type>",
2160
+ "Device type: mobile, tablet, or desktop"
2161
+ )
2162
+ )
2163
+ ).action(async (options, command) => {
2164
+ const globalOptions = getGlobalOptions(command);
2165
+ const retryPolicy = parseRetryPolicy(options);
2166
+ const target = describeTarget(options);
2167
+ const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
763
2168
  const config = parseServerConfig({
764
2169
  ...options,
765
2170
  timeout: globalOptions.timeout
@@ -767,11 +2172,11 @@ function registerAppsCommands(program) {
767
2172
  const result = await withEphemeralManager(
768
2173
  config,
769
2174
  (manager, serverId) => buildChatGptWidgetContent(manager, serverId, {
770
- uri: resourceUri,
2175
+ uri: options.resourceUri,
771
2176
  toolId: options.toolId,
772
2177
  toolName: options.toolName,
773
2178
  toolInput: parseJsonRecord(options.toolInput, "Tool input") ?? {},
774
- toolOutput: parseJsonValue(options.toolOutput),
2179
+ toolOutput: parseJsonInputValue(options.toolOutput, "Tool output"),
775
2180
  toolResponseMetadata: parseJsonRecord(
776
2181
  options.toolResponseMetadata,
777
2182
  "Tool response metadata"
@@ -793,27 +2198,6 @@ function registerAppsCommands(program) {
793
2198
  );
794
2199
  });
795
2200
  }
796
- function parseJsonValue(value) {
797
- if (value === void 0) {
798
- return void 0;
799
- }
800
- try {
801
- return JSON.parse(value);
802
- } catch (error) {
803
- throw usageError("Value must be valid JSON.", {
804
- source: error instanceof Error ? error.message : String(error)
805
- });
806
- }
807
- }
808
- function parseTheme(value) {
809
- if (value === void 0) {
810
- return void 0;
811
- }
812
- if (value === "light" || value === "dark") {
813
- return value;
814
- }
815
- throw usageError(`Invalid theme "${value}". Use "light" or "dark".`);
816
- }
817
2201
  function parseCspMode(value) {
818
2202
  if (value === void 0) {
819
2203
  return void 0;
@@ -844,7 +2228,7 @@ function buildAppsConformanceConfig(options) {
844
2228
  const categories = options.category?.filter(Boolean);
845
2229
  const invalidCategories = collectInvalidEntries(
846
2230
  categories,
847
- sdk.MCP_APPS_CHECK_CATEGORIES
2231
+ MCP_APPS_CHECK_CATEGORIES
848
2232
  );
849
2233
  if (invalidCategories.length > 0) {
850
2234
  throw usageError(
@@ -852,7 +2236,7 @@ function buildAppsConformanceConfig(options) {
852
2236
  );
853
2237
  }
854
2238
  const checkIds = options.checkId?.filter(Boolean);
855
- const invalidCheckIds = collectInvalidEntries(checkIds, sdk.MCP_APPS_CHECK_IDS);
2239
+ const invalidCheckIds = collectInvalidEntries(checkIds, MCP_APPS_CHECK_IDS);
856
2240
  if (invalidCheckIds.length > 0) {
857
2241
  throw usageError(
858
2242
  `Unknown check id${invalidCheckIds.length === 1 ? "" : "s"}: ${invalidCheckIds.join(", ")}`
@@ -873,6 +2257,9 @@ function buildAppsConformanceConfig(options) {
873
2257
  function registerProtocolCommands(program) {
874
2258
  const protocol = program.command("protocol").description("MCP protocol inspection and conformance checks");
875
2259
  protocol.command("conformance").description("Run MCP protocol conformance checks against an HTTP server").requiredOption("--url <url>", "MCP server URL").option("--access-token <token>", "Bearer access token for HTTP servers").option(
2260
+ "--credentials-file <path>",
2261
+ "Load OAuth access token from a file created by oauth login --credentials-out"
2262
+ ).option(
876
2263
  "--header <header>",
877
2264
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
878
2265
  (value, previous = []) => [...previous, value],
@@ -892,231 +2279,96 @@ function registerProtocolCommands(program) {
892
2279
  "Specific check ID to run. Repeat for multiple. Default: all.",
893
2280
  (value, previous = []) => [...previous, value],
894
2281
  []
2282
+ ).option(
2283
+ "--reporter <reporter>",
2284
+ "Structured reporter output: json-summary or junit-xml"
895
2285
  ).action(async (options, command) => {
896
- const format = getFormat(command);
2286
+ const reporter = parseReporterFormat(options.reporter);
2287
+ const format = getFormat(command, reporter);
897
2288
  const config = buildConfig(options);
898
- const result = await new sdk.MCPConformanceTest(config).run();
899
- writeResult(result, format);
2289
+ const result = await new MCPConformanceTest(config).run();
2290
+ writeConformanceOutput2(renderConformanceForCli(result, reporter, format));
900
2291
  if (!result.passed) {
901
- setProcessExitCode(1);
902
- }
903
- });
904
- }
905
- function getFormat(command) {
906
- const opts = command.optsWithGlobals();
907
- return resolveOutputFormat(opts.format, process.stdout.isTTY);
908
- }
909
- function collectInvalidEntries2(values, allowedValues) {
910
- return (values ?? []).filter((value) => !allowedValues.includes(value));
911
- }
912
- function buildConfig(options) {
913
- const serverUrl = options.url.trim();
914
- let parsed;
915
- try {
916
- parsed = new URL(serverUrl);
917
- } catch {
918
- throw usageError(`Invalid URL: ${serverUrl}`);
919
- }
920
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
921
- throw usageError(`Invalid URL scheme: ${serverUrl}`);
922
- }
923
- const customHeaders = parseHeadersOption(options.header);
924
- const categories = options.category?.filter(Boolean);
925
- const invalidCategories = collectInvalidEntries2(
926
- categories,
927
- sdk.MCP_CHECK_CATEGORIES
928
- );
929
- if (invalidCategories.length > 0) {
930
- throw usageError(
931
- invalidCategories.length === 1 ? `Unknown category: ${invalidCategories[0]}` : `Unknown categories: ${invalidCategories.join(", ")}`
932
- );
933
- }
934
- const checkIds = options.checkId?.filter(Boolean);
935
- const invalidCheckIds = collectInvalidEntries2(checkIds, sdk.MCP_CHECK_IDS);
936
- if (invalidCheckIds.length > 0) {
937
- throw usageError(
938
- `Unknown check id${invalidCheckIds.length === 1 ? "" : "s"}: ${invalidCheckIds.join(", ")}`
939
- );
940
- }
941
- return {
942
- serverUrl,
943
- accessToken: options.accessToken,
944
- customHeaders,
945
- checkTimeout: options.checkTimeout ?? 15e3,
946
- ...categories && categories.length > 0 ? { categories } : {},
947
- ...checkIds && checkIds.length > 0 ? { checkIds } : {}
948
- };
949
- }
950
-
951
- // src/lib/oauth-enums.ts
952
- var VALID_PROTOCOL_VERSIONS = /* @__PURE__ */ new Set([
953
- "2025-03-26",
954
- "2025-06-18",
955
- "2025-11-25"
956
- ]);
957
- var VALID_REGISTRATION_STRATEGIES = /* @__PURE__ */ new Set([
958
- "cimd",
959
- "dcr",
960
- "preregistered"
961
- ]);
962
- var VALID_AUTH_MODES = /* @__PURE__ */ new Set([
963
- "headless",
964
- "interactive",
965
- "client_credentials"
966
- ]);
967
- function assertValidUrl(value, label) {
968
- if (typeof value !== "string" || !value.trim()) {
969
- throw usageError(`${label} is required and must be a non-empty string`);
970
- }
971
- try {
972
- new URL(value);
973
- } catch {
974
- throw usageError(`Invalid ${label}: ${value}`);
975
- }
976
- }
977
- function assertEnum(value, allowed, label) {
978
- if (typeof value !== "string" || !allowed.has(value)) {
979
- throw usageError(
980
- `Invalid ${label} "${String(value)}". Allowed: ${[...allowed].join(", ")}`
981
- );
982
- }
983
- }
984
- function validateFlow(flow, defaults, index) {
985
- const protocolVersion = flow.protocolVersion ?? defaults?.protocolVersion;
986
- if (!protocolVersion) {
987
- throw usageError(
988
- `flows[${index}]: protocolVersion is required (not set in flow or defaults)`
989
- );
990
- }
991
- assertEnum(protocolVersion, VALID_PROTOCOL_VERSIONS, `flows[${index}].protocolVersion`);
992
- const registrationStrategy = flow.registrationStrategy ?? defaults?.registrationStrategy;
993
- if (!registrationStrategy) {
994
- throw usageError(
995
- `flows[${index}]: registrationStrategy is required (not set in flow or defaults)`
996
- );
997
- }
998
- assertEnum(
999
- registrationStrategy,
1000
- VALID_REGISTRATION_STRATEGIES,
1001
- `flows[${index}].registrationStrategy`
2292
+ setProcessExitCode(1);
2293
+ }
2294
+ });
2295
+ protocol.command("conformance-suite").description(
2296
+ "Run a matrix of MCP protocol conformance checks from a JSON config file"
2297
+ ).requiredOption("--config <path>", "Path to JSON config file").option(
2298
+ "--reporter <reporter>",
2299
+ "Structured reporter output: json-summary or junit-xml"
2300
+ ).action(async (options, command) => {
2301
+ const reporter = parseReporterFormat(options.reporter);
2302
+ const format = getFormat(command, reporter);
2303
+ const config = loadProtocolSuiteConfig(options.config);
2304
+ const result = await new MCPConformanceSuite(config).run();
2305
+ writeConformanceOutput2(renderConformanceForCli(result, reporter, format));
2306
+ if (!result.passed) {
2307
+ setProcessExitCode(1);
2308
+ }
2309
+ });
2310
+ }
2311
+ function getFormat(command, reporter) {
2312
+ const opts = command.optsWithGlobals();
2313
+ return resolveConformanceOutputFormatForCli(
2314
+ opts.format,
2315
+ process.stdout.isTTY,
2316
+ reporter
1002
2317
  );
1003
- const auth = flow.auth ?? defaults?.auth;
1004
- if (auth?.mode) {
1005
- assertEnum(auth.mode, VALID_AUTH_MODES, `flows[${index}].auth.mode`);
1006
- }
1007
2318
  }
1008
- function loadSuiteConfig(filePath) {
1009
- let raw;
1010
- try {
1011
- raw = fs.readFileSync(filePath, "utf-8");
1012
- } catch (error) {
1013
- throw usageError(
1014
- `Cannot read config file "${filePath}": ${error instanceof Error ? error.message : String(error)}`
1015
- );
1016
- }
1017
- let config;
2319
+ function writeConformanceOutput2(output) {
2320
+ process.stdout.write(output.endsWith("\n") ? output : `${output}
2321
+ `);
2322
+ }
2323
+ function collectInvalidEntries2(values, allowedValues) {
2324
+ return (values ?? []).filter((value) => !allowedValues.includes(value));
2325
+ }
2326
+ function buildConfig(options) {
2327
+ const serverUrl = options.url.trim();
2328
+ let parsed;
1018
2329
  try {
1019
- config = JSON.parse(raw);
2330
+ parsed = new URL(serverUrl);
1020
2331
  } catch {
1021
- throw usageError(`Config file "${filePath}" is not valid JSON`);
2332
+ throw usageError(`Invalid URL: ${serverUrl}`);
1022
2333
  }
1023
- if (typeof config !== "object" || config === null || Array.isArray(config)) {
1024
- throw usageError("Config file must be a JSON object");
2334
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
2335
+ throw usageError(`Invalid URL scheme: ${serverUrl}`);
1025
2336
  }
1026
- assertValidUrl(config.serverUrl, "serverUrl");
1027
- const flows = config.flows;
1028
- if (!Array.isArray(flows) || flows.length === 0) {
1029
- throw usageError('Config file must have a non-empty "flows" array');
2337
+ const customHeaders = parseHeadersOption(options.header);
2338
+ assertNoCredentialsFileAuthConflicts(options);
2339
+ const accessToken = options.credentialsFile ? resolveCredentialsFileAccessToken(options.credentialsFile, serverUrl) : options.accessToken;
2340
+ const categories = options.category?.filter(Boolean);
2341
+ const invalidCategories = collectInvalidEntries2(
2342
+ categories,
2343
+ MCP_CHECK_CATEGORIES
2344
+ );
2345
+ if (invalidCategories.length > 0) {
2346
+ throw usageError(
2347
+ invalidCategories.length === 1 ? `Unknown category: ${invalidCategories[0]}` : `Unknown categories: ${invalidCategories.join(", ")}`
2348
+ );
1030
2349
  }
1031
- const defaults = config.defaults;
1032
- for (let i = 0; i < flows.length; i++) {
1033
- const flow = flows[i];
1034
- if (typeof flow !== "object" || flow === null || Array.isArray(flow)) {
1035
- throw usageError(`flows[${i}] must be an object`);
1036
- }
1037
- validateFlow(flow, defaults, i);
2350
+ const checkIds = options.checkId?.filter(Boolean);
2351
+ const invalidCheckIds = collectInvalidEntries2(checkIds, MCP_CHECK_IDS);
2352
+ if (invalidCheckIds.length > 0) {
2353
+ throw usageError(
2354
+ `Unknown check id${invalidCheckIds.length === 1 ? "" : "s"}: ${invalidCheckIds.join(", ")}`
2355
+ );
1038
2356
  }
1039
- return config;
1040
- }
1041
-
1042
- // src/lib/junit-xml.ts
1043
- function escapeXml(value) {
1044
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1045
- }
1046
- function stepToTestCase(step, classname) {
1047
- const name = escapeXml(step.title || step.step);
1048
- const time = (step.durationMs / 1e3).toFixed(3);
1049
- const cls = escapeXml(classname);
1050
- if (step.status === "skipped") {
1051
- return ` <testcase name="${name}" classname="${cls}" time="${time}">
1052
- <skipped/>
1053
- </testcase>`;
1054
- }
1055
- if (step.status === "failed") {
1056
- const message = escapeXml(step.error?.message ?? "Unknown failure");
1057
- const details = step.httpAttempts.map((attempt) => {
1058
- const req = `${attempt.request.method} ${attempt.request.url}`;
1059
- const res = attempt.response ? `${attempt.response.status} ${attempt.response.statusText}` : "No response";
1060
- return `${req} \u2192 ${res}`;
1061
- }).join("\n");
1062
- const body = details ? escapeXml(details) : "";
1063
- return ` <testcase name="${name}" classname="${cls}" time="${time}">
1064
- <failure message="${message}">${body}</failure>
1065
- </testcase>`;
1066
- }
1067
- return ` <testcase name="${name}" classname="${cls}" time="${time}"/>`;
1068
- }
1069
- function flowToTestSuite(result) {
1070
- const name = escapeXml(result.label);
1071
- const tests = result.steps.length;
1072
- const failures = result.steps.filter((s) => s.status === "failed").length;
1073
- const skipped = result.steps.filter((s) => s.status === "skipped").length;
1074
- const time = (result.durationMs / 1e3).toFixed(3);
1075
- const classname = result.serverUrl;
1076
- const cases = result.steps.map((step) => stepToTestCase(step, classname)).join("\n");
1077
- return ` <testsuite name="${name}" tests="${tests}" failures="${failures}" skipped="${skipped}" time="${time}">
1078
- ${cases}
1079
- </testsuite>`;
1080
- }
1081
- function suiteResultToJUnitXml(result) {
1082
- const name = escapeXml(result.name);
1083
- const tests = result.results.reduce((sum, r) => sum + r.steps.length, 0);
1084
- const failures = result.results.reduce(
1085
- (sum, r) => sum + r.steps.filter((s) => s.status === "failed").length,
1086
- 0
1087
- );
1088
- const time = (result.durationMs / 1e3).toFixed(3);
1089
- const suites = result.results.map(flowToTestSuite).join("\n");
1090
- return `<?xml version="1.0" encoding="UTF-8"?>
1091
- <testsuites name="${name}" tests="${tests}" failures="${failures}" time="${time}">
1092
- ${suites}
1093
- </testsuites>
1094
- `;
1095
- }
1096
- function singleResultToJUnitXml(result, label) {
1097
- const suiteResult = {
1098
- name: "OAuth Conformance",
1099
- serverUrl: result.serverUrl,
1100
- passed: result.passed,
1101
- results: [
1102
- {
1103
- ...result,
1104
- label: `${result.protocolVersion}/${result.registrationStrategy}`
1105
- }
1106
- ],
1107
- summary: result.summary,
1108
- durationMs: result.durationMs
2357
+ return {
2358
+ serverUrl,
2359
+ accessToken,
2360
+ customHeaders,
2361
+ checkTimeout: options.checkTimeout ?? 15e3,
2362
+ ...categories && categories.length > 0 ? { categories } : {},
2363
+ ...checkIds && checkIds.length > 0 ? { checkIds } : {}
1109
2364
  };
1110
- return suiteResultToJUnitXml(suiteResult);
1111
2365
  }
1112
-
1113
- // src/lib/oauth-output.ts
1114
2366
  function parseOAuthOutputFormat(value) {
1115
- if (value === "json" || value === "human" || value === "junit-xml") {
2367
+ if (value === "json" || value === "human") {
1116
2368
  return value;
1117
2369
  }
1118
2370
  throw usageError(
1119
- `Invalid output format "${value}". Use "json", "human", or "junit-xml".`
2371
+ `Invalid output format "${value}". Use "json" or "human".`
1120
2372
  );
1121
2373
  }
1122
2374
  function resolveOAuthOutputFormat(value, isTTY) {
@@ -1125,9 +2377,7 @@ function resolveOAuthOutputFormat(value, isTTY) {
1125
2377
  function renderOAuthConformanceResult(result, format) {
1126
2378
  switch (format) {
1127
2379
  case "human":
1128
- return sdk.formatOAuthConformanceHuman(result);
1129
- case "junit-xml":
1130
- return singleResultToJUnitXml(result);
2380
+ return formatOAuthConformanceHuman(result);
1131
2381
  case "json":
1132
2382
  return JSON.stringify(result);
1133
2383
  }
@@ -1135,9 +2385,7 @@ function renderOAuthConformanceResult(result, format) {
1135
2385
  function renderOAuthConformanceSuiteResult(result, format) {
1136
2386
  switch (format) {
1137
2387
  case "human":
1138
- return sdk.formatOAuthConformanceSuiteHuman(result);
1139
- case "junit-xml":
1140
- return suiteResultToJUnitXml(result);
2388
+ return formatOAuthConformanceSuiteHuman(result);
1141
2389
  case "json":
1142
2390
  return JSON.stringify(result);
1143
2391
  }
@@ -1160,7 +2408,7 @@ async function writeCommandDebugArtifact(options, dependencies = {}) {
1160
2408
  ]
1161
2409
  });
1162
2410
  const artifactPath = await writeDebugArtifact(options.outputPath, payload);
1163
- if (options.format === "human") {
2411
+ if (options.format === "human" && !options.quiet) {
1164
2412
  process.stderr.write(`Debug artifact: ${artifactPath}
1165
2413
  `);
1166
2414
  }
@@ -1185,7 +2433,7 @@ function buildDebugArtifactEnvelope(options) {
1185
2433
  if (rpcLogs.length > 0) {
1186
2434
  payload._rpcLogs = rpcLogs;
1187
2435
  }
1188
- return sdk.redactSensitiveValue(payload);
2436
+ return redactSensitiveValue(payload);
1189
2437
  }
1190
2438
  function buildCommandArtifactError(code, message, details) {
1191
2439
  return {
@@ -1195,11 +2443,11 @@ function buildCommandArtifactError(code, message, details) {
1195
2443
  };
1196
2444
  }
1197
2445
  async function writeDebugArtifact(outputPath, payload) {
1198
- const resolvedPath = path__default.default.resolve(process.cwd(), outputPath);
1199
- const redactedPayload = sdk.redactSensitiveValue(payload);
2446
+ const resolvedPath = path2.resolve(process.cwd(), outputPath);
2447
+ const redactedPayload = redactSensitiveValue(payload);
1200
2448
  try {
1201
- await promises.mkdir(path__default.default.dirname(resolvedPath), { recursive: true });
1202
- await promises.writeFile(
2449
+ await mkdir(path2.dirname(resolvedPath), { recursive: true });
2450
+ await writeFile(
1203
2451
  resolvedPath,
1204
2452
  `${JSON.stringify(redactedPayload, null, 2)}
1205
2453
  `,
@@ -1217,7 +2465,7 @@ async function writeDebugArtifact(outputPath, payload) {
1217
2465
  }
1218
2466
  async function collectDoctorSnapshot(options, dependencies = {}) {
1219
2467
  try {
1220
- const runDoctor = dependencies.runDoctor ?? sdk.runServerDoctor;
2468
+ const runDoctor = dependencies.runDoctor ?? runServerDoctor;
1221
2469
  return {
1222
2470
  snapshot: await runDoctor({
1223
2471
  ...options.input,
@@ -1343,27 +2591,55 @@ function getOAuthFormat(command) {
1343
2591
  const opts = command.optsWithGlobals();
1344
2592
  return resolveOAuthOutputFormat(opts.format, process.stdout.isTTY);
1345
2593
  }
1346
- function getStructuredOAuthFormat(command) {
1347
- const format = getOAuthFormat(command);
1348
- if (format === "junit-xml") {
1349
- throw usageError(
1350
- 'The oauth metadata/proxy commands only support --format "json" or "human".'
1351
- );
1352
- }
1353
- return format;
2594
+ function getOAuthConformanceFormat(command, reporter) {
2595
+ const opts = command.optsWithGlobals();
2596
+ return resolveConformanceOutputFormatForCli(
2597
+ opts.format,
2598
+ process.stdout.isTTY,
2599
+ reporter
2600
+ );
1354
2601
  }
1355
2602
  function writeOAuthOutput(output) {
1356
2603
  process.stdout.write(output.endsWith("\n") ? output : `${output}
1357
2604
  `);
1358
2605
  }
2606
+ function buildOAuthLoginDebugOutcome(options) {
2607
+ if (options.commandError !== void 0) {
2608
+ return {
2609
+ status: "error",
2610
+ error: options.commandError
2611
+ };
2612
+ }
2613
+ if (options.credentialsFileError !== void 0) {
2614
+ return {
2615
+ status: "error",
2616
+ result: options.result,
2617
+ error: options.credentialsFileError
2618
+ };
2619
+ }
2620
+ if (options.result?.completed) {
2621
+ return {
2622
+ status: "success",
2623
+ result: options.result
2624
+ };
2625
+ }
2626
+ return {
2627
+ status: "error",
2628
+ result: options.result,
2629
+ error: buildCommandArtifactError(
2630
+ "OAUTH_LOGIN_INCOMPLETE",
2631
+ options.result?.error?.message ?? "OAuth login did not complete."
2632
+ )
2633
+ };
2634
+ }
1359
2635
  function registerOAuthCommands(program) {
1360
2636
  const oauth = program.command("oauth").description("Run MCP OAuth login, proxy, and conformance flows");
1361
- oauth.command("login").description("Run an OAuth login flow against an HTTP MCP server").requiredOption("--url <url>", "MCP server URL").requiredOption(
2637
+ oauth.command("login").description("Run an OAuth login flow against an HTTP MCP server").requiredOption("--url <url>", "MCP server URL").option(
1362
2638
  "--protocol-version <version>",
1363
- "OAuth protocol version: 2025-03-26, 2025-06-18, or 2025-11-25"
1364
- ).requiredOption(
2639
+ "OAuth protocol override: 2025-03-26, 2025-06-18, or 2025-11-25"
2640
+ ).option(
1365
2641
  "--registration <strategy>",
1366
- "Registration strategy: dcr, preregistered, or cimd"
2642
+ "Registration override: dcr, preregistered, or cimd"
1367
2643
  ).option(
1368
2644
  "--auth-mode <mode>",
1369
2645
  "Authorization mode: headless, interactive, or client_credentials",
@@ -1390,16 +2666,20 @@ function registerOAuthCommands(program) {
1390
2666
  ).option(
1391
2667
  "--debug-out <path>",
1392
2668
  "Write a structured debug artifact to a file"
2669
+ ).option(
2670
+ "--credentials-out <path>",
2671
+ "Write OAuth credentials to <path> (mode 0600); stdout output has secret fields redacted to [SAVED_TO_FILE]"
1393
2672
  ).action(async (options, command) => {
1394
- const format = getStructuredOAuthFormat(command);
1395
- const config = buildOAuthConformanceConfig(
2673
+ const globalOptions = getGlobalOptions(command);
2674
+ const format = getOAuthFormat(command);
2675
+ const config = buildOAuthLoginConfig(
1396
2676
  options,
1397
2677
  {
1398
2678
  defaultAuthMode: "interactive"
1399
2679
  }
1400
2680
  );
1401
2681
  const snapshotCollector = options.debugOut ? createCliRpcLogCollector({ __cli__: config.serverUrl }) : void 0;
1402
- const isTTY = process.stderr.isTTY;
2682
+ const isTTY = process.stderr.isTTY && !globalOptions.quiet;
1403
2683
  if (isTTY) {
1404
2684
  config.onProgress = (message) => {
1405
2685
  process.stderr.write(`\r\x1B[K${message}`);
@@ -1408,7 +2688,7 @@ function registerOAuthCommands(program) {
1408
2688
  let result;
1409
2689
  let commandError;
1410
2690
  try {
1411
- result = await sdk.runOAuthLogin(config);
2691
+ result = await runOAuthLogin(config);
1412
2692
  } catch (error) {
1413
2693
  commandError = error;
1414
2694
  } finally {
@@ -1421,28 +2701,32 @@ function registerOAuthCommands(program) {
1421
2701
  config.serverUrl,
1422
2702
  snapshotConfig
1423
2703
  );
2704
+ let credentialsFilePath;
2705
+ let credentialsFileError;
2706
+ if (commandError === void 0 && result && options.credentialsOut && hasCredentialsToSave(result)) {
2707
+ try {
2708
+ credentialsFilePath = await writeCredentialsFile(
2709
+ options.credentialsOut,
2710
+ result
2711
+ );
2712
+ } catch (error) {
2713
+ credentialsFileError = error;
2714
+ }
2715
+ }
1424
2716
  await writeCommandDebugArtifact({
1425
2717
  outputPath: options.debugOut,
1426
2718
  format,
2719
+ quiet: globalOptions.quiet,
1427
2720
  commandName: "oauth login",
1428
2721
  commandInput: summarizeOAuthLoginCommandInput(
1429
2722
  options
1430
2723
  ),
1431
2724
  target,
1432
- outcome: commandError ? {
1433
- status: "error",
1434
- error: commandError
1435
- } : result?.completed ? {
1436
- status: "success",
1437
- result
1438
- } : {
1439
- status: "error",
2725
+ outcome: buildOAuthLoginDebugOutcome({
2726
+ commandError,
1440
2727
  result,
1441
- error: buildCommandArtifactError(
1442
- "OAUTH_LOGIN_INCOMPLETE",
1443
- result?.error?.message ?? "OAuth login did not complete."
1444
- )
1445
- },
2728
+ credentialsFileError
2729
+ }),
1446
2730
  snapshot: options.debugOut ? {
1447
2731
  input: {
1448
2732
  config: snapshotConfig,
@@ -1458,7 +2742,17 @@ function registerOAuthCommands(program) {
1458
2742
  if (!result) {
1459
2743
  throw cliError("INTERNAL_ERROR", "OAuth login did not return a result.");
1460
2744
  }
1461
- writeResult(result, format);
2745
+ if (options.credentialsOut) {
2746
+ writeResult(
2747
+ redactCredentialsFromResult(result, credentialsFilePath),
2748
+ format
2749
+ );
2750
+ if (credentialsFileError) {
2751
+ throw credentialsFileError;
2752
+ }
2753
+ } else {
2754
+ writeResult(result, format);
2755
+ }
1462
2756
  if (!result.completed) {
1463
2757
  setProcessExitCode(1);
1464
2758
  }
@@ -1498,11 +2792,17 @@ function registerOAuthCommands(program) {
1498
2792
  ).option(
1499
2793
  "--print-url",
1500
2794
  "In interactive mode, print the consent URL to stderr instead of launching a browser"
2795
+ ).option(
2796
+ "--reporter <reporter>",
2797
+ "Structured reporter output: json-summary or junit-xml"
1501
2798
  ).action(async (options, command) => {
1502
- const format = getOAuthFormat(command);
2799
+ const reporter = parseReporterFormat(options.reporter);
2800
+ const format = getOAuthConformanceFormat(command, reporter);
1503
2801
  const config = buildOAuthConformanceConfig(options);
1504
- const result = await new sdk.OAuthConformanceTest(config).run();
1505
- writeOAuthOutput(renderOAuthConformanceResult(result, format));
2802
+ const result = await new OAuthConformanceTest(config).run();
2803
+ writeOAuthOutput(
2804
+ reporter ? renderConformanceReporterResult(result, reporter) : renderOAuthConformanceResult(result, format)
2805
+ );
1506
2806
  if (!result.passed) {
1507
2807
  setProcessExitCode(1);
1508
2808
  }
@@ -1515,9 +2815,13 @@ function registerOAuthCommands(program) {
1515
2815
  ).option(
1516
2816
  "--verify-call-tool <name>",
1517
2817
  "Also call the named tool after listing"
2818
+ ).option(
2819
+ "--reporter <reporter>",
2820
+ "Structured reporter output: json-summary or junit-xml"
1518
2821
  ).action(async (options, command) => {
1519
- const format = getOAuthFormat(command);
1520
- const config = loadSuiteConfig(options.config);
2822
+ const reporter = parseReporterFormat(options.reporter);
2823
+ const format = getOAuthConformanceFormat(command, reporter);
2824
+ const config = loadOAuthSuiteConfig(options.config);
1521
2825
  if (options.verifyTools || options.verifyCallTool) {
1522
2826
  const cliVerification = {
1523
2827
  listTools: true,
@@ -1531,43 +2835,56 @@ function registerOAuthCommands(program) {
1531
2835
  verification: { ...config.defaults?.verification, ...cliVerification }
1532
2836
  };
1533
2837
  }
1534
- const suite = new sdk.OAuthConformanceSuite(config);
2838
+ const suite = new OAuthConformanceSuite(config);
1535
2839
  const result = await suite.run();
1536
- writeOAuthOutput(renderOAuthConformanceSuiteResult(result, format));
2840
+ writeOAuthOutput(
2841
+ reporter ? renderConformanceReporterResult(result, reporter) : renderOAuthConformanceSuiteResult(result, format)
2842
+ );
1537
2843
  if (!result.passed) {
1538
2844
  setProcessExitCode(1);
1539
2845
  }
1540
2846
  });
1541
2847
  oauth.command("metadata").description("Fetch OAuth metadata from a URL").requiredOption("--url <url>", "OAuth metadata URL").action(async (options, command) => {
2848
+ const format = getOAuthFormat(command);
1542
2849
  const result = await runOAuthMetadata(options.url);
1543
- writeResult(result, getStructuredOAuthFormat(command));
2850
+ writeResult(result, format);
1544
2851
  });
1545
2852
  oauth.command("proxy").description("Proxy an OAuth request with hosted-mode safety checks").requiredOption("--url <url>", "OAuth request URL").option("--method <method>", "HTTP method", "GET").option(
1546
2853
  "--header <header>",
1547
2854
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
1548
2855
  (value, previous = []) => [...previous, value],
1549
2856
  []
1550
- ).option("--body <value>", "Request body as JSON or raw string").action(async (options, command) => {
2857
+ ).option(
2858
+ "--body <value>",
2859
+ "Request body as JSON, raw string, @path, or - for stdin"
2860
+ ).action(async (options, command) => {
2861
+ const format = getOAuthFormat(command);
1551
2862
  const result = await runOAuthProxy(options);
1552
- writeResult(result, getStructuredOAuthFormat(command));
2863
+ writeResult(result, format);
1553
2864
  });
1554
2865
  oauth.command("debug-proxy").description("Proxy an OAuth debug request with hosted-mode safety checks").requiredOption("--url <url>", "OAuth request URL").option("--method <method>", "HTTP method", "GET").option(
1555
2866
  "--header <header>",
1556
2867
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
1557
2868
  (value, previous = []) => [...previous, value],
1558
2869
  []
1559
- ).option("--body <value>", "Request body as JSON or raw string").action(async (options, command) => {
2870
+ ).option(
2871
+ "--body <value>",
2872
+ "Request body as JSON, raw string, @path, or - for stdin"
2873
+ ).action(async (options, command) => {
2874
+ const format = getOAuthFormat(command);
1560
2875
  const result = await runOAuthDebugProxy(
1561
2876
  options
1562
2877
  );
1563
- writeResult(result, getStructuredOAuthFormat(command));
2878
+ writeResult(result, format);
1564
2879
  });
1565
2880
  }
1566
2881
  function buildOAuthConformanceConfig(options, defaults) {
1567
2882
  const serverUrl = options.url.trim();
1568
2883
  assertValidUrl2(serverUrl, "server URL");
1569
- const protocolVersion = parseProtocolVersion(options.protocolVersion);
1570
- const registrationStrategy = parseRegistrationStrategy(options.registration);
2884
+ const protocolVersion = parseRequiredProtocolVersion(options.protocolVersion);
2885
+ const registrationStrategy = parseRequiredRegistrationStrategy(
2886
+ options.registration
2887
+ );
1571
2888
  const authMode = parseAuthMode(
1572
2889
  options.authMode ?? defaults?.defaultAuthMode ?? "interactive"
1573
2890
  );
@@ -1642,9 +2959,97 @@ function buildOAuthConformanceConfig(options, defaults) {
1642
2959
  oauthConformanceChecks: options.conformanceChecks ?? false
1643
2960
  };
1644
2961
  }
2962
+ function buildOAuthLoginConfig(options, defaults) {
2963
+ const serverUrl = options.url.trim();
2964
+ assertValidUrl2(serverUrl, "server URL");
2965
+ const protocolVersion = options.protocolVersion ? parseProtocolVersion(options.protocolVersion) : void 0;
2966
+ const registrationStrategy = options.registration ? parseRegistrationStrategy(options.registration) : void 0;
2967
+ const authMode = parseAuthMode(
2968
+ options.authMode ?? defaults?.defaultAuthMode ?? "interactive"
2969
+ );
2970
+ if (options.printUrl && authMode !== "interactive") {
2971
+ throw usageError(
2972
+ "--print-url only applies to --auth-mode interactive. Headless and client_credentials modes do not open a browser."
2973
+ );
2974
+ }
2975
+ if (protocolVersion !== void 0 && registrationStrategy === "cimd" && protocolVersion !== "2025-11-25") {
2976
+ throw usageError(
2977
+ `CIMD registration is not supported for protocol version ${protocolVersion}.`
2978
+ );
2979
+ }
2980
+ if (authMode === "client_credentials" && registrationStrategy === "cimd") {
2981
+ throw usageError(
2982
+ "--auth-mode client_credentials cannot be used with --registration cimd. CIMD is a browser-based registration flow and only works with --auth-mode headless or --auth-mode interactive. For client_credentials, use --registration dcr or --registration preregistered instead."
2983
+ );
2984
+ }
2985
+ const clientId = options.clientId?.trim();
2986
+ const clientSecret = options.clientSecret;
2987
+ const clientMetadataUrl = options.clientMetadataUrl?.trim();
2988
+ const redirectUrl = options.redirectUrl?.trim();
2989
+ if (registrationStrategy === "preregistered" && !clientId) {
2990
+ throw usageError(
2991
+ "--client-id is required when --registration preregistered is used."
2992
+ );
2993
+ }
2994
+ if (registrationStrategy === "preregistered" && authMode === "client_credentials" && !clientSecret) {
2995
+ throw usageError(
2996
+ "--client-secret is required for preregistered client_credentials runs."
2997
+ );
2998
+ }
2999
+ if (clientMetadataUrl) {
3000
+ assertValidUrl2(clientMetadataUrl, "client metadata URL");
3001
+ }
3002
+ if (redirectUrl) {
3003
+ assertValidUrl2(redirectUrl, "redirect URL");
3004
+ }
3005
+ const customHeaders = parseHeadersOption(options.header);
3006
+ const client = {};
3007
+ if (clientId) {
3008
+ client.preregistered = {
3009
+ clientId,
3010
+ ...clientSecret ? { clientSecret } : {}
3011
+ };
3012
+ }
3013
+ if (clientMetadataUrl) {
3014
+ client.clientIdMetadataUrl = clientMetadataUrl;
3015
+ }
3016
+ const verification = options.verifyTools || options.verifyCallTool ? {
3017
+ listTools: options.verifyTools ?? !!options.verifyCallTool,
3018
+ ...options.verifyCallTool ? { callTool: { name: options.verifyCallTool } } : {}
3019
+ } : void 0;
3020
+ const auth = buildAuthConfig(
3021
+ authMode,
3022
+ registrationStrategy ?? "dcr",
3023
+ clientId,
3024
+ clientSecret
3025
+ );
3026
+ if (options.printUrl && auth.mode === "interactive") {
3027
+ auth.openUrl = async (url) => {
3028
+ process.stderr.write(`OAUTH_CONSENT_URL: ${url}
3029
+ `);
3030
+ };
3031
+ }
3032
+ return {
3033
+ serverUrl,
3034
+ ...protocolVersion ? { protocolVersion } : {},
3035
+ ...registrationStrategy ? { registrationStrategy } : {},
3036
+ protocolMode: protocolVersion ?? "auto",
3037
+ registrationMode: registrationStrategy ?? "auto",
3038
+ auth,
3039
+ client,
3040
+ scopes: options.scopes?.trim() || void 0,
3041
+ customHeaders,
3042
+ redirectUrl,
3043
+ stepTimeout: options.stepTimeout ?? 3e4,
3044
+ verification,
3045
+ oauthConformanceChecks: false
3046
+ };
3047
+ }
1645
3048
  function summarizeOAuthLoginCommandInput(options) {
1646
3049
  return {
1647
3050
  serverUrl: options.url.trim(),
3051
+ protocolMode: options.protocolVersion ?? "auto",
3052
+ registrationMode: options.registration ?? "auto",
1648
3053
  protocolVersion: options.protocolVersion,
1649
3054
  registration: options.registration,
1650
3055
  authMode: options.authMode ?? "interactive",
@@ -1717,6 +3122,14 @@ function parseProtocolVersion(value) {
1717
3122
  `Invalid protocol version "${value}". Use ${[...VALID_PROTOCOL_VERSIONS].join(", ")}.`
1718
3123
  );
1719
3124
  }
3125
+ function parseRequiredProtocolVersion(value) {
3126
+ if (!value) {
3127
+ throw usageError(
3128
+ "--protocol-version is required for oauth conformance flows."
3129
+ );
3130
+ }
3131
+ return parseProtocolVersion(value);
3132
+ }
1720
3133
  function parseRegistrationStrategy(value) {
1721
3134
  if (VALID_REGISTRATION_STRATEGIES.has(value)) {
1722
3135
  return value;
@@ -1725,6 +3138,14 @@ function parseRegistrationStrategy(value) {
1725
3138
  `Invalid registration strategy "${value}". Use ${[...VALID_REGISTRATION_STRATEGIES].join(", ")}.`
1726
3139
  );
1727
3140
  }
3141
+ function parseRequiredRegistrationStrategy(value) {
3142
+ if (!value) {
3143
+ throw usageError(
3144
+ "--registration is required for oauth conformance flows."
3145
+ );
3146
+ }
3147
+ return parseRegistrationStrategy(value);
3148
+ }
1728
3149
  function parseAuthMode(value) {
1729
3150
  if (VALID_AUTH_MODES.has(value)) {
1730
3151
  return value;
@@ -1735,7 +3156,7 @@ function parseAuthMode(value) {
1735
3156
  }
1736
3157
  async function runOAuthMetadata(url) {
1737
3158
  try {
1738
- const result = await sdk.fetchOAuthMetadata(url, true);
3159
+ const result = await fetchOAuthMetadata(url, true);
1739
3160
  if ("status" in result && result.status !== void 0) {
1740
3161
  throw cliError(
1741
3162
  statusToErrorCode(result.status),
@@ -1749,7 +3170,7 @@ async function runOAuthMetadata(url) {
1749
3170
  }
1750
3171
  async function runOAuthProxy(options) {
1751
3172
  try {
1752
- return await sdk.executeOAuthProxy({
3173
+ return await executeOAuthProxy({
1753
3174
  url: options.url,
1754
3175
  method: options.method,
1755
3176
  headers: parseHeadersOption(options.header),
@@ -1762,7 +3183,7 @@ async function runOAuthProxy(options) {
1762
3183
  }
1763
3184
  async function runOAuthDebugProxy(options) {
1764
3185
  try {
1765
- return await sdk.executeDebugOAuthProxy({
3186
+ return await executeDebugOAuthProxy({
1766
3187
  url: options.url,
1767
3188
  method: options.method,
1768
3189
  headers: parseHeadersOption(options.header),
@@ -1777,14 +3198,15 @@ function parseProxyBody(value) {
1777
3198
  if (value === void 0) {
1778
3199
  return void 0;
1779
3200
  }
3201
+ const source = readInputSource(value, "Request body");
1780
3202
  try {
1781
- return JSON.parse(value);
3203
+ return JSON.parse(source);
1782
3204
  } catch {
1783
- return value;
3205
+ return source;
1784
3206
  }
1785
3207
  }
1786
3208
  function mapOAuthProxyError(error) {
1787
- if (error instanceof sdk.OAuthProxyError) {
3209
+ if (error instanceof OAuthProxyError) {
1788
3210
  return cliError(statusToErrorCode(error.status), error.message);
1789
3211
  }
1790
3212
  return error;
@@ -1816,7 +3238,7 @@ function registerPromptCommands(program) {
1816
3238
  });
1817
3239
  const result = await withEphemeralManager(
1818
3240
  config,
1819
- (manager, serverId) => sdk.listPrompts(manager, { serverId, cursor: options.cursor }),
3241
+ (manager, serverId) => listPrompts(manager, { serverId, cursor: options.cursor }),
1820
3242
  {
1821
3243
  timeout: globalOptions.timeout,
1822
3244
  rpcLogger: collector?.rpcLogger,
@@ -1830,7 +3252,10 @@ function registerPromptCommands(program) {
1830
3252
  });
1831
3253
  addRetryOptions(
1832
3254
  addSharedServerOptions(
1833
- prompts.command("get").description("Get a named prompt from an MCP server").option("--prompt-name <prompt>", "Prompt name").option("--name <prompt>", "Alias for --prompt-name").option("--prompt-args <json>", "Prompt arguments as a JSON object")
3255
+ prompts.command("get").description("Get a named prompt from an MCP server").option("--prompt-name <prompt>", "Prompt name").option("--name <prompt>", "Alias for --prompt-name").option(
3256
+ "--prompt-args <json>",
3257
+ "Prompt arguments as JSON, @path, or - for stdin"
3258
+ )
1834
3259
  )
1835
3260
  ).action(async (options, command) => {
1836
3261
  const globalOptions = getGlobalOptions(command);
@@ -1853,7 +3278,7 @@ function registerPromptCommands(program) {
1853
3278
  const promptArguments = parsePromptArguments(options.promptArgs);
1854
3279
  const result = await withEphemeralManager(
1855
3280
  config,
1856
- (manager, serverId) => sdk.getPrompt(manager, {
3281
+ (manager, serverId) => getPrompt(manager, {
1857
3282
  serverId,
1858
3283
  name: promptName,
1859
3284
  arguments: promptArguments
@@ -1887,7 +3312,7 @@ function registerResourcesCommands(program) {
1887
3312
  });
1888
3313
  const result = await withEphemeralManager(
1889
3314
  config,
1890
- (manager, serverId) => sdk.listResources(manager, { serverId, cursor: options.cursor }),
3315
+ (manager, serverId) => listResources(manager, { serverId, cursor: options.cursor }),
1891
3316
  {
1892
3317
  timeout: globalOptions.timeout,
1893
3318
  rpcLogger: collector?.rpcLogger,
@@ -1923,7 +3348,7 @@ function registerResourcesCommands(program) {
1923
3348
  });
1924
3349
  const result = await withEphemeralManager(
1925
3350
  config,
1926
- (manager, serverId) => sdk.readResource(manager, { serverId, uri: resourceUri }),
3351
+ (manager, serverId) => readResource(manager, { serverId, uri: resourceUri }),
1927
3352
  {
1928
3353
  timeout: globalOptions.timeout,
1929
3354
  rpcLogger: collector?.rpcLogger,
@@ -1964,48 +3389,8 @@ function registerResourcesCommands(program) {
1964
3389
  withRpcLogsIfRequested(result, collector, globalOptions),
1965
3390
  globalOptions.format
1966
3391
  );
1967
- });
1968
- }
1969
- function parseReporterFormat(value) {
1970
- if (value === void 0) {
1971
- return void 0;
1972
- }
1973
- if (value === "json-summary" || value === "junit-xml") {
1974
- return value;
1975
- }
1976
- throw usageError(
1977
- `Invalid reporter "${value}". Use "json-summary" or "junit-xml".`
1978
- );
1979
- }
1980
- function writeReporterResult(reporter, report) {
1981
- if (reporter === "junit-xml") {
1982
- process.stdout.write(sdk.renderStructuredRunJUnitXml(report));
1983
- return;
1984
- }
1985
- writeResult(sdk.renderStructuredRunJson(report), "json");
1986
- }
1987
- async function writeJsonArtifact(outputPath, payload) {
1988
- const resolvedPath = path__default.default.resolve(process.cwd(), outputPath);
1989
- try {
1990
- await promises.mkdir(path__default.default.dirname(resolvedPath), { recursive: true });
1991
- await promises.writeFile(
1992
- resolvedPath,
1993
- `${JSON.stringify(payload, null, 2)}
1994
- `,
1995
- "utf8"
1996
- );
1997
- } catch (error) {
1998
- throw operationalError(
1999
- `Failed to write JSON artifact to "${resolvedPath}".`,
2000
- {
2001
- source: error instanceof Error ? error.message : String(error)
2002
- }
2003
- );
2004
- }
2005
- return resolvedPath;
3392
+ });
2006
3393
  }
2007
-
2008
- // src/commands/server.ts
2009
3394
  function registerServerCommands(program) {
2010
3395
  const server = program.command("server").description("Inspect MCP server connectivity and capabilities");
2011
3396
  addRetryOptions(
@@ -2014,6 +3399,9 @@ function registerServerCommands(program) {
2014
3399
  ).requiredOption("--url <url>", "HTTP MCP server URL").option("--access-token <token>", "Bearer access token for HTTP servers").option(
2015
3400
  "--oauth-access-token <token>",
2016
3401
  "OAuth bearer access token for HTTP servers"
3402
+ ).option(
3403
+ "--credentials-file <path>",
3404
+ "Load OAuth access token from a file created by oauth login --credentials-out"
2017
3405
  ).option(
2018
3406
  "--header <header>",
2019
3407
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
@@ -2021,7 +3409,7 @@ function registerServerCommands(program) {
2021
3409
  []
2022
3410
  ).option(
2023
3411
  "--client-capabilities <json>",
2024
- "Client capabilities advertised in the initialize probe as a JSON object"
3412
+ "Client capabilities as JSON, @path, or - for stdin"
2025
3413
  ).option(
2026
3414
  "--protocol-version <version>",
2027
3415
  "OAuth/MCP protocol version hint used for the initialize probe",
@@ -2038,8 +3426,10 @@ function registerServerCommands(program) {
2038
3426
  const globalOptions = getGlobalOptions(command);
2039
3427
  const retryPolicy = parseRetryPolicy(options);
2040
3428
  const protocolVersion = options.protocolVersion;
3429
+ const accessToken = resolveServerProbeAccessToken(options);
2041
3430
  const config = parseServerConfig({
2042
3431
  ...options,
3432
+ ...options.credentialsFile ? { accessToken, credentialsFile: void 0 } : {},
2043
3433
  timeout: options.timeout ?? globalOptions.timeout
2044
3434
  });
2045
3435
  const target = describeTarget(options);
@@ -2057,11 +3447,11 @@ function registerServerCommands(program) {
2057
3447
  if (!probeUrl) {
2058
3448
  throw usageError("HTTP probe requires --url.");
2059
3449
  }
2060
- result = await sdk.probeMcpServer({
3450
+ result = await probeMcpServer({
2061
3451
  url: probeUrl,
2062
3452
  protocolVersion,
2063
3453
  headers: parseHeadersOption(options.header),
2064
- accessToken: resolveHttpAccessToken(options),
3454
+ accessToken,
2065
3455
  clientCapabilities: "clientCapabilities" in config ? config.clientCapabilities : void 0,
2066
3456
  timeoutMs: options.timeout ?? globalOptions.timeout,
2067
3457
  retryPolicy
@@ -2072,6 +3462,7 @@ function registerServerCommands(program) {
2072
3462
  await writeCommandDebugArtifact({
2073
3463
  outputPath: options.debugOut,
2074
3464
  format: globalOptions.format,
3465
+ quiet: globalOptions.quiet,
2075
3466
  commandName: "server probe",
2076
3467
  commandInput: {
2077
3468
  protocolVersion,
@@ -2126,7 +3517,7 @@ function registerServerCommands(program) {
2126
3517
  timeout: globalOptions.timeout
2127
3518
  });
2128
3519
  const doctorTarget = summarizeServerDoctorTarget(target, config);
2129
- const result = await sdk.runServerDoctor({
3520
+ const result = await runServerDoctor({
2130
3521
  config,
2131
3522
  target: doctorTarget,
2132
3523
  timeout: globalOptions.timeout,
@@ -2223,6 +3614,7 @@ function registerServerCommands(program) {
2223
3614
  await writeCommandDebugArtifact({
2224
3615
  outputPath: options.debugOut,
2225
3616
  format: globalOptions.format,
3617
+ quiet: globalOptions.quiet,
2226
3618
  commandName: "server validate",
2227
3619
  commandInput: {},
2228
3620
  target: targetSummary,
@@ -2330,7 +3722,7 @@ function registerServerCommands(program) {
2330
3722
  ...options,
2331
3723
  timeout: globalOptions.timeout
2332
3724
  });
2333
- const snapshot = await sdk.collectServerSnapshot({
3725
+ const snapshot = await collectServerSnapshot({
2334
3726
  config,
2335
3727
  target,
2336
3728
  timeout: globalOptions.timeout,
@@ -2339,7 +3731,7 @@ function registerServerCommands(program) {
2339
3731
  clientName: "mcpjam",
2340
3732
  serverId: "__cli__"
2341
3733
  });
2342
- const result = options.stable ? sdk.serializeStableServerSnapshot(snapshot) : sdk.serializeServerSnapshot(snapshot, { mode: "raw" });
3734
+ const result = options.stable ? serializeStableServerSnapshot(snapshot) : serializeServerSnapshot(snapshot, { mode: "raw" });
2343
3735
  writeResult(
2344
3736
  options.stable ? result : withRpcLogsIfRequested(result, collector, globalOptions),
2345
3737
  globalOptions.format
@@ -2383,7 +3775,7 @@ function registerServerCommands(program) {
2383
3775
  timeout: globalOptions.timeout
2384
3776
  });
2385
3777
  const baselineSnapshot = await readSnapshotFile(mode.baselinePath);
2386
- const currentSnapshot = await sdk.collectServerSnapshot({
3778
+ const currentSnapshot = await collectServerSnapshot({
2387
3779
  config,
2388
3780
  target,
2389
3781
  timeout: globalOptions.timeout,
@@ -2419,7 +3811,7 @@ function registerServerCommands(program) {
2419
3811
  if (reporter) {
2420
3812
  writeReporterResult(
2421
3813
  reporter,
2422
- sdk.buildServerDiffReport(rawDiff, {
3814
+ buildServerDiffReport(rawDiff, {
2423
3815
  metadata: mode.kind === "baseline-live" ? {
2424
3816
  comparisonMode: mode.kind,
2425
3817
  baselinePath: mode.baselinePath
@@ -2441,6 +3833,17 @@ function registerServerCommands(program) {
2441
3833
  }
2442
3834
  });
2443
3835
  }
3836
+ function resolveServerProbeAccessToken(options) {
3837
+ assertNoCredentialsFileAuthConflicts(options);
3838
+ if (options.credentialsFile) {
3839
+ const url = options.url?.trim();
3840
+ if (!url) {
3841
+ throw usageError("--credentials-file requires --url.");
3842
+ }
3843
+ return resolveCredentialsFileAccessToken(options.credentialsFile, url);
3844
+ }
3845
+ return resolveHttpAccessToken(options);
3846
+ }
2444
3847
  function hasServerTargetOptions(options) {
2445
3848
  return typeof options.url === "string" || typeof options.command === "string";
2446
3849
  }
@@ -2489,7 +3892,7 @@ function parseDiffFailOn(value) {
2489
3892
  async function readSnapshotFile(filePath) {
2490
3893
  let contents;
2491
3894
  try {
2492
- contents = await promises.readFile(filePath, "utf8");
3895
+ contents = await readFile(filePath, "utf8");
2493
3896
  } catch (error) {
2494
3897
  throw operationalError(`Failed to read snapshot file "${filePath}".`, {
2495
3898
  source: error instanceof Error ? error.message : String(error)
@@ -2512,34 +3915,646 @@ function toOptionalString(value) {
2512
3915
  }
2513
3916
  function createServerDiffResult(left, right, failOn) {
2514
3917
  try {
2515
- return sdk.diffServerSnapshots(left, right, { failOn });
3918
+ return diffServerSnapshots(left, right, { failOn });
2516
3919
  } catch (error) {
2517
- if (error instanceof sdk.ServerSnapshotFormatError) {
3920
+ if (error instanceof ServerSnapshotFormatError) {
2518
3921
  throw usageError(error.message);
2519
3922
  }
2520
3923
  throw error;
2521
3924
  }
2522
3925
  }
2523
- async function listToolsWithMetadata(manager, params) {
2524
- const result = await manager.listTools(
2525
- params.serverId,
2526
- params.cursor ? { cursor: params.cursor } : void 0
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
2527
4042
  );
2528
- const tools = result.tools ?? [];
2529
- const toolsMetadata = manager.getAllToolsMetadata(params.serverId);
2530
- const tokenCount = params.modelId ? estimateTokensFromChars(JSON.stringify(tools)) : void 0;
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
+ });
2531
4170
  return {
2532
- tools,
2533
- nextCursor: result.nextCursor,
2534
- toolsMetadata,
2535
- ...tokenCount === void 0 ? {} : { tokenCount }
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
2536
4177
  };
2537
4178
  }
2538
- function estimateTokensFromChars(text) {
2539
- return Math.ceil(text.length / 4);
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
+ }
2540
4512
  }
2541
4513
 
2542
- // src/commands/tools.ts
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
+ }
2543
4558
  function registerToolsCommands(program) {
2544
4559
  const tools = program.command("tools").description("List and invoke MCP server tools");
2545
4560
  addRetryOptions(
@@ -2574,7 +4589,10 @@ function registerToolsCommands(program) {
2574
4589
  );
2575
4590
  });
2576
4591
  addSharedServerOptions(
2577
- tools.command("call").description("Call an MCP tool").option("--tool-name <tool>", "Tool name").option("--name <tool>", "Alias for --tool-name").option("--tool-args <json>", "Tool parameter object as JSON").option("--params <json>", "Alias for --tool-args").option(
4592
+ tools.command("call").description("Call an MCP tool").option("--tool-name <tool>", "Tool name").option("--name <tool>", "Alias for --tool-name").option(
4593
+ "--tool-args <json>",
4594
+ "Tool parameter object as JSON, @path, or - for stdin"
4595
+ ).option("--params <json>", "Alias for --tool-args").option(
2578
4596
  "--validate-response",
2579
4597
  "Validate the MCP tool-call envelope returned by the server"
2580
4598
  ).option(
@@ -2643,6 +4661,7 @@ function registerToolsCommands(program) {
2643
4661
  await writeCommandDebugArtifact({
2644
4662
  outputPath: options.debugOut,
2645
4663
  format: globalOptions.format,
4664
+ quiet: globalOptions.quiet,
2646
4665
  commandName: "tools call",
2647
4666
  commandInput: {
2648
4667
  toolName,
@@ -2669,14 +4688,14 @@ function registerToolsCommands(program) {
2669
4688
  if (commandError) {
2670
4689
  throw commandError;
2671
4690
  }
2672
- const validationResult = shouldValidateResponse || shouldExpectSuccess ? sdk.validateToolCallResult(result, {
4691
+ const validationResult = shouldValidateResponse || shouldExpectSuccess ? validateToolCallResult(result, {
2673
4692
  envelope: shouldValidateResponse,
2674
4693
  outcome: shouldExpectSuccess ? { failOnIsError: true } : void 0
2675
4694
  }) : void 0;
2676
4695
  if (reporter) {
2677
4696
  writeReporterResult(
2678
4697
  reporter,
2679
- sdk.buildToolCallValidationReport(validationResult, {
4698
+ buildToolCallValidationReport(validationResult, {
2680
4699
  durationMs: Date.now() - startedAt,
2681
4700
  rawResult: result,
2682
4701
  metadata: {
@@ -2693,16 +4712,91 @@ function registerToolsCommands(program) {
2693
4712
  if (validationResult && !validationResult.passed) {
2694
4713
  setProcessExitCode(1);
2695
4714
  }
2696
- if (sdk.isCallToolResultError(result)) {
4715
+ if (isCallToolResultError(result)) {
2697
4716
  setProcessExitCode(1);
2698
4717
  }
2699
4718
  });
2700
4719
  }
2701
4720
 
4721
+ // src/commands/inspector.ts
4722
+ function addInspectorUrlOption(command) {
4723
+ return command.option("--inspector-url <url>", "Local Inspector base URL");
4724
+ }
4725
+ function resolveInspectorBaseUrl(options) {
4726
+ return normalizeInspectorBaseUrl(
4727
+ typeof options.inspectorUrl === "string" ? options.inspectorUrl : void 0
4728
+ );
4729
+ }
4730
+ function registerInspectorCommands(program) {
4731
+ const inspector = program.command("inspector").description("Start or attach to the local MCPJam Inspector");
4732
+ addInspectorUrlOption(
4733
+ inspector.command("open").description("Start or attach to the local Inspector and open the UI")
4734
+ ).option("--tab <tab>", "Open the Inspector on a specific tab").action(async (options, command) => {
4735
+ const globalOptions = getGlobalOptions(command);
4736
+ const baseUrl = resolveInspectorBaseUrl(options);
4737
+ const tab = typeof options.tab === "string" && options.tab.trim().length > 0 ? options.tab.trim() : void 0;
4738
+ const result = await ensureInspector({
4739
+ baseUrl,
4740
+ openBrowser: true,
4741
+ startIfNeeded: true,
4742
+ tab,
4743
+ timeoutMs: globalOptions.timeout
4744
+ });
4745
+ writeResult(
4746
+ {
4747
+ success: true,
4748
+ started: result.started,
4749
+ baseUrl: result.baseUrl,
4750
+ url: buildInspectorUrl(result.baseUrl, tab),
4751
+ ...tab ? { tab } : {}
4752
+ },
4753
+ globalOptions.format
4754
+ );
4755
+ });
4756
+ addInspectorUrlOption(
4757
+ inspector.command("start").description(
4758
+ "Start the local Inspector in the background without opening a browser"
4759
+ )
4760
+ ).action(async (options, command) => {
4761
+ const globalOptions = getGlobalOptions(command);
4762
+ const baseUrl = resolveInspectorBaseUrl(options);
4763
+ const result = await ensureInspector({
4764
+ baseUrl,
4765
+ openBrowser: false,
4766
+ startIfNeeded: true,
4767
+ timeoutMs: globalOptions.timeout
4768
+ });
4769
+ writeResult(
4770
+ {
4771
+ success: true,
4772
+ started: result.started,
4773
+ baseUrl: result.baseUrl
4774
+ },
4775
+ globalOptions.format
4776
+ );
4777
+ });
4778
+ addInspectorUrlOption(
4779
+ inspector.command("stop").description("Stop the local Inspector if it is running")
4780
+ ).action(async (options, command) => {
4781
+ const globalOptions = getGlobalOptions(command);
4782
+ const baseUrl = resolveInspectorBaseUrl(options);
4783
+ const result = await stopInspector(baseUrl);
4784
+ writeResult(
4785
+ {
4786
+ success: true,
4787
+ stopped: result.stopped,
4788
+ baseUrl: result.baseUrl
4789
+ },
4790
+ globalOptions.format
4791
+ );
4792
+ });
4793
+ }
4794
+
2702
4795
  // src/index.ts
2703
- async function main(argv = process.argv) {
4796
+ var pkgVersion = package_default.version;
4797
+ async function main(argv = process.argv, dependencies = {}) {
2704
4798
  const program = addGlobalOptions(
2705
- new commander.Command().name("mcpjam").version(version, "-v, --version", "output the CLI version").description(
4799
+ new Command().name("mcpjam").version(pkgVersion, "-v, --version", "output the CLI version").description(
2706
4800
  "Test, debug, and validate MCP servers. Health checks, OAuth conformance, tool-surface diffing, and structured triage from the terminal or CI."
2707
4801
  ).allowExcessArguments(false).exitOverride().configureOutput({
2708
4802
  writeOut: (value) => process.stdout.write(value),
@@ -2710,6 +4804,7 @@ async function main(argv = process.argv) {
2710
4804
  }
2711
4805
  })
2712
4806
  );
4807
+ const telemetry = initTelemetry(program, pkgVersion, dependencies.telemetry);
2713
4808
  registerServerCommands(program);
2714
4809
  registerToolsCommands(program);
2715
4810
  registerResourcesCommands(program);
@@ -2717,33 +4812,82 @@ async function main(argv = process.argv) {
2717
4812
  registerAppsCommands(program);
2718
4813
  registerOAuthCommands(program);
2719
4814
  registerProtocolCommands(program);
4815
+ registerInspectorCommands(program);
4816
+ registerTelemetryCommands(program, dependencies.telemetry);
2720
4817
  if (argv.length <= 2) {
2721
4818
  program.outputHelp();
2722
- return 0;
4819
+ return {
4820
+ exitCode: 0,
4821
+ shouldCheckForUpdates: false
4822
+ };
2723
4823
  }
2724
4824
  try {
2725
4825
  await program.parseAsync(argv);
2726
- const exitCode = process.exitCode;
2727
- if (typeof exitCode === "number") {
2728
- return exitCode;
2729
- }
2730
- return Number(exitCode ?? 0) || 0;
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();
4832
+ return {
4833
+ exitCode: normalizedExitCode,
4834
+ shouldCheckForUpdates: true
4835
+ };
2731
4836
  } catch (error) {
2732
4837
  const format = detectOutputFormatFromArgv(argv);
2733
- if (error instanceof commander.CommanderError) {
4838
+ if (error instanceof CommanderError) {
2734
4839
  if (error.code === "commander.helpDisplayed" || error.code === "commander.version") {
2735
- return 0;
4840
+ await telemetry.flush();
4841
+ return {
4842
+ exitCode: 0,
4843
+ shouldCheckForUpdates: false
4844
+ };
2736
4845
  }
2737
4846
  writeError(usageError(error.message), format);
2738
- return 2;
4847
+ captureCommandEvent(2, "USAGE_ERROR");
4848
+ await telemetry.flush();
4849
+ return {
4850
+ exitCode: 2,
4851
+ shouldCheckForUpdates: false
4852
+ };
2739
4853
  }
2740
4854
  const normalizedError = normalizeCliError(error);
2741
4855
  writeError(normalizedError, format);
2742
- return normalizedError.exitCode;
4856
+ captureCommandEvent(normalizedError.exitCode, normalizedError.code);
4857
+ await telemetry.flush();
4858
+ return {
4859
+ exitCode: normalizedError.exitCode,
4860
+ shouldCheckForUpdates: false
4861
+ };
2743
4862
  }
2744
4863
  }
2745
- void main().then((exitCode) => {
2746
- process.exitCode = exitCode;
2747
- });
4864
+ async function runCliEntrypoint(argv = process.argv, dependencies = {}) {
4865
+ const result = await main(argv, dependencies);
4866
+ process.exitCode = result.exitCode;
4867
+ if (result.exitCode === 0 && result.shouldCheckForUpdates) {
4868
+ (dependencies.checkForUpdates ?? checkForUpdates)(pkgVersion);
4869
+ }
4870
+ return result;
4871
+ }
4872
+ function isDirectRun(importMetaUrl, argv = process.argv) {
4873
+ const entrypoint = argv[1];
4874
+ if (!entrypoint) {
4875
+ return false;
4876
+ }
4877
+ const entrypointUrl = pathToFileURL(entrypoint).href;
4878
+ if (importMetaUrl === entrypointUrl) {
4879
+ return true;
4880
+ }
4881
+ try {
4882
+ return importMetaUrl === pathToFileURL(realpathSync(entrypoint)).href;
4883
+ } catch {
4884
+ return false;
4885
+ }
4886
+ }
4887
+ if (isDirectRun(import.meta.url)) {
4888
+ void runCliEntrypoint();
4889
+ }
4890
+
4891
+ export { isDirectRun, main, runCliEntrypoint };
2748
4892
  //# sourceMappingURL=index.js.map
2749
4893
  //# sourceMappingURL=index.js.map