@mcpjam/cli 2.0.1 → 2.1.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
@@ -12,7 +12,7 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
12
  var path__default = /*#__PURE__*/_interopDefault(path);
13
13
 
14
14
  // package.json
15
- var version = "2.0.1";
15
+ var version = "2.1.0";
16
16
 
17
17
  // src/lib/output.ts
18
18
  var DEFAULT_OUTPUT_FORMAT = "json";
@@ -233,51 +233,16 @@ async function withEphemeralManager(config, fn, options) {
233
233
  serverId: "__cli__",
234
234
  clientName: "mcpjam",
235
235
  timeout: options?.timeout ?? 3e4,
236
- rpcLogger: options?.rpcLogger
236
+ rpcLogger: options?.rpcLogger,
237
+ retryPolicy: options?.retryPolicy
237
238
  });
238
239
  }
239
240
 
240
- // src/lib/redaction.ts
241
- function redactSensitiveValue(value) {
242
- if (Array.isArray(value)) {
243
- return value.map((entry) => redactSensitiveValue(entry));
244
- }
245
- if (!value || typeof value !== "object") {
246
- return typeof value === "string" ? redactSensitiveString(value) : value;
247
- }
248
- return Object.fromEntries(
249
- Object.entries(value).map(([key, entryValue]) => [
250
- key,
251
- shouldRedactKey(key) ? "[REDACTED]" : redactSensitiveValue(entryValue)
252
- ])
253
- );
254
- }
255
- function redactSensitiveString(value) {
256
- return value.replace(
257
- /\b(authorization|proxy-authorization|cookie|set-cookie)\s*:\s*[^\r\n]*/giu,
258
- (_match, headerName) => `${headerName}: [REDACTED]`
259
- ).replace(
260
- /\bBearer\s+(?![A-Za-z_][A-Za-z0-9_-]*=)([A-Za-z0-9\-._~+/]+=*)/giu,
261
- "Bearer [REDACTED]"
262
- ).replace(
263
- /\b(access_token|refresh_token|client_secret|id_token|code|code_verifier|accessToken|refreshToken|clientSecret|idToken|codeVerifier)=([^&\s]+)/giu,
264
- "$1=[REDACTED]"
265
- ).replace(
266
- /(["']?(?:access_token|refresh_token|client_secret|id_token|code|code_verifier|accessToken|refreshToken|clientSecret|idToken|codeVerifier)["']?\s*:\s*["'])[^"']*(["'])/giu,
267
- "$1[REDACTED]$2"
268
- );
269
- }
270
- function shouldRedactKey(key) {
271
- const normalized = key.toLowerCase().replace(/[^a-z0-9]/gu, "");
272
- return normalized === "authorization" || normalized === "proxyauthorization" || normalized === "cookie" || normalized === "setcookie" || normalized === "accesstoken" || normalized === "refreshtoken" || normalized === "clientsecret" || normalized === "idtoken" || normalized === "apikey" || normalized === "xapikey";
273
- }
274
-
275
241
  // src/lib/rpc-logs.ts
276
242
  var CliRpcLogCollector = class {
277
243
  constructor(serverNamesById) {
278
244
  this.serverNamesById = serverNamesById;
279
245
  }
280
- serverNamesById;
281
246
  logs = [];
282
247
  rpcLogger = ({ direction, message, serverId }) => {
283
248
  this.logs.push({
@@ -313,7 +278,7 @@ function getCliRpcLogEvents(collectors) {
313
278
  function redactCliRpcLogs(logs) {
314
279
  return logs.map((event) => ({
315
280
  ...event,
316
- message: redactSensitiveValue(event.message)
281
+ message: sdk.redactSensitiveValue(event.message)
317
282
  }));
318
283
  }
319
284
 
@@ -326,20 +291,21 @@ function withRpcLogsIfRequested(value, collector, options) {
326
291
  }
327
292
 
328
293
  // src/lib/server-config.ts
294
+ var DEFAULT_CLI_RETRY_POLICY = {
295
+ retries: 0,
296
+ retryDelayMs: 3e3
297
+ };
329
298
  function collectString(value, previous = []) {
330
299
  return [...previous, value];
331
300
  }
332
301
  function addSharedServerOptions(command) {
333
- return command.option("--url <url>", "HTTP MCP server URL").option("--access-token <token>", "Bearer access token for HTTP servers").option(
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(
334
306
  "--oauth-access-token <token>",
335
307
  "OAuth bearer access token for HTTP servers"
336
- ).option(
337
- "--refresh-token <token>",
338
- "OAuth refresh token for HTTP servers"
339
- ).option(
340
- "--client-id <id>",
341
- "OAuth client ID used with --refresh-token"
342
- ).option(
308
+ ).option("--refresh-token <token>", "OAuth refresh token for HTTP servers").option("--client-id <id>", "OAuth client ID used with --refresh-token").option(
343
309
  "--client-secret <secret>",
344
310
  "OAuth client secret used with --refresh-token"
345
311
  ).option(
@@ -351,19 +317,24 @@ function addSharedServerOptions(command) {
351
317
  "--client-capabilities <json>",
352
318
  "Client capabilities advertised to the server as a JSON object"
353
319
  ).option("--command <command>", "Command for a stdio MCP server").option(
320
+ "--args <arg...>",
321
+ "Preferred stdio command arguments. Pass multiple values or repeat the flag."
322
+ ).option(
354
323
  "--command-args <arg>",
355
- "Stdio command argument. Repeat to pass multiple arguments.",
324
+ "Legacy stdio command argument. Repeat to pass multiple arguments.",
356
325
  collectString
357
326
  ).option(
358
- "--env <env>",
359
- 'Stdio environment assignment in "KEY=VALUE" format. Repeat to pass multiple assignments.',
360
- collectString
361
- );
327
+ "-e, --env <env...>",
328
+ 'Stdio environment assignment in "KEY=VALUE" format. Pass multiple values or repeat the flag.'
329
+ ).option("--cwd <path>", "Working directory for the stdio MCP server process");
362
330
  }
363
331
  function getGlobalOptions(command) {
364
332
  const options = command.optsWithGlobals();
365
333
  return {
366
- format: resolveOutputFormat(options.format, process.stdout.isTTY),
334
+ format: resolveOutputFormat(
335
+ options.format,
336
+ process.stdout.isTTY
337
+ ),
367
338
  timeout: options.timeout ?? 3e4,
368
339
  rpc: options.rpc ?? false
369
340
  };
@@ -375,6 +346,37 @@ function parsePositiveInteger(value, label = "Value") {
375
346
  }
376
347
  return parsed;
377
348
  }
349
+ function parseNonNegativeInteger(value, label = "Value") {
350
+ const parsed = Number(value);
351
+ if (!Number.isInteger(parsed) || parsed < 0) {
352
+ throw usageError(`${label} must be a non-negative integer.`);
353
+ }
354
+ return parsed;
355
+ }
356
+ function addRetryOptions(command) {
357
+ return command.option(
358
+ "--retries <count>",
359
+ "Retry transient failures this many times",
360
+ (value) => parseNonNegativeInteger(value, "Retries")
361
+ ).option(
362
+ "--retry-delay-ms <ms>",
363
+ "Fixed delay between retries in milliseconds",
364
+ (value) => parseNonNegativeInteger(value, "Retry delay")
365
+ );
366
+ }
367
+ function parseRetryPolicy(options = {}) {
368
+ if (options.retries === void 0 && options.retryDelayMs === void 0) {
369
+ return void 0;
370
+ }
371
+ const retries = options.retries ?? DEFAULT_CLI_RETRY_POLICY.retries;
372
+ if (options.retryDelayMs !== void 0 && retries === 0) {
373
+ throw usageError("--retry-delay-ms requires --retries to be greater than 0.");
374
+ }
375
+ return {
376
+ retries,
377
+ retryDelayMs: options.retryDelayMs ?? DEFAULT_CLI_RETRY_POLICY.retryDelayMs
378
+ };
379
+ }
378
380
  function parseHeadersOption(headers) {
379
381
  if (!headers || headers.length === 0) {
380
382
  return void 0;
@@ -430,7 +432,9 @@ function resolveAliasedStringOption(options, aliases, label, config) {
430
432
  flag: alias.flag,
431
433
  value: normalized
432
434
  };
433
- }).filter((entry) => entry !== void 0);
435
+ }).filter(
436
+ (entry) => entry !== void 0
437
+ );
434
438
  const flagsText = aliases.map((alias) => alias.flag).join(" or ");
435
439
  if (provided.length === 0) {
436
440
  if (config?.required) {
@@ -449,16 +453,15 @@ function parseServerConfig(options) {
449
453
  const command = options.command?.trim();
450
454
  const hasUrl = Boolean(url);
451
455
  const hasCommand = Boolean(command);
456
+ const transport = resolveTargetTransport(options, hasUrl, hasCommand);
457
+ const cwd = options.cwd?.trim();
452
458
  const clientCapabilities = resolveClientCapabilities(
453
459
  options.clientCapabilities
454
460
  );
455
- if (hasUrl === hasCommand) {
456
- throw usageError("Specify exactly one target: either --url or --command.");
457
- }
458
- if (hasUrl && url) {
459
- if ((options.commandArgs?.length ?? 0) > 0 || (options.env?.length ?? 0) > 0) {
461
+ if (transport === "http" && url) {
462
+ if ((options.args?.length ?? 0) > 0 || (options.commandArgs?.length ?? 0) > 0 || (options.env?.length ?? 0) > 0 || cwd) {
460
463
  throw usageError(
461
- "--command-args and --env can only be used together with --command."
464
+ "--args, --command-args, --env, and --cwd can only be used together with --command."
462
465
  );
463
466
  }
464
467
  try {
@@ -505,10 +508,11 @@ function parseServerConfig(options) {
505
508
  }
506
509
  return {
507
510
  command,
508
- args: parseCommandArgs(options.commandArgs),
511
+ args: parseCommandArgs(options.args, options.commandArgs),
509
512
  env: parseEnvironmentOption(options.env),
513
+ ...cwd ? { cwd } : {},
510
514
  ...clientCapabilities ? { clientCapabilities } : {},
511
- stderr: "ignore",
515
+ stderr: "pipe",
512
516
  timeout: options.timeout
513
517
  };
514
518
  }
@@ -537,11 +541,12 @@ function parseHeader(entry) {
537
541
  }
538
542
  return [key, value];
539
543
  }
540
- function parseCommandArgs(values) {
541
- if (!values || values.length === 0) {
544
+ function parseCommandArgs(values, legacyValues) {
545
+ const combined = [...values ?? [], ...legacyValues ?? []];
546
+ if (combined.length === 0) {
542
547
  return void 0;
543
548
  }
544
- return values;
549
+ return combined;
545
550
  }
546
551
  function parseEnvironmentOption(values) {
547
552
  if (!values || values.length === 0) {
@@ -575,6 +580,42 @@ function resolveClientCapabilities(value) {
575
580
  }
576
581
  return parseUnknownRecord(value, "Client capabilities");
577
582
  }
583
+ function resolveTargetTransport(options, hasUrl, hasCommand) {
584
+ const transport = resolveTransportOption(options.transport);
585
+ if (!transport) {
586
+ if (hasUrl === hasCommand) {
587
+ throw usageError("Specify exactly one target: either --url or --command.");
588
+ }
589
+ return hasUrl ? "http" : "stdio";
590
+ }
591
+ if (transport === "http") {
592
+ if (!hasUrl) {
593
+ throw usageError("--transport http requires --url.");
594
+ }
595
+ if (hasCommand) {
596
+ throw usageError("--command can only be used with --transport stdio.");
597
+ }
598
+ return transport;
599
+ }
600
+ if (!hasCommand) {
601
+ throw usageError("--transport stdio requires --command.");
602
+ }
603
+ if (hasUrl) {
604
+ throw usageError("--url can only be used with --transport http.");
605
+ }
606
+ return transport;
607
+ }
608
+ function resolveTransportOption(value) {
609
+ if (value === void 0) {
610
+ return void 0;
611
+ }
612
+ if (value === "http" || value === "stdio") {
613
+ return value;
614
+ }
615
+ throw usageError(
616
+ `Invalid transport "${value}". Use "http" or "stdio".`
617
+ );
618
+ }
578
619
  function resolveHttpAccessToken(options) {
579
620
  const accessToken = options.accessToken?.trim();
580
621
  const oauthAccessToken = options.oauthAccessToken?.trim();
@@ -587,17 +628,70 @@ function resolveHttpAccessToken(options) {
587
628
  }
588
629
 
589
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
+ };
590
644
  function registerAppsCommands(program) {
591
- const apps = program.command("apps").description("Fetch MCP App and ChatGPT App widget content");
645
+ const apps = program.command("apps").description(
646
+ "MCP Apps utilities, widget extraction, and conformance checks"
647
+ );
592
648
  addSharedServerOptions(
593
- 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("--tool-id <id>", "Tool call id used for runtime injection").requiredOption("--tool-name <name>", "Tool name used for runtime injection").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(
594
- "--csp-mode <mode>",
595
- "CSP mode: permissive or widget-declared"
596
- ).option("--template <uri>", "Optional ui:// template override").option("--view-mode <mode>", "Widget view mode").option("--view-params <json>", "Widget view params as JSON")
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
+ )
597
660
  ).action(async (options, command) => {
598
661
  const globalOptions = getGlobalOptions(command);
599
662
  const target = describeTarget(options);
600
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
675
+ );
676
+ if (!result.passed) {
677
+ setProcessExitCode(1);
678
+ }
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;
601
695
  const resourceUri = resolveAliasedStringOption(
602
696
  options,
603
697
  [
@@ -627,21 +721,34 @@ function registerAppsCommands(program) {
627
721
  }),
628
722
  {
629
723
  timeout: globalOptions.timeout,
630
- rpcLogger: collector?.rpcLogger
724
+ rpcLogger: collector?.rpcLogger,
725
+ retryPolicy
631
726
  }
632
727
  );
633
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
728
+ writeResult(
729
+ withRpcLogsIfRequested(result, collector, globalOptions),
730
+ globalOptions.format
731
+ );
634
732
  });
635
- addSharedServerOptions(
636
- 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("--tool-id <id>", "Tool call id used for runtime injection").requiredOption("--tool-name <name>", "Tool name used for runtime injection").option("--tool-input <json>", "Tool input payload as JSON").option("--tool-output <json>", "Tool output payload as JSON").option(
637
- "--tool-response-metadata <json>",
638
- "Tool response metadata as a JSON object"
639
- ).option("--theme <theme>", "Widget theme: light or dark").option(
640
- "--csp-mode <mode>",
641
- "CSP mode: permissive or widget-declared"
642
- ).option("--locale <locale>", "Locale override").option("--device-type <type>", "Device type: mobile, tablet, or desktop")
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
+ )
643
749
  ).action(async (options, command) => {
644
750
  const globalOptions = getGlobalOptions(command);
751
+ const retryPolicy = parseRetryPolicy(options);
645
752
  const target = describeTarget(options);
646
753
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
647
754
  const resourceUri = resolveAliasedStringOption(
@@ -676,10 +783,14 @@ function registerAppsCommands(program) {
676
783
  }),
677
784
  {
678
785
  timeout: globalOptions.timeout,
679
- rpcLogger: collector?.rpcLogger
786
+ rpcLogger: collector?.rpcLogger,
787
+ retryPolicy
680
788
  }
681
789
  );
682
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
790
+ writeResult(
791
+ withRpcLogsIfRequested(result, collector, globalOptions),
792
+ globalOptions.format
793
+ );
683
794
  });
684
795
  }
685
796
  function parseJsonValue(value) {
@@ -725,6 +836,40 @@ function parseDeviceType(value) {
725
836
  `Invalid device type "${value}". Use "mobile", "tablet", or "desktop".`
726
837
  );
727
838
  }
839
+ function collectInvalidEntries(values, allowedValues) {
840
+ return (values ?? []).filter((value) => !allowedValues.includes(value));
841
+ }
842
+ function buildAppsConformanceConfig(options) {
843
+ const serverConfig = parseServerConfig(options);
844
+ const categories = options.category?.filter(Boolean);
845
+ const invalidCategories = collectInvalidEntries(
846
+ categories,
847
+ sdk.MCP_APPS_CHECK_CATEGORIES
848
+ );
849
+ if (invalidCategories.length > 0) {
850
+ throw usageError(
851
+ invalidCategories.length === 1 ? `Unknown category: ${invalidCategories[0]}` : `Unknown categories: ${invalidCategories.join(", ")}`
852
+ );
853
+ }
854
+ const checkIds = options.checkId?.filter(Boolean);
855
+ const invalidCheckIds = collectInvalidEntries(checkIds, sdk.MCP_APPS_CHECK_IDS);
856
+ if (invalidCheckIds.length > 0) {
857
+ throw usageError(
858
+ `Unknown check id${invalidCheckIds.length === 1 ? "" : "s"}: ${invalidCheckIds.join(", ")}`
859
+ );
860
+ }
861
+ const resolvedCheckIds = checkIds && checkIds.length > 0 ? checkIds : categories && categories.length > 0 ? Array.from(
862
+ new Set(
863
+ categories.flatMap(
864
+ (category) => APPS_CHECK_IDS_BY_CATEGORY[category]
865
+ )
866
+ )
867
+ ) : void 0;
868
+ return {
869
+ ...serverConfig,
870
+ ...resolvedCheckIds && resolvedCheckIds.length > 0 ? { checkIds: resolvedCheckIds } : {}
871
+ };
872
+ }
728
873
  function registerProtocolCommands(program) {
729
874
  const protocol = program.command("protocol").description("MCP protocol inspection and conformance checks");
730
875
  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(
@@ -761,7 +906,7 @@ function getFormat(command) {
761
906
  const opts = command.optsWithGlobals();
762
907
  return resolveOutputFormat(opts.format, process.stdout.isTTY);
763
908
  }
764
- function collectInvalidEntries(values, allowedValues) {
909
+ function collectInvalidEntries2(values, allowedValues) {
765
910
  return (values ?? []).filter((value) => !allowedValues.includes(value));
766
911
  }
767
912
  function buildConfig(options) {
@@ -777,7 +922,7 @@ function buildConfig(options) {
777
922
  }
778
923
  const customHeaders = parseHeadersOption(options.header);
779
924
  const categories = options.category?.filter(Boolean);
780
- const invalidCategories = collectInvalidEntries(
925
+ const invalidCategories = collectInvalidEntries2(
781
926
  categories,
782
927
  sdk.MCP_CHECK_CATEGORIES
783
928
  );
@@ -787,7 +932,7 @@ function buildConfig(options) {
787
932
  );
788
933
  }
789
934
  const checkIds = options.checkId?.filter(Boolean);
790
- const invalidCheckIds = collectInvalidEntries(checkIds, sdk.MCP_CHECK_IDS);
935
+ const invalidCheckIds = collectInvalidEntries2(checkIds, sdk.MCP_CHECK_IDS);
791
936
  if (invalidCheckIds.length > 0) {
792
937
  throw usageError(
793
938
  `Unknown check id${invalidCheckIds.length === 1 ? "" : "s"}: ${invalidCheckIds.join(", ")}`
@@ -1040,7 +1185,7 @@ function buildDebugArtifactEnvelope(options) {
1040
1185
  if (rpcLogs.length > 0) {
1041
1186
  payload._rpcLogs = rpcLogs;
1042
1187
  }
1043
- return redactSensitiveValue(payload);
1188
+ return sdk.redactSensitiveValue(payload);
1044
1189
  }
1045
1190
  function buildCommandArtifactError(code, message, details) {
1046
1191
  return {
@@ -1051,7 +1196,7 @@ function buildCommandArtifactError(code, message, details) {
1051
1196
  }
1052
1197
  async function writeDebugArtifact(outputPath, payload) {
1053
1198
  const resolvedPath = path__default.default.resolve(process.cwd(), outputPath);
1054
- const redactedPayload = redactSensitiveValue(payload);
1199
+ const redactedPayload = sdk.redactSensitiveValue(payload);
1055
1200
  try {
1056
1201
  await promises.mkdir(path__default.default.dirname(resolvedPath), { recursive: true });
1057
1202
  await promises.writeFile(
@@ -1254,12 +1399,22 @@ function registerOAuthCommands(program) {
1254
1399
  }
1255
1400
  );
1256
1401
  const snapshotCollector = options.debugOut ? createCliRpcLogCollector({ __cli__: config.serverUrl }) : void 0;
1402
+ const isTTY = process.stderr.isTTY;
1403
+ if (isTTY) {
1404
+ config.onProgress = (message) => {
1405
+ process.stderr.write(`\r\x1B[K${message}`);
1406
+ };
1407
+ }
1257
1408
  let result;
1258
1409
  let commandError;
1259
1410
  try {
1260
1411
  result = await sdk.runOAuthLogin(config);
1261
1412
  } catch (error) {
1262
1413
  commandError = error;
1414
+ } finally {
1415
+ if (isTTY) {
1416
+ process.stderr.write("\r\x1B[K");
1417
+ }
1263
1418
  }
1264
1419
  const snapshotConfig = buildOAuthLoginSnapshotConfig(config, result);
1265
1420
  const target = summarizeServerDoctorTarget(
@@ -1646,10 +1801,13 @@ function statusToErrorCode(status) {
1646
1801
  }
1647
1802
  function registerPromptCommands(program) {
1648
1803
  const prompts = program.command("prompts").description("List and fetch MCP prompts");
1649
- addSharedServerOptions(
1650
- prompts.command("list").description("List prompts exposed by an MCP server").option("--cursor <cursor>", "Pagination cursor")
1804
+ addRetryOptions(
1805
+ addSharedServerOptions(
1806
+ prompts.command("list").description("List prompts exposed by an MCP server").option("--cursor <cursor>", "Pagination cursor")
1807
+ )
1651
1808
  ).action(async (options, command) => {
1652
1809
  const globalOptions = getGlobalOptions(command);
1810
+ const retryPolicy = parseRetryPolicy(options);
1653
1811
  const target = describeTarget(options);
1654
1812
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
1655
1813
  const config = parseServerConfig({
@@ -1661,15 +1819,22 @@ function registerPromptCommands(program) {
1661
1819
  (manager, serverId) => sdk.listPrompts(manager, { serverId, cursor: options.cursor }),
1662
1820
  {
1663
1821
  timeout: globalOptions.timeout,
1664
- rpcLogger: collector?.rpcLogger
1822
+ rpcLogger: collector?.rpcLogger,
1823
+ retryPolicy
1665
1824
  }
1666
1825
  );
1667
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
1826
+ writeResult(
1827
+ withRpcLogsIfRequested(result, collector, globalOptions),
1828
+ globalOptions.format
1829
+ );
1668
1830
  });
1669
- addSharedServerOptions(
1670
- 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")
1831
+ addRetryOptions(
1832
+ 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")
1834
+ )
1671
1835
  ).action(async (options, command) => {
1672
1836
  const globalOptions = getGlobalOptions(command);
1837
+ const retryPolicy = parseRetryPolicy(options);
1673
1838
  const target = describeTarget(options);
1674
1839
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
1675
1840
  const promptName = resolveAliasedStringOption(
@@ -1695,18 +1860,25 @@ function registerPromptCommands(program) {
1695
1860
  }),
1696
1861
  {
1697
1862
  timeout: globalOptions.timeout,
1698
- rpcLogger: collector?.rpcLogger
1863
+ rpcLogger: collector?.rpcLogger,
1864
+ retryPolicy
1699
1865
  }
1700
1866
  );
1701
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
1867
+ writeResult(
1868
+ withRpcLogsIfRequested(result, collector, globalOptions),
1869
+ globalOptions.format
1870
+ );
1702
1871
  });
1703
1872
  }
1704
1873
  function registerResourcesCommands(program) {
1705
1874
  const resources = program.command("resources").description("List and read MCP resources");
1706
- addSharedServerOptions(
1707
- resources.command("list").description("List resources exposed by an MCP server").option("--cursor <cursor>", "Pagination cursor")
1875
+ addRetryOptions(
1876
+ addSharedServerOptions(
1877
+ resources.command("list").description("List resources exposed by an MCP server").option("--cursor <cursor>", "Pagination cursor")
1878
+ )
1708
1879
  ).action(async (options, command) => {
1709
1880
  const globalOptions = getGlobalOptions(command);
1881
+ const retryPolicy = parseRetryPolicy(options);
1710
1882
  const target = describeTarget(options);
1711
1883
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
1712
1884
  const config = parseServerConfig({
@@ -1718,15 +1890,22 @@ function registerResourcesCommands(program) {
1718
1890
  (manager, serverId) => sdk.listResources(manager, { serverId, cursor: options.cursor }),
1719
1891
  {
1720
1892
  timeout: globalOptions.timeout,
1721
- rpcLogger: collector?.rpcLogger
1893
+ rpcLogger: collector?.rpcLogger,
1894
+ retryPolicy
1722
1895
  }
1723
1896
  );
1724
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
1897
+ writeResult(
1898
+ withRpcLogsIfRequested(result, collector, globalOptions),
1899
+ globalOptions.format
1900
+ );
1725
1901
  });
1726
- addSharedServerOptions(
1727
- resources.command("read").description("Read a resource from an MCP server").option("--resource-uri <uri>", "Resource URI").option("--uri <uri>", "Alias for --resource-uri")
1902
+ addRetryOptions(
1903
+ addSharedServerOptions(
1904
+ resources.command("read").description("Read a resource from an MCP server").option("--resource-uri <uri>", "Resource URI").option("--uri <uri>", "Alias for --resource-uri")
1905
+ )
1728
1906
  ).action(async (options, command) => {
1729
1907
  const globalOptions = getGlobalOptions(command);
1908
+ const retryPolicy = parseRetryPolicy(options);
1730
1909
  const target = describeTarget(options);
1731
1910
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
1732
1911
  const resourceUri = resolveAliasedStringOption(
@@ -1747,15 +1926,22 @@ function registerResourcesCommands(program) {
1747
1926
  (manager, serverId) => sdk.readResource(manager, { serverId, uri: resourceUri }),
1748
1927
  {
1749
1928
  timeout: globalOptions.timeout,
1750
- rpcLogger: collector?.rpcLogger
1929
+ rpcLogger: collector?.rpcLogger,
1930
+ retryPolicy
1751
1931
  }
1752
1932
  );
1753
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
1933
+ writeResult(
1934
+ withRpcLogsIfRequested(result, collector, globalOptions),
1935
+ globalOptions.format
1936
+ );
1754
1937
  });
1755
- addSharedServerOptions(
1756
- resources.command("templates").description("List resource templates exposed by an MCP server").option("--cursor <cursor>", "Pagination cursor")
1938
+ addRetryOptions(
1939
+ addSharedServerOptions(
1940
+ resources.command("templates").description("List resource templates exposed by an MCP server").option("--cursor <cursor>", "Pagination cursor")
1941
+ )
1757
1942
  ).action(async (options, command) => {
1758
1943
  const globalOptions = getGlobalOptions(command);
1944
+ const retryPolicy = parseRetryPolicy(options);
1759
1945
  const target = describeTarget(options);
1760
1946
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
1761
1947
  const config = parseServerConfig({
@@ -1770,102 +1956,87 @@ function registerResourcesCommands(program) {
1770
1956
  ),
1771
1957
  {
1772
1958
  timeout: globalOptions.timeout,
1773
- rpcLogger: collector?.rpcLogger
1959
+ rpcLogger: collector?.rpcLogger,
1960
+ retryPolicy
1774
1961
  }
1775
1962
  );
1776
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
1963
+ writeResult(
1964
+ withRpcLogsIfRequested(result, collector, globalOptions),
1965
+ globalOptions.format
1966
+ );
1777
1967
  });
1778
1968
  }
1779
-
1780
- // src/lib/server-ops.ts
1781
- async function listToolsWithMetadata(manager, params) {
1782
- const result = await manager.listTools(
1783
- params.serverId,
1784
- params.cursor ? { cursor: params.cursor } : void 0
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".`
1785
1978
  );
1786
- const tools = result.tools ?? [];
1787
- const toolsMetadata = manager.getAllToolsMetadata(params.serverId);
1788
- const tokenCount = params.modelId ? estimateTokensFromChars(JSON.stringify(tools)) : void 0;
1789
- return {
1790
- tools,
1791
- nextCursor: result.nextCursor,
1792
- toolsMetadata,
1793
- ...tokenCount === void 0 ? {} : { tokenCount }
1794
- };
1795
1979
  }
1796
- async function exportServerSnapshot(manager, serverId, target) {
1797
- const [toolsResult, resourcesResult, promptsResult, resourceTemplatesResult] = await Promise.all([
1798
- manager.listTools(serverId),
1799
- manager.listResources(serverId),
1800
- manager.listPrompts(serverId),
1801
- manager.listResourceTemplates(serverId).catch(() => ({
1802
- resourceTemplates: []
1803
- }))
1804
- ]);
1805
- return {
1806
- target,
1807
- exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
1808
- initInfo: manager.getInitializationInfo(serverId) ?? null,
1809
- capabilities: manager.getServerCapabilities(serverId) ?? null,
1810
- tools: (toolsResult.tools ?? []).map((tool) => ({
1811
- name: tool.name,
1812
- description: tool.description,
1813
- inputSchema: tool.inputSchema,
1814
- outputSchema: tool.outputSchema
1815
- })),
1816
- toolsMetadata: manager.getAllToolsMetadata(serverId),
1817
- resources: (resourcesResult.resources ?? []).map((resource) => ({
1818
- uri: resource.uri,
1819
- name: resource.name,
1820
- description: resource.description,
1821
- mimeType: resource.mimeType
1822
- })),
1823
- resourceTemplates: (resourceTemplatesResult.resourceTemplates ?? []).map(
1824
- (template) => ({
1825
- uriTemplate: template.uriTemplate,
1826
- name: template.name,
1827
- description: template.description,
1828
- mimeType: template.mimeType
1829
- })
1830
- ),
1831
- prompts: (promptsResult.prompts ?? []).map((prompt) => ({
1832
- name: prompt.name,
1833
- description: prompt.description,
1834
- arguments: prompt.arguments
1835
- }))
1836
- };
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");
1837
1986
  }
1838
- function estimateTokensFromChars(text) {
1839
- return Math.ceil(text.length / 4);
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;
1840
2006
  }
1841
2007
 
1842
2008
  // src/commands/server.ts
1843
2009
  function registerServerCommands(program) {
1844
2010
  const server = program.command("server").description("Inspect MCP server connectivity and capabilities");
1845
- server.command("probe").description("Probe an HTTP MCP server without using the full client connect flow").requiredOption("--url <url>", "HTTP MCP server URL").option("--access-token <token>", "Bearer access token for HTTP servers").option(
1846
- "--oauth-access-token <token>",
1847
- "OAuth bearer access token for HTTP servers"
1848
- ).option(
1849
- "--header <header>",
1850
- 'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
1851
- (value, previous = []) => [...previous, value],
1852
- []
1853
- ).option(
1854
- "--client-capabilities <json>",
1855
- "Client capabilities advertised in the initialize probe as a JSON object"
1856
- ).option(
1857
- "--protocol-version <version>",
1858
- "OAuth/MCP protocol version hint used for the initialize probe",
1859
- "2025-11-25"
1860
- ).option(
1861
- "--timeout <ms>",
1862
- "Request timeout in milliseconds",
1863
- (value) => parsePositiveInteger(value, "Timeout")
1864
- ).option(
1865
- "--debug-out <path>",
1866
- "Write a structured debug artifact to a file"
2011
+ addRetryOptions(
2012
+ server.command("probe").description(
2013
+ "Probe an HTTP MCP server without using the full client connect flow"
2014
+ ).requiredOption("--url <url>", "HTTP MCP server URL").option("--access-token <token>", "Bearer access token for HTTP servers").option(
2015
+ "--oauth-access-token <token>",
2016
+ "OAuth bearer access token for HTTP servers"
2017
+ ).option(
2018
+ "--header <header>",
2019
+ 'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
2020
+ (value, previous = []) => [...previous, value],
2021
+ []
2022
+ ).option(
2023
+ "--client-capabilities <json>",
2024
+ "Client capabilities advertised in the initialize probe as a JSON object"
2025
+ ).option(
2026
+ "--protocol-version <version>",
2027
+ "OAuth/MCP protocol version hint used for the initialize probe",
2028
+ "2025-11-25"
2029
+ ).option(
2030
+ "--timeout <ms>",
2031
+ "Request timeout in milliseconds",
2032
+ (value) => parsePositiveInteger(value, "Timeout")
2033
+ ).option(
2034
+ "--debug-out <path>",
2035
+ "Write a structured debug artifact to a file"
2036
+ )
1867
2037
  ).action(async (options, command) => {
1868
2038
  const globalOptions = getGlobalOptions(command);
2039
+ const retryPolicy = parseRetryPolicy(options);
1869
2040
  const protocolVersion = options.protocolVersion;
1870
2041
  const config = parseServerConfig({
1871
2042
  ...options,
@@ -1892,7 +2063,8 @@ function registerServerCommands(program) {
1892
2063
  headers: parseHeadersOption(options.header),
1893
2064
  accessToken: resolveHttpAccessToken(options),
1894
2065
  clientCapabilities: "clientCapabilities" in config ? config.clientCapabilities : void 0,
1895
- timeoutMs: options.timeout ?? globalOptions.timeout
2066
+ timeoutMs: options.timeout ?? globalOptions.timeout,
2067
+ retryPolicy
1896
2068
  });
1897
2069
  } catch (error) {
1898
2070
  commandError = error;
@@ -1940,10 +2112,13 @@ function registerServerCommands(program) {
1940
2112
  setProcessExitCode(1);
1941
2113
  }
1942
2114
  });
1943
- addSharedServerOptions(
1944
- server.command("doctor").description("Run a stateless diagnostic sweep against an MCP server").option("--out <path>", "Write the doctor JSON artifact to a file")
2115
+ addRetryOptions(
2116
+ addSharedServerOptions(
2117
+ server.command("doctor").description("Run a stateless diagnostic sweep against an MCP server").option("--out <path>", "Write the doctor JSON artifact to a file")
2118
+ )
1945
2119
  ).action(async (options, command) => {
1946
2120
  const globalOptions = getGlobalOptions(command);
2121
+ const retryPolicy = parseRetryPolicy(options);
1947
2122
  const target = describeTarget(options);
1948
2123
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
1949
2124
  const config = parseServerConfig({
@@ -1951,14 +2126,13 @@ function registerServerCommands(program) {
1951
2126
  timeout: globalOptions.timeout
1952
2127
  });
1953
2128
  const doctorTarget = summarizeServerDoctorTarget(target, config);
1954
- const result = await sdk.runServerDoctor(
1955
- {
1956
- config,
1957
- target: doctorTarget,
1958
- timeout: globalOptions.timeout,
1959
- rpcLogger: collector?.rpcLogger
1960
- }
1961
- );
2129
+ const result = await sdk.runServerDoctor({
2130
+ config,
2131
+ target: doctorTarget,
2132
+ timeout: globalOptions.timeout,
2133
+ rpcLogger: collector?.rpcLogger,
2134
+ retryPolicy
2135
+ });
1962
2136
  const jsonPayload = globalOptions.rpc ? attachCliRpcLogs(result, collector) : result;
1963
2137
  const artifactPath = options.out ? await writeDebugArtifact(options.out, jsonPayload) : void 0;
1964
2138
  if (globalOptions.format === "human") {
@@ -1973,10 +2147,13 @@ function registerServerCommands(program) {
1973
2147
  setProcessExitCode(1);
1974
2148
  }
1975
2149
  });
1976
- addSharedServerOptions(
1977
- server.command("info").description("Get initialization info for an MCP server")
2150
+ addRetryOptions(
2151
+ addSharedServerOptions(
2152
+ server.command("info").description("Get initialization info for an MCP server")
2153
+ )
1978
2154
  ).action(async (options, command) => {
1979
2155
  const globalOptions = getGlobalOptions(command);
2156
+ const retryPolicy = parseRetryPolicy(options);
1980
2157
  const target = describeTarget(options);
1981
2158
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
1982
2159
  const config = parseServerConfig({
@@ -1996,18 +2173,22 @@ function registerServerCommands(program) {
1996
2173
  },
1997
2174
  {
1998
2175
  timeout: globalOptions.timeout,
1999
- rpcLogger: collector?.rpcLogger
2176
+ rpcLogger: collector?.rpcLogger,
2177
+ retryPolicy
2000
2178
  }
2001
2179
  );
2002
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
2180
+ writeResult(
2181
+ withRpcLogsIfRequested(result, collector, globalOptions),
2182
+ globalOptions.format
2183
+ );
2003
2184
  });
2004
- addSharedServerOptions(
2005
- server.command("validate").description("Connect to a server and verify the debugger surface works")
2006
- ).option(
2007
- "--debug-out <path>",
2008
- "Write a structured debug artifact to a file"
2009
- ).action(async (options, command) => {
2185
+ addRetryOptions(
2186
+ addSharedServerOptions(
2187
+ server.command("validate").description("Connect to a server and verify the debugger surface works")
2188
+ )
2189
+ ).option("--debug-out <path>", "Write a structured debug artifact to a file").action(async (options, command) => {
2010
2190
  const globalOptions = getGlobalOptions(command);
2191
+ const retryPolicy = parseRetryPolicy(options);
2011
2192
  const target = describeTarget(options);
2012
2193
  const primaryCollector = globalOptions.rpc || options.debugOut ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2013
2194
  const snapshotCollector = options.debugOut ? createCliRpcLogCollector({ __cli__: target }) : void 0;
@@ -2032,7 +2213,8 @@ function registerServerCommands(program) {
2032
2213
  },
2033
2214
  {
2034
2215
  timeout: globalOptions.timeout,
2035
- rpcLogger: primaryCollector?.rpcLogger
2216
+ rpcLogger: primaryCollector?.rpcLogger,
2217
+ retryPolicy
2036
2218
  }
2037
2219
  );
2038
2220
  } catch (error) {
@@ -2069,10 +2251,13 @@ function registerServerCommands(program) {
2069
2251
  globalOptions.format
2070
2252
  );
2071
2253
  });
2072
- addSharedServerOptions(
2073
- server.command("ping").description("Ping an MCP server")
2254
+ addRetryOptions(
2255
+ addSharedServerOptions(
2256
+ server.command("ping").description("Ping an MCP server")
2257
+ )
2074
2258
  ).action(async (options, command) => {
2075
2259
  const globalOptions = getGlobalOptions(command);
2260
+ const retryPolicy = parseRetryPolicy(options);
2076
2261
  const target = describeTarget(options);
2077
2262
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2078
2263
  const config = parseServerConfig({
@@ -2088,15 +2273,22 @@ function registerServerCommands(program) {
2088
2273
  }),
2089
2274
  {
2090
2275
  timeout: globalOptions.timeout,
2091
- rpcLogger: collector?.rpcLogger
2276
+ rpcLogger: collector?.rpcLogger,
2277
+ retryPolicy
2092
2278
  }
2093
2279
  );
2094
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
2280
+ writeResult(
2281
+ withRpcLogsIfRequested(result, collector, globalOptions),
2282
+ globalOptions.format
2283
+ );
2095
2284
  });
2096
- addSharedServerOptions(
2097
- server.command("capabilities").description("Get resolved server capabilities")
2285
+ addRetryOptions(
2286
+ addSharedServerOptions(
2287
+ server.command("capabilities").description("Get resolved server capabilities")
2288
+ )
2098
2289
  ).action(async (options, command) => {
2099
2290
  const globalOptions = getGlobalOptions(command);
2291
+ const retryPolicy = parseRetryPolicy(options);
2100
2292
  const target = describeTarget(options);
2101
2293
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2102
2294
  const config = parseServerConfig({
@@ -2111,38 +2303,252 @@ function registerServerCommands(program) {
2111
2303
  }),
2112
2304
  {
2113
2305
  timeout: globalOptions.timeout,
2114
- rpcLogger: collector?.rpcLogger
2306
+ rpcLogger: collector?.rpcLogger,
2307
+ retryPolicy
2115
2308
  }
2116
2309
  );
2117
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
2310
+ writeResult(
2311
+ withRpcLogsIfRequested(result, collector, globalOptions),
2312
+ globalOptions.format
2313
+ );
2118
2314
  });
2119
- addSharedServerOptions(
2120
- server.command("export").description("Export server tools, resources, prompts, and capabilities")
2315
+ addRetryOptions(
2316
+ addSharedServerOptions(
2317
+ server.command("export").description(
2318
+ "Export server tools, resources, prompts, and capabilities"
2319
+ ).option(
2320
+ "--stable",
2321
+ "Emit the deterministic versioned snapshot format for baselines"
2322
+ )
2323
+ )
2121
2324
  ).action(async (options, command) => {
2122
2325
  const globalOptions = getGlobalOptions(command);
2326
+ const retryPolicy = parseRetryPolicy(options);
2123
2327
  const target = describeTarget(options);
2124
2328
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2125
2329
  const config = parseServerConfig({
2126
2330
  ...options,
2127
2331
  timeout: globalOptions.timeout
2128
2332
  });
2129
- const result = await withEphemeralManager(
2333
+ const snapshot = await sdk.collectServerSnapshot({
2130
2334
  config,
2131
- (manager, serverId) => exportServerSnapshot(manager, serverId, target),
2132
- {
2335
+ target,
2336
+ timeout: globalOptions.timeout,
2337
+ rpcLogger: collector?.rpcLogger,
2338
+ retryPolicy,
2339
+ clientName: "mcpjam",
2340
+ serverId: "__cli__"
2341
+ });
2342
+ const result = options.stable ? sdk.serializeStableServerSnapshot(snapshot) : sdk.serializeServerSnapshot(snapshot, { mode: "raw" });
2343
+ writeResult(
2344
+ options.stable ? result : withRpcLogsIfRequested(result, collector, globalOptions),
2345
+ globalOptions.format
2346
+ );
2347
+ });
2348
+ addRetryOptions(
2349
+ addSharedServerOptions(
2350
+ server.command("diff").description(
2351
+ "Compare a server snapshot baseline against a live or file snapshot"
2352
+ ).option(
2353
+ "--baseline <path>",
2354
+ "Compare a baseline file to a live server target"
2355
+ ).option(
2356
+ "--left <path>",
2357
+ "Left snapshot file for file-vs-file comparison"
2358
+ ).option(
2359
+ "--right <path>",
2360
+ "Right snapshot file for file-vs-file comparison"
2361
+ ).option(
2362
+ "--fail-on <policy>",
2363
+ "Diff failure policy: breaking, any, or none"
2364
+ ).option(
2365
+ "--reporter <reporter>",
2366
+ "Structured reporter output: json-summary or junit-xml"
2367
+ ).option("--out <path>", "Write the raw diff JSON artifact to a file")
2368
+ )
2369
+ ).action(async (options, command) => {
2370
+ const globalOptions = getGlobalOptions(command);
2371
+ const retryPolicy = parseRetryPolicy(options);
2372
+ const reporter = parseReporterFormat(
2373
+ options.reporter
2374
+ );
2375
+ const mode = resolveServerDiffMode(options);
2376
+ let rawDiff;
2377
+ let collector;
2378
+ if (mode.kind === "baseline-live") {
2379
+ const target = describeTarget(options);
2380
+ collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2381
+ const config = parseServerConfig({
2382
+ ...options,
2383
+ timeout: globalOptions.timeout
2384
+ });
2385
+ const baselineSnapshot = await readSnapshotFile(mode.baselinePath);
2386
+ const currentSnapshot = await sdk.collectServerSnapshot({
2387
+ config,
2388
+ target,
2133
2389
  timeout: globalOptions.timeout,
2134
- rpcLogger: collector?.rpcLogger
2390
+ rpcLogger: collector?.rpcLogger,
2391
+ retryPolicy,
2392
+ clientName: "mcpjam",
2393
+ serverId: "__cli__"
2394
+ });
2395
+ rawDiff = createServerDiffResult(
2396
+ baselineSnapshot,
2397
+ currentSnapshot,
2398
+ parseDiffFailOn(options.failOn)
2399
+ );
2400
+ } else {
2401
+ if (hasServerTargetOptions(options)) {
2402
+ throw usageError(
2403
+ "Do not pass live target options together with --left/--right file comparison."
2404
+ );
2135
2405
  }
2136
- );
2137
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
2406
+ const [leftSnapshot, rightSnapshot] = await Promise.all([
2407
+ readSnapshotFile(mode.leftPath),
2408
+ readSnapshotFile(mode.rightPath)
2409
+ ]);
2410
+ rawDiff = createServerDiffResult(
2411
+ leftSnapshot,
2412
+ rightSnapshot,
2413
+ parseDiffFailOn(options.failOn)
2414
+ );
2415
+ }
2416
+ if (options.out) {
2417
+ await writeJsonArtifact(options.out, rawDiff);
2418
+ }
2419
+ if (reporter) {
2420
+ writeReporterResult(
2421
+ reporter,
2422
+ sdk.buildServerDiffReport(rawDiff, {
2423
+ metadata: mode.kind === "baseline-live" ? {
2424
+ comparisonMode: mode.kind,
2425
+ baselinePath: mode.baselinePath
2426
+ } : {
2427
+ comparisonMode: mode.kind,
2428
+ leftPath: mode.leftPath,
2429
+ rightPath: mode.rightPath
2430
+ }
2431
+ })
2432
+ );
2433
+ } else {
2434
+ writeResult(
2435
+ withRpcLogsIfRequested(rawDiff, collector, globalOptions),
2436
+ globalOptions.format
2437
+ );
2438
+ }
2439
+ if (!rawDiff.passed) {
2440
+ setProcessExitCode(1);
2441
+ }
2138
2442
  });
2139
2443
  }
2444
+ function hasServerTargetOptions(options) {
2445
+ return typeof options.url === "string" || typeof options.command === "string";
2446
+ }
2447
+ function resolveServerDiffMode(options) {
2448
+ const baselinePath = toOptionalString(options.baseline);
2449
+ const leftPath = toOptionalString(options.left);
2450
+ const rightPath = toOptionalString(options.right);
2451
+ if (baselinePath && (leftPath || rightPath)) {
2452
+ throw usageError(
2453
+ "Specify either --baseline with a live target or --left/--right for file comparison."
2454
+ );
2455
+ }
2456
+ if (baselinePath) {
2457
+ return {
2458
+ kind: "baseline-live",
2459
+ baselinePath
2460
+ };
2461
+ }
2462
+ if (leftPath && rightPath) {
2463
+ return {
2464
+ kind: "file-file",
2465
+ leftPath,
2466
+ rightPath
2467
+ };
2468
+ }
2469
+ if (leftPath || rightPath) {
2470
+ throw usageError(
2471
+ "Both --left and --right are required for file comparison."
2472
+ );
2473
+ }
2474
+ throw usageError(
2475
+ "Specify either --baseline with a live target or --left/--right for file comparison."
2476
+ );
2477
+ }
2478
+ function parseDiffFailOn(value) {
2479
+ if (value === void 0) {
2480
+ return void 0;
2481
+ }
2482
+ if (value === "breaking" || value === "any" || value === "none") {
2483
+ return value;
2484
+ }
2485
+ throw usageError(
2486
+ `Invalid fail-on policy "${value}". Use "breaking", "any", or "none".`
2487
+ );
2488
+ }
2489
+ async function readSnapshotFile(filePath) {
2490
+ let contents;
2491
+ try {
2492
+ contents = await promises.readFile(filePath, "utf8");
2493
+ } catch (error) {
2494
+ throw operationalError(`Failed to read snapshot file "${filePath}".`, {
2495
+ source: error instanceof Error ? error.message : String(error)
2496
+ });
2497
+ }
2498
+ try {
2499
+ return JSON.parse(contents);
2500
+ } catch (error) {
2501
+ throw usageError(`Snapshot file "${filePath}" must contain valid JSON.`, {
2502
+ source: error instanceof Error ? error.message : String(error)
2503
+ });
2504
+ }
2505
+ }
2506
+ function toOptionalString(value) {
2507
+ if (typeof value !== "string") {
2508
+ return void 0;
2509
+ }
2510
+ const normalized = value.trim();
2511
+ return normalized.length > 0 ? normalized : void 0;
2512
+ }
2513
+ function createServerDiffResult(left, right, failOn) {
2514
+ try {
2515
+ return sdk.diffServerSnapshots(left, right, { failOn });
2516
+ } catch (error) {
2517
+ if (error instanceof sdk.ServerSnapshotFormatError) {
2518
+ throw usageError(error.message);
2519
+ }
2520
+ throw error;
2521
+ }
2522
+ }
2523
+ async function listToolsWithMetadata(manager, params) {
2524
+ const result = await manager.listTools(
2525
+ params.serverId,
2526
+ params.cursor ? { cursor: params.cursor } : void 0
2527
+ );
2528
+ const tools = result.tools ?? [];
2529
+ const toolsMetadata = manager.getAllToolsMetadata(params.serverId);
2530
+ const tokenCount = params.modelId ? estimateTokensFromChars(JSON.stringify(tools)) : void 0;
2531
+ return {
2532
+ tools,
2533
+ nextCursor: result.nextCursor,
2534
+ toolsMetadata,
2535
+ ...tokenCount === void 0 ? {} : { tokenCount }
2536
+ };
2537
+ }
2538
+ function estimateTokensFromChars(text) {
2539
+ return Math.ceil(text.length / 4);
2540
+ }
2541
+
2542
+ // src/commands/tools.ts
2140
2543
  function registerToolsCommands(program) {
2141
2544
  const tools = program.command("tools").description("List and invoke MCP server tools");
2142
- addSharedServerOptions(
2143
- tools.command("list").description("List tools exposed by an MCP server").option("--cursor <cursor>", "Pagination cursor").option("--model-id <model>", "Model id used for token counting")
2545
+ addRetryOptions(
2546
+ addSharedServerOptions(
2547
+ tools.command("list").description("List tools exposed by an MCP server").option("--cursor <cursor>", "Pagination cursor").option("--model-id <model>", "Model id used for token counting")
2548
+ )
2144
2549
  ).action(async (options, command) => {
2145
2550
  const globalOptions = getGlobalOptions(command);
2551
+ const retryPolicy = parseRetryPolicy(options);
2146
2552
  const target = describeTarget(options);
2147
2553
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2148
2554
  const config = parseServerConfig({
@@ -2158,13 +2564,26 @@ function registerToolsCommands(program) {
2158
2564
  }),
2159
2565
  {
2160
2566
  timeout: globalOptions.timeout,
2161
- rpcLogger: collector?.rpcLogger
2567
+ rpcLogger: collector?.rpcLogger,
2568
+ retryPolicy
2162
2569
  }
2163
2570
  );
2164
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
2571
+ writeResult(
2572
+ withRpcLogsIfRequested(result, collector, globalOptions),
2573
+ globalOptions.format
2574
+ );
2165
2575
  });
2166
2576
  addSharedServerOptions(
2167
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(
2578
+ "--validate-response",
2579
+ "Validate the MCP tool-call envelope returned by the server"
2580
+ ).option(
2581
+ "--expect-success",
2582
+ "Evaluate the tool-call outcome policy against isError"
2583
+ ).option(
2584
+ "--reporter <reporter>",
2585
+ "Structured reporter output: json-summary or junit-xml"
2586
+ ).option(
2168
2587
  "--debug-out <path>",
2169
2588
  "Write a structured debug artifact to a file"
2170
2589
  )
@@ -2177,6 +2596,9 @@ function registerToolsCommands(program) {
2177
2596
  ...options,
2178
2597
  timeout: globalOptions.timeout
2179
2598
  });
2599
+ const reporter = parseReporterFormat(
2600
+ options.reporter
2601
+ );
2180
2602
  const toolName = resolveAliasedStringOption(
2181
2603
  options,
2182
2604
  [
@@ -2196,8 +2618,16 @@ function registerToolsCommands(program) {
2196
2618
  );
2197
2619
  const params = parseJsonRecord(paramsInput, "Tool parameters") ?? {};
2198
2620
  const targetSummary = summarizeServerDoctorTarget(target, config);
2621
+ const shouldValidateResponse = options.validateResponse === true;
2622
+ const shouldExpectSuccess = options.expectSuccess === true;
2623
+ if (reporter && !shouldValidateResponse && !shouldExpectSuccess) {
2624
+ throw usageError(
2625
+ "--reporter requires --validate-response and/or --expect-success."
2626
+ );
2627
+ }
2199
2628
  let result;
2200
2629
  let commandError;
2630
+ const startedAt = Date.now();
2201
2631
  try {
2202
2632
  result = await withEphemeralManager(
2203
2633
  config,
@@ -2239,10 +2669,30 @@ function registerToolsCommands(program) {
2239
2669
  if (commandError) {
2240
2670
  throw commandError;
2241
2671
  }
2242
- writeResult(
2243
- withRpcLogsIfRequested(result, primaryCollector, globalOptions),
2244
- globalOptions.format
2245
- );
2672
+ const validationResult = shouldValidateResponse || shouldExpectSuccess ? sdk.validateToolCallResult(result, {
2673
+ envelope: shouldValidateResponse,
2674
+ outcome: shouldExpectSuccess ? { failOnIsError: true } : void 0
2675
+ }) : void 0;
2676
+ if (reporter) {
2677
+ writeReporterResult(
2678
+ reporter,
2679
+ sdk.buildToolCallValidationReport(validationResult, {
2680
+ durationMs: Date.now() - startedAt,
2681
+ rawResult: result,
2682
+ metadata: {
2683
+ toolName
2684
+ }
2685
+ })
2686
+ );
2687
+ } else {
2688
+ writeResult(
2689
+ withRpcLogsIfRequested(result, primaryCollector, globalOptions),
2690
+ globalOptions.format
2691
+ );
2692
+ }
2693
+ if (validationResult && !validationResult.passed) {
2694
+ setProcessExitCode(1);
2695
+ }
2246
2696
  if (sdk.isCallToolResultError(result)) {
2247
2697
  setProcessExitCode(1);
2248
2698
  }
@@ -2253,7 +2703,7 @@ function registerToolsCommands(program) {
2253
2703
  async function main(argv = process.argv) {
2254
2704
  const program = addGlobalOptions(
2255
2705
  new commander.Command().name("mcpjam").version(version, "-v, --version", "output the CLI version").description(
2256
- "Test, debug, and validate MCP servers \u2014 health checks, OAuth conformance, tool-surface diffing, and structured triage from the terminal or CI"
2706
+ "Test, debug, and validate MCP servers. Health checks, OAuth conformance, tool-surface diffing, and structured triage from the terminal or CI."
2257
2707
  ).allowExcessArguments(false).exitOverride().configureOutput({
2258
2708
  writeOut: (value) => process.stdout.write(value),
2259
2709
  writeErr: () => {