@mcpjam/cli 2.0.2 → 3.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
@@ -1,18 +1,17 @@
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, statSync, renameSync, 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 } from 'path';
8
+ import { randomUUID } from 'crypto';
9
+ import { spawn } from 'child_process';
10
+ import os, { homedir } from 'os';
13
11
 
14
12
  // package.json
15
- var version = "2.0.2";
13
+ var package_default = {
14
+ version: "3.1.0"};
16
15
 
17
16
  // src/lib/output.ts
18
17
  var DEFAULT_OUTPUT_FORMAT = "json";
@@ -93,8 +92,16 @@ function parseOutputFormat(value) {
93
92
  if (value === "json" || value === "human") {
94
93
  return value;
95
94
  }
95
+ rejectReporterFormatAsOutputFormat(value);
96
96
  throw usageError(`Invalid output format "${value}". Use "json" or "human".`);
97
97
  }
98
+ function rejectReporterFormatAsOutputFormat(value) {
99
+ if (value === "junit-xml" || value === "json-summary") {
100
+ throw usageError(
101
+ `Invalid output format "${value}". Use --reporter ${value} for CI reporter output.`
102
+ );
103
+ }
104
+ }
98
105
  function resolveOutputFormat(value, isTTY) {
99
106
  return parseOutputFormat(value ?? (isTTY ? "human" : "json"));
100
107
  }
@@ -118,12 +125,18 @@ function setProcessExitCode(code) {
118
125
  }
119
126
 
120
127
  // src/lib/apps.ts
128
+ function parseTheme(value) {
129
+ if (value === void 0) {
130
+ return void 0;
131
+ }
132
+ if (value === "light" || value === "dark") {
133
+ return value;
134
+ }
135
+ throw usageError(`Invalid theme "${value}". Use "light" or "dark".`);
136
+ }
121
137
  async function buildMcpWidgetContent(manager, serverId, options) {
122
138
  if (options.template && !options.template.startsWith("ui://")) {
123
- throw cliError(
124
- "VALIDATION_ERROR",
125
- "Template must use ui:// protocol"
126
- );
139
+ throw cliError("VALIDATION_ERROR", "Template must use ui:// protocol");
127
140
  }
128
141
  const resolvedResourceUri = options.template || options.resourceUri;
129
142
  const effectiveCspMode = options.cspMode ?? "permissive";
@@ -136,14 +149,14 @@ async function buildMcpWidgetContent(manager, serverId, options) {
136
149
  throw cliError("NOT_FOUND", "No content in resource");
137
150
  }
138
151
  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;
152
+ const mimeTypeValid = contentMimeType === MCP_UI_RESOURCE_MIME_TYPE;
153
+ 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
154
  let html = extractHtmlFromResourceContent(content);
142
155
  if (!html) {
143
156
  throw cliError("NOT_FOUND", "No HTML content in resource");
144
157
  }
145
158
  const uiMeta = content._meta?.ui;
146
- html = sdk.injectOpenAICompat(html, {
159
+ html = injectOpenAICompat(html, {
147
160
  toolId: options.toolId,
148
161
  toolName: options.toolName,
149
162
  toolInput: options.toolInput ?? {},
@@ -178,8 +191,8 @@ async function buildChatGptWidgetContent(manager, serverId, options) {
178
191
  const resourceMeta = firstContent?._meta;
179
192
  const widgetCspRaw = resourceMeta?.["openai/widgetCSP"];
180
193
  const effectiveCspMode = options.cspMode ?? "permissive";
181
- const cspConfig = sdk.buildCspHeader(effectiveCspMode, widgetCspRaw);
182
- const runtimeHeadContent = sdk.buildChatGptRuntimeHead({
194
+ const cspConfig = buildCspHeader(effectiveCspMode, widgetCspRaw);
195
+ const runtimeHeadContent = buildChatGptRuntimeHead({
183
196
  htmlContent,
184
197
  runtimeConfig: {
185
198
  toolId: options.toolId,
@@ -197,11 +210,14 @@ async function buildChatGptWidgetContent(manager, serverId, options) {
197
210
  });
198
211
  let cspMetaTag = "";
199
212
  if (cspConfig.headerString) {
200
- const metaCspContent = sdk.buildCspMetaContent(cspConfig.headerString);
201
- cspMetaTag = `<meta http-equiv="Content-Security-Policy" content="${metaCspContent.replace(/"/g, "&quot;")}">`;
213
+ const metaCspContent = buildCspMetaContent(cspConfig.headerString);
214
+ cspMetaTag = `<meta http-equiv="Content-Security-Policy" content="${metaCspContent.replace(
215
+ /"/g,
216
+ "&quot;"
217
+ )}">`;
202
218
  }
203
219
  return {
204
- html: sdk.injectScripts(htmlContent, cspMetaTag + runtimeHeadContent),
220
+ html: injectScripts(htmlContent, cspMetaTag + runtimeHeadContent),
205
221
  csp: {
206
222
  mode: cspConfig.mode,
207
223
  connectDomains: cspConfig.connectDomains,
@@ -228,48 +244,395 @@ function extractHtmlFromResourceContent(content) {
228
244
  }
229
245
  return "";
230
246
  }
231
- async function withEphemeralManager(config, fn, options) {
232
- return sdk.withEphemeralClient(config, fn, {
233
- serverId: "__cli__",
234
- clientName: "mcpjam",
235
- timeout: options?.timeout ?? 3e4,
236
- rpcLogger: options?.rpcLogger
237
- });
238
- }
239
247
 
240
- // src/lib/redaction.ts
241
- function redactSensitiveValue(value) {
242
- if (Array.isArray(value)) {
243
- return value.map((entry) => redactSensitiveValue(entry));
248
+ // src/lib/oauth-enums.ts
249
+ var VALID_PROTOCOL_VERSIONS = /* @__PURE__ */ new Set([
250
+ "2025-03-26",
251
+ "2025-06-18",
252
+ "2025-11-25"
253
+ ]);
254
+ var VALID_REGISTRATION_STRATEGIES = /* @__PURE__ */ new Set([
255
+ "cimd",
256
+ "dcr",
257
+ "preregistered"
258
+ ]);
259
+ var VALID_AUTH_MODES = /* @__PURE__ */ new Set([
260
+ "headless",
261
+ "interactive",
262
+ "client_credentials"
263
+ ]);
264
+
265
+ // src/lib/config-file.ts
266
+ function readConfigFile(filePath) {
267
+ let raw;
268
+ try {
269
+ raw = readFileSync(filePath, "utf-8");
270
+ } catch (error) {
271
+ throw usageError(
272
+ `Cannot read config file "${filePath}": ${error instanceof Error ? error.message : String(error)}`
273
+ );
244
274
  }
245
- if (!value || typeof value !== "object") {
246
- return typeof value === "string" ? redactSensitiveString(value) : value;
275
+ let config;
276
+ try {
277
+ config = JSON.parse(raw);
278
+ } catch {
279
+ throw usageError(`Config file "${filePath}" is not valid JSON`);
247
280
  }
248
- return Object.fromEntries(
249
- Object.entries(value).map(([key, entryValue]) => [
250
- key,
251
- shouldRedactKey(key) ? "[REDACTED]" : redactSensitiveValue(entryValue)
252
- ])
281
+ if (typeof config !== "object" || config === null || Array.isArray(config)) {
282
+ throw usageError("Config file must be a JSON object");
283
+ }
284
+ return config;
285
+ }
286
+ function assertObject(value, label) {
287
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
288
+ throw usageError(`${label} must be a JSON object`);
289
+ }
290
+ }
291
+ function assertValidUrl(value, label) {
292
+ if (typeof value !== "string" || !value.trim()) {
293
+ throw usageError(`${label} is required and must be a non-empty string`);
294
+ }
295
+ let parsed;
296
+ try {
297
+ parsed = new URL(value);
298
+ } catch {
299
+ throw usageError(`Invalid ${label}: ${value}`);
300
+ }
301
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
302
+ throw usageError(`Invalid ${label}: ${value}`);
303
+ }
304
+ }
305
+ function assertEnum(value, allowed, label) {
306
+ if (typeof value !== "string" || !allowed.has(value)) {
307
+ throw usageError(
308
+ `Invalid ${label} "${String(value)}". Allowed: ${[...allowed].join(", ")}`
309
+ );
310
+ }
311
+ }
312
+ function validateOptionalString(value, label) {
313
+ if (value !== void 0 && typeof value !== "string") {
314
+ throw usageError(`${label} must be a string`);
315
+ }
316
+ }
317
+ function validateEnumArray(value, allowedValues, label) {
318
+ if (value === void 0) {
319
+ return;
320
+ }
321
+ if (!Array.isArray(value)) {
322
+ throw usageError(`${label} must be an array`);
323
+ }
324
+ for (let index = 0; index < value.length; index += 1) {
325
+ assertEnum(value[index], new Set(allowedValues), `${label}[${index}]`);
326
+ }
327
+ }
328
+ function validateOptionalStringArray(value, label) {
329
+ if (value === void 0) {
330
+ return;
331
+ }
332
+ if (!Array.isArray(value)) {
333
+ throw usageError(`${label} must be an array`);
334
+ }
335
+ for (let index = 0; index < value.length; index += 1) {
336
+ if (typeof value[index] !== "string") {
337
+ throw usageError(`${label}[${index}] must be a string`);
338
+ }
339
+ }
340
+ }
341
+ function validateOptionalStringRecord(value, label) {
342
+ if (value === void 0) {
343
+ return;
344
+ }
345
+ assertObject(value, label);
346
+ for (const [key, entry] of Object.entries(value)) {
347
+ if (typeof entry !== "string") {
348
+ throw usageError(`${label}.${key} must be a string`);
349
+ }
350
+ }
351
+ }
352
+ function validateProtocolRun(run, label) {
353
+ validateOptionalString(run.label, `${label}.label`);
354
+ validateEnumArray(run.categories, MCP_CHECK_CATEGORIES, `${label}.categories`);
355
+ validateEnumArray(run.checkIds, MCP_CHECK_IDS, `${label}.checkIds`);
356
+ }
357
+ function validateOAuthFlow(flow, defaults, index) {
358
+ validateOptionalString(flow.label, `flows[${index}].label`);
359
+ const protocolVersion = flow.protocolVersion ?? defaults?.protocolVersion;
360
+ if (!protocolVersion) {
361
+ throw usageError(
362
+ `flows[${index}]: protocolVersion is required (not set in flow or defaults)`
363
+ );
364
+ }
365
+ assertEnum(
366
+ protocolVersion,
367
+ VALID_PROTOCOL_VERSIONS,
368
+ `flows[${index}].protocolVersion`
369
+ );
370
+ const registrationStrategy = flow.registrationStrategy ?? defaults?.registrationStrategy;
371
+ if (!registrationStrategy) {
372
+ throw usageError(
373
+ `flows[${index}]: registrationStrategy is required (not set in flow or defaults)`
374
+ );
375
+ }
376
+ assertEnum(
377
+ registrationStrategy,
378
+ VALID_REGISTRATION_STRATEGIES,
379
+ `flows[${index}].registrationStrategy`
380
+ );
381
+ const auth = flow.auth ?? defaults?.auth;
382
+ if (auth?.mode) {
383
+ assertEnum(auth.mode, VALID_AUTH_MODES, `flows[${index}].auth.mode`);
384
+ }
385
+ }
386
+ function validateAppsTarget(value, label) {
387
+ assertObject(value, label);
388
+ const hasUrl = typeof value.url === "string" && value.url.trim().length > 0;
389
+ const hasCommand = typeof value.command === "string" && value.command.trim().length > 0;
390
+ if (hasUrl === hasCommand) {
391
+ throw usageError(
392
+ `${label} must provide exactly one of "url" or "command"`
393
+ );
394
+ }
395
+ if (hasUrl) {
396
+ assertValidUrl(value.url, `${label}.url`);
397
+ }
398
+ if (hasCommand) {
399
+ validateOptionalString(value.command, `${label}.command`);
400
+ }
401
+ validateOptionalStringArray(value.args, `${label}.args`);
402
+ validateOptionalStringRecord(value.env, `${label}.env`);
403
+ validateOptionalString(value.cwd, `${label}.cwd`);
404
+ }
405
+ function validateAppsRun(run, label) {
406
+ validateOptionalString(run.label, `${label}.label`);
407
+ validateEnumArray(run.checkIds, MCP_APPS_CHECK_IDS, `${label}.checkIds`);
408
+ }
409
+ function loadOAuthSuiteConfig(filePath) {
410
+ const config = readConfigFile(filePath);
411
+ assertValidUrl(config.serverUrl, "serverUrl");
412
+ const flows = config.flows;
413
+ if (!Array.isArray(flows) || flows.length === 0) {
414
+ throw usageError('Config file must have a non-empty "flows" array');
415
+ }
416
+ const defaults = config.defaults;
417
+ if (defaults !== void 0) {
418
+ assertObject(defaults, "defaults");
419
+ }
420
+ for (let index = 0; index < flows.length; index += 1) {
421
+ const flow = flows[index];
422
+ assertObject(flow, `flows[${index}]`);
423
+ validateOAuthFlow(flow, defaults, index);
424
+ }
425
+ return config;
426
+ }
427
+ function loadProtocolSuiteConfig(filePath) {
428
+ const config = readConfigFile(filePath);
429
+ assertValidUrl(config.serverUrl, "serverUrl");
430
+ const runs = config.runs;
431
+ if (!Array.isArray(runs) || runs.length === 0) {
432
+ throw usageError('Config file must have a non-empty "runs" array');
433
+ }
434
+ if (config.defaults !== void 0) {
435
+ assertObject(config.defaults, "defaults");
436
+ validateProtocolRun(config.defaults, "defaults");
437
+ }
438
+ for (let index = 0; index < runs.length; index += 1) {
439
+ const run = runs[index];
440
+ assertObject(run, `runs[${index}]`);
441
+ validateProtocolRun(run, `runs[${index}]`);
442
+ }
443
+ return config;
444
+ }
445
+ function loadAppsSuiteConfig(filePath) {
446
+ const config = readConfigFile(filePath);
447
+ if (config.name !== void 0) {
448
+ validateOptionalString(config.name, "name");
449
+ }
450
+ if (config.target === void 0) {
451
+ throw usageError('Config file must include a "target" object');
452
+ }
453
+ validateAppsTarget(config.target, "target");
454
+ const runs = config.runs;
455
+ if (!Array.isArray(runs) || runs.length === 0) {
456
+ throw usageError('Config file must have a non-empty "runs" array');
457
+ }
458
+ if (config.defaults !== void 0) {
459
+ assertObject(config.defaults, "defaults");
460
+ validateAppsRun(config.defaults, "defaults");
461
+ }
462
+ for (let index = 0; index < runs.length; index += 1) {
463
+ const run = runs[index];
464
+ assertObject(run, `runs[${index}]`);
465
+ validateAppsRun(run, `runs[${index}]`);
466
+ }
467
+ return config;
468
+ }
469
+ function parseConformanceOutputFormat(value) {
470
+ if (value === "json" || value === "human") {
471
+ return value;
472
+ }
473
+ rejectReporterFormatAsOutputFormat(value);
474
+ throw usageError(
475
+ `Invalid output format "${value}". Use "json" or "human".`
476
+ );
477
+ }
478
+ function resolveConformanceOutputFormat(value, isTTY) {
479
+ return parseConformanceOutputFormat(value ?? (isTTY ? "human" : "json"));
480
+ }
481
+ function resolveConformanceOutputFormatForCli(value, isTTY, reporter) {
482
+ if (reporter === void 0 || value === void 0) {
483
+ return resolveConformanceOutputFormat(value, isTTY);
484
+ }
485
+ if (value === "json" || value === "human") {
486
+ return value;
487
+ }
488
+ if (value === "junit-xml" || value === "json-summary") {
489
+ return "json";
490
+ }
491
+ throw usageError(
492
+ `Invalid output format "${value}". Use "json" or "human".`
253
493
  );
254
494
  }
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"
495
+ function renderConformanceResult(result, format) {
496
+ switch (format) {
497
+ case "human":
498
+ return JSON.stringify(result, null, 2);
499
+ case "json":
500
+ return JSON.stringify(result);
501
+ }
502
+ }
503
+ function renderConformanceReporterResult(result, reporter) {
504
+ const report = toConformanceReport(result);
505
+ switch (reporter) {
506
+ case "json-summary":
507
+ return JSON.stringify(renderConformanceReportJson(report));
508
+ case "junit-xml":
509
+ return renderConformanceReportJUnitXml(report);
510
+ }
511
+ }
512
+ function renderConformanceForCli(result, reporter, format) {
513
+ return reporter ? renderConformanceReporterResult(result, reporter) : renderConformanceResult(result, format);
514
+ }
515
+ var readTextFile = (path6, encoding) => readFileSync(path6, encoding);
516
+ var JsonInputContext = class {
517
+ constructor(readFile2 = readTextFile) {
518
+ this.readFile = readFile2;
519
+ }
520
+ stdinConsumer;
521
+ readInputSource(value, label) {
522
+ if (value === "-") {
523
+ if (this.stdinConsumer) {
524
+ throw usageError(
525
+ `Cannot read ${label} from stdin because stdin was already consumed by ${this.stdinConsumer}. Use @file for one of the JSON inputs.`
526
+ );
527
+ }
528
+ try {
529
+ const contents = this.readFile(0, "utf8");
530
+ this.stdinConsumer = label;
531
+ return contents;
532
+ } catch (error) {
533
+ throw usageError(`Failed to read ${label} from stdin.`, {
534
+ source: error instanceof Error ? error.message : String(error)
535
+ });
536
+ }
537
+ }
538
+ if (!value.startsWith("@")) {
539
+ return value;
540
+ }
541
+ const filePath = value.slice(1);
542
+ if (!filePath) {
543
+ throw usageError(`${label} file path is required after @.`);
544
+ }
545
+ try {
546
+ return this.readFile(filePath, "utf8");
547
+ } catch (error) {
548
+ throw usageError(`Failed to read ${label} file "${filePath}".`, {
549
+ source: error instanceof Error ? error.message : String(error)
550
+ });
551
+ }
552
+ }
553
+ parseJsonInputValue(value, label) {
554
+ if (value === void 0) {
555
+ return void 0;
556
+ }
557
+ const source = this.readInputSource(value, label);
558
+ if (source.trim() === "") {
559
+ throw usageError(`${label} input is empty.`);
560
+ }
561
+ try {
562
+ return JSON.parse(source);
563
+ } catch (error) {
564
+ throw usageError(`${label} must be valid JSON.`, {
565
+ source: error instanceof Error ? error.message : String(error)
566
+ });
567
+ }
568
+ }
569
+ parseJsonInputRecord(value, label) {
570
+ const parsed = this.parseJsonInputValue(value, label);
571
+ if (parsed === void 0) {
572
+ return void 0;
573
+ }
574
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
575
+ throw usageError(`${label} must be a JSON object.`);
576
+ }
577
+ return parsed;
578
+ }
579
+ };
580
+ var defaultJsonInputContext = new JsonInputContext();
581
+ function readInputSource(value, label) {
582
+ return defaultJsonInputContext.readInputSource(value, label);
583
+ }
584
+ function parseJsonInputValue(value, label) {
585
+ return defaultJsonInputContext.parseJsonInputValue(value, label);
586
+ }
587
+ function parseJsonInputRecord(value, label) {
588
+ return defaultJsonInputContext.parseJsonInputRecord(value, label);
589
+ }
590
+ function parseReporterFormat(value) {
591
+ if (value === void 0) {
592
+ return void 0;
593
+ }
594
+ if (value === "json-summary" || value === "junit-xml") {
595
+ return value;
596
+ }
597
+ throw usageError(
598
+ `Invalid reporter "${value}". Use "json-summary" or "junit-xml".`
268
599
  );
269
600
  }
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";
601
+ function writeReporterResult(reporter, report) {
602
+ if (reporter === "junit-xml") {
603
+ process.stdout.write(renderStructuredRunJUnitXml(report));
604
+ return;
605
+ }
606
+ writeResult(renderStructuredRunJson(report), "json");
607
+ }
608
+ async function writeJsonArtifact(outputPath, payload) {
609
+ const resolvedPath = path2.resolve(process.cwd(), outputPath);
610
+ try {
611
+ await mkdir(path2.dirname(resolvedPath), { recursive: true });
612
+ await writeFile(
613
+ resolvedPath,
614
+ `${JSON.stringify(payload, null, 2)}
615
+ `,
616
+ "utf8"
617
+ );
618
+ } catch (error) {
619
+ throw operationalError(
620
+ `Failed to write JSON artifact to "${resolvedPath}".`,
621
+ {
622
+ source: error instanceof Error ? error.message : String(error)
623
+ }
624
+ );
625
+ }
626
+ return resolvedPath;
627
+ }
628
+ async function withEphemeralManager(config, fn, options) {
629
+ return withEphemeralClient(config, fn, {
630
+ serverId: "__cli__",
631
+ clientName: "mcpjam",
632
+ timeout: options?.timeout ?? 3e4,
633
+ rpcLogger: options?.rpcLogger,
634
+ retryPolicy: options?.retryPolicy
635
+ });
273
636
  }
274
637
 
275
638
  // src/lib/rpc-logs.ts
@@ -277,7 +640,6 @@ var CliRpcLogCollector = class {
277
640
  constructor(serverNamesById) {
278
641
  this.serverNamesById = serverNamesById;
279
642
  }
280
- serverNamesById;
281
643
  logs = [];
282
644
  rpcLogger = ({ direction, message, serverId }) => {
283
645
  this.logs.push({
@@ -324,24 +686,241 @@ function withRpcLogsIfRequested(value, collector, options) {
324
686
  }
325
687
  return attachCliRpcLogs(value, collector);
326
688
  }
327
-
328
- // src/lib/server-config.ts
329
- function collectString(value, previous = []) {
330
- return [...previous, value];
689
+ var CREDENTIALS_FILE_VERSION = 1;
690
+ var ACCESS_TOKEN_EXPIRY_SKEW_MS = 6e4;
691
+ async function writeCredentialsFile(outputPath, result, now = /* @__PURE__ */ new Date()) {
692
+ const resolvedPath = path2.resolve(process.cwd(), outputPath);
693
+ const contents = validateCredentialsFileContents(
694
+ { ...buildCredentialsFileContents(result, now) },
695
+ resolvedPath
696
+ );
697
+ const outputDirectory = path2.dirname(resolvedPath);
698
+ const temporaryPath = path2.join(
699
+ outputDirectory,
700
+ `.${path2.basename(resolvedPath)}.${randomUUID()}.tmp`
701
+ );
702
+ try {
703
+ await mkdir(outputDirectory, { recursive: true });
704
+ await writeFile(
705
+ temporaryPath,
706
+ `${JSON.stringify(contents, null, 2)}
707
+ `,
708
+ {
709
+ encoding: "utf8",
710
+ mode: 384
711
+ }
712
+ );
713
+ await chmod(temporaryPath, 384);
714
+ await rename(temporaryPath, resolvedPath);
715
+ } catch (error) {
716
+ await rm(temporaryPath, { force: true }).catch(() => void 0);
717
+ throw operationalError(
718
+ `Failed to write credentials file to "${resolvedPath}".`,
719
+ {
720
+ source: error instanceof Error ? error.message : String(error)
721
+ }
722
+ );
723
+ }
724
+ return resolvedPath;
331
725
  }
332
- function addSharedServerOptions(command) {
333
- return command.option("--url <url>", "HTTP MCP server URL").option("--access-token <token>", "Bearer access token for HTTP servers").option(
726
+ function readCredentialsFile(filePath) {
727
+ let raw;
728
+ try {
729
+ raw = readFileSync(filePath, "utf8");
730
+ } catch (error) {
731
+ throw usageError(
732
+ `Cannot read credentials file "${filePath}": ${error instanceof Error ? error.message : String(error)}`
733
+ );
734
+ }
735
+ let parsed;
736
+ try {
737
+ parsed = JSON.parse(raw);
738
+ } catch {
739
+ throw usageError(`Credentials file "${filePath}" is not valid JSON`);
740
+ }
741
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
742
+ throw usageError("Credentials file must be a JSON object");
743
+ }
744
+ return validateCredentialsFileContents(
745
+ parsed,
746
+ filePath
747
+ );
748
+ }
749
+ function resolveCredentialsFileAuth(filePath, serverUrl, now = /* @__PURE__ */ new Date()) {
750
+ const contents = readCredentialsFile(filePath);
751
+ assertMatchingServerUrl(contents.serverUrl, serverUrl, filePath);
752
+ if (contents.accessToken && isAccessTokenUsable(contents, now)) {
753
+ return { accessToken: contents.accessToken };
754
+ }
755
+ if (contents.refreshToken && contents.clientId) {
756
+ return {
757
+ refreshToken: contents.refreshToken,
758
+ clientId: contents.clientId,
759
+ ...contents.clientSecret ? { clientSecret: contents.clientSecret } : {}
760
+ };
761
+ }
762
+ if (contents.accessToken) {
763
+ throw usageError(
764
+ `Credentials file "${filePath}" has an expired access token and no refresh token credentials.`
765
+ );
766
+ }
767
+ throw usageError(`Credentials file "${filePath}" does not contain usable OAuth credentials.`);
768
+ }
769
+ function resolveCredentialsFileAccessToken(filePath, serverUrl, now = /* @__PURE__ */ new Date()) {
770
+ const contents = readCredentialsFile(filePath);
771
+ assertMatchingServerUrl(contents.serverUrl, serverUrl, filePath);
772
+ if (contents.accessToken && isAccessTokenUsable(contents, now)) {
773
+ return contents.accessToken;
774
+ }
775
+ throw usageError(
776
+ `Credentials file "${filePath}" does not contain a non-expired access token for this command.`
777
+ );
778
+ }
779
+ function assertNoCredentialsFileAuthConflicts(options) {
780
+ if (!options.credentialsFile || !(options.accessToken?.trim() || options.oauthAccessToken?.trim() || options.refreshToken?.trim() || options.clientId?.trim() || options.clientSecret?.trim())) {
781
+ return;
782
+ }
783
+ throw usageError(
784
+ "--credentials-file cannot be used together with --access-token, --oauth-access-token, --refresh-token, --client-id, or --client-secret."
785
+ );
786
+ }
787
+ function redactCredentialsFromResult(result, credentialsFilePath) {
788
+ const redacted = redactSensitiveValue(result);
789
+ const credentials = result.credentials;
790
+ const secretMarker = credentialsFilePath ? "[SAVED_TO_FILE]" : "[REDACTED]";
791
+ const redactedCredentials = {
792
+ ...redacted.credentials ?? {},
793
+ ...credentials.clientId ? { clientId: credentials.clientId } : {},
794
+ ...credentials.tokenType ? { tokenType: credentials.tokenType } : {},
795
+ ...credentials.expiresIn !== void 0 ? { expiresIn: credentials.expiresIn } : {},
796
+ ...credentials.accessToken ? { accessToken: secretMarker } : {},
797
+ ...credentials.refreshToken ? { refreshToken: secretMarker } : {},
798
+ ...credentials.clientSecret ? { clientSecret: secretMarker } : {}
799
+ };
800
+ return {
801
+ ...redacted,
802
+ credentials: redactedCredentials,
803
+ ...credentialsFilePath ? { credentialsFile: credentialsFilePath } : {}
804
+ };
805
+ }
806
+ function hasCredentialsToSave(result) {
807
+ return Boolean(result.credentials.accessToken || result.credentials.refreshToken);
808
+ }
809
+ function buildCredentialsFileContents(result, now) {
810
+ if (!hasCredentialsToSave(result)) {
811
+ throw usageError("OAuth login did not return usable credentials to save.");
812
+ }
813
+ const expiresAt = typeof result.credentials.expiresIn === "number" && Number.isFinite(result.credentials.expiresIn) ? new Date(now.getTime() + result.credentials.expiresIn * 1e3).toISOString() : void 0;
814
+ return {
815
+ version: CREDENTIALS_FILE_VERSION,
816
+ serverUrl: result.serverUrl,
817
+ ...result.credentials.accessToken ? { accessToken: result.credentials.accessToken } : {},
818
+ ...result.credentials.refreshToken ? { refreshToken: result.credentials.refreshToken } : {},
819
+ ...result.credentials.clientId ? { clientId: result.credentials.clientId } : {},
820
+ ...result.credentials.clientSecret ? { clientSecret: result.credentials.clientSecret } : {},
821
+ ...result.credentials.tokenType ? { tokenType: result.credentials.tokenType } : {},
822
+ ...expiresAt ? { expiresAt } : {},
823
+ ...result.protocolVersion ? { protocolVersion: result.protocolVersion } : {}
824
+ };
825
+ }
826
+ function validateCredentialsFileContents(value, filePath) {
827
+ if (value.version !== CREDENTIALS_FILE_VERSION) {
828
+ throw usageError(
829
+ `Unsupported credentials file version "${String(value.version)}".`
830
+ );
831
+ }
832
+ const contents = {
833
+ version: CREDENTIALS_FILE_VERSION,
834
+ serverUrl: requireString(value.serverUrl, "serverUrl"),
835
+ ...optionalStringField(value, "accessToken"),
836
+ ...optionalStringField(value, "refreshToken"),
837
+ ...optionalStringField(value, "clientId"),
838
+ ...optionalStringField(value, "clientSecret"),
839
+ ...optionalStringField(value, "tokenType"),
840
+ ...optionalStringField(value, "expiresAt"),
841
+ ...optionalStringField(value, "protocolVersion")
842
+ };
843
+ normalizeUrl(contents.serverUrl, "serverUrl");
844
+ if (!contents.accessToken && !contents.refreshToken) {
845
+ throw usageError(`Credentials file "${filePath}" does not contain OAuth tokens.`);
846
+ }
847
+ if (contents.refreshToken && !contents.clientId) {
848
+ throw usageError(
849
+ `Credentials file "${filePath}" with refreshToken requires clientId.`
850
+ );
851
+ }
852
+ if (contents.expiresAt) {
853
+ assertValidDate(contents.expiresAt, "expiresAt");
854
+ }
855
+ return contents;
856
+ }
857
+ function optionalStringField(value, key) {
858
+ const entry = value[key];
859
+ if (entry === void 0) {
860
+ return {};
861
+ }
862
+ return { [key]: requireString(entry, key) };
863
+ }
864
+ function requireString(value, label) {
865
+ if (typeof value !== "string" || !value.trim()) {
866
+ throw usageError(`${label} must be a non-empty string.`);
867
+ }
868
+ return value.trim();
869
+ }
870
+ function assertValidDate(value, label) {
871
+ if (Number.isNaN(Date.parse(value))) {
872
+ throw usageError(`${label} must be a valid ISO timestamp.`);
873
+ }
874
+ }
875
+ function assertMatchingServerUrl(credentialsServerUrl, serverUrl, filePath) {
876
+ if (normalizeUrl(credentialsServerUrl, "credentials file serverUrl") === normalizeUrl(serverUrl, "server URL")) {
877
+ return;
878
+ }
879
+ throw usageError(
880
+ `Credentials file "${filePath}" was issued for ${credentialsServerUrl}, not ${serverUrl}.`
881
+ );
882
+ }
883
+ function normalizeUrl(value, label) {
884
+ let parsed;
885
+ try {
886
+ parsed = new URL(value);
887
+ } catch {
888
+ throw usageError(`Invalid ${label}: ${value}`);
889
+ }
890
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
891
+ throw usageError(`${label} must use http or https: ${value}`);
892
+ }
893
+ const normalizedPathname = parsed.pathname.replace(/\/+$/u, "") || "/";
894
+ return `${parsed.origin}${normalizedPathname}${parsed.search}`;
895
+ }
896
+ function isAccessTokenUsable(contents, now) {
897
+ if (!contents.expiresAt) {
898
+ return true;
899
+ }
900
+ return Date.parse(contents.expiresAt) - now.getTime() > ACCESS_TOKEN_EXPIRY_SKEW_MS;
901
+ }
902
+
903
+ // src/lib/server-config.ts
904
+ var DEFAULT_CLI_RETRY_POLICY = {
905
+ retries: 0,
906
+ retryDelayMs: 3e3
907
+ };
908
+ function collectString(value, previous = []) {
909
+ return [...previous, value];
910
+ }
911
+ function addSharedServerOptions(command) {
912
+ return command.option(
913
+ "--transport <transport>",
914
+ 'Explicit transport type: "http" or "stdio"'
915
+ ).option("--url <url>", "HTTP MCP server URL").option("--access-token <token>", "Bearer access token for HTTP servers").option(
334
916
  "--oauth-access-token <token>",
335
917
  "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(
918
+ ).option("--refresh-token <token>", "OAuth refresh token for HTTP servers").option("--client-id <id>", "OAuth client ID used with --refresh-token").option(
343
919
  "--client-secret <secret>",
344
920
  "OAuth client secret used with --refresh-token"
921
+ ).option(
922
+ "--credentials-file <path>",
923
+ "Load OAuth credentials from a file created by oauth login --credentials-out"
345
924
  ).option(
346
925
  "--header <header>",
347
926
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
@@ -349,23 +928,29 @@ function addSharedServerOptions(command) {
349
928
  []
350
929
  ).option(
351
930
  "--client-capabilities <json>",
352
- "Client capabilities advertised to the server as a JSON object"
931
+ "Client capabilities as JSON, @path, or - for stdin"
353
932
  ).option("--command <command>", "Command for a stdio MCP server").option(
933
+ "--args <arg...>",
934
+ "Preferred stdio command arguments. Pass multiple values or repeat the flag."
935
+ ).option(
354
936
  "--command-args <arg>",
355
- "Stdio command argument. Repeat to pass multiple arguments.",
937
+ "Legacy stdio command argument. Repeat to pass multiple arguments.",
356
938
  collectString
357
939
  ).option(
358
- "--env <env>",
359
- 'Stdio environment assignment in "KEY=VALUE" format. Repeat to pass multiple assignments.',
360
- collectString
361
- );
940
+ "-e, --env <env...>",
941
+ 'Stdio environment assignment in "KEY=VALUE" format. Pass multiple values or repeat the flag.'
942
+ ).option("--cwd <path>", "Working directory for the stdio MCP server process");
362
943
  }
363
944
  function getGlobalOptions(command) {
364
945
  const options = command.optsWithGlobals();
365
946
  return {
366
- format: resolveOutputFormat(options.format, process.stdout.isTTY),
947
+ format: resolveOutputFormat(
948
+ options.format,
949
+ process.stdout.isTTY
950
+ ),
367
951
  timeout: options.timeout ?? 3e4,
368
- rpc: options.rpc ?? false
952
+ rpc: options.rpc ?? false,
953
+ quiet: options.quiet ?? false
369
954
  };
370
955
  }
371
956
  function parsePositiveInteger(value, label = "Value") {
@@ -375,6 +960,37 @@ function parsePositiveInteger(value, label = "Value") {
375
960
  }
376
961
  return parsed;
377
962
  }
963
+ function parseNonNegativeInteger(value, label = "Value") {
964
+ const parsed = Number(value);
965
+ if (!Number.isInteger(parsed) || parsed < 0) {
966
+ throw usageError(`${label} must be a non-negative integer.`);
967
+ }
968
+ return parsed;
969
+ }
970
+ function addRetryOptions(command) {
971
+ return command.option(
972
+ "--retries <count>",
973
+ "Retry transient failures this many times",
974
+ (value) => parseNonNegativeInteger(value, "Retries")
975
+ ).option(
976
+ "--retry-delay-ms <ms>",
977
+ "Fixed delay between retries in milliseconds",
978
+ (value) => parseNonNegativeInteger(value, "Retry delay")
979
+ );
980
+ }
981
+ function parseRetryPolicy(options = {}) {
982
+ if (options.retries === void 0 && options.retryDelayMs === void 0) {
983
+ return void 0;
984
+ }
985
+ const retries = options.retries ?? DEFAULT_CLI_RETRY_POLICY.retries;
986
+ if (options.retryDelayMs !== void 0 && retries === 0) {
987
+ throw usageError("--retry-delay-ms requires --retries to be greater than 0.");
988
+ }
989
+ return {
990
+ retries,
991
+ retryDelayMs: options.retryDelayMs ?? DEFAULT_CLI_RETRY_POLICY.retryDelayMs
992
+ };
993
+ }
378
994
  function parseHeadersOption(headers) {
379
995
  if (!headers || headers.length === 0) {
380
996
  return void 0;
@@ -382,21 +998,7 @@ function parseHeadersOption(headers) {
382
998
  return Object.fromEntries(headers.map(parseHeader));
383
999
  }
384
1000
  function parseJsonRecord(value, label) {
385
- if (value === void 0) {
386
- return void 0;
387
- }
388
- let parsed;
389
- try {
390
- parsed = JSON.parse(value);
391
- } catch (error) {
392
- throw usageError(`${label} must be valid JSON.`, {
393
- source: error instanceof Error ? error.message : String(error)
394
- });
395
- }
396
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
397
- throw usageError(`${label} must be a JSON object.`);
398
- }
399
- return parsed;
1001
+ return parseJsonInputRecord(value, label);
400
1002
  }
401
1003
  function parseUnknownRecord(value, label) {
402
1004
  if (value === void 0) {
@@ -430,7 +1032,9 @@ function resolveAliasedStringOption(options, aliases, label, config) {
430
1032
  flag: alias.flag,
431
1033
  value: normalized
432
1034
  };
433
- }).filter((entry) => entry !== void 0);
1035
+ }).filter(
1036
+ (entry) => entry !== void 0
1037
+ );
434
1038
  const flagsText = aliases.map((alias) => alias.flag).join(" or ");
435
1039
  if (provided.length === 0) {
436
1040
  if (config?.required) {
@@ -449,16 +1053,15 @@ function parseServerConfig(options) {
449
1053
  const command = options.command?.trim();
450
1054
  const hasUrl = Boolean(url);
451
1055
  const hasCommand = Boolean(command);
1056
+ const transport = resolveTargetTransport(options, hasUrl, hasCommand);
1057
+ const cwd = options.cwd?.trim();
452
1058
  const clientCapabilities = resolveClientCapabilities(
453
1059
  options.clientCapabilities
454
1060
  );
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) {
1061
+ if (transport === "http" && url) {
1062
+ if ((options.args?.length ?? 0) > 0 || (options.commandArgs?.length ?? 0) > 0 || (options.env?.length ?? 0) > 0 || cwd) {
460
1063
  throw usageError(
461
- "--command-args and --env can only be used together with --command."
1064
+ "--args, --command-args, --env, and --cwd can only be used together with --command."
462
1065
  );
463
1066
  }
464
1067
  try {
@@ -467,10 +1070,12 @@ function parseServerConfig(options) {
467
1070
  throw usageError(`Invalid URL: ${url}`);
468
1071
  }
469
1072
  const headers = parseHeadersOption(options.header);
470
- const accessToken = resolveHttpAccessToken(options);
471
- const refreshToken = options.refreshToken?.trim();
472
- const clientId = options.clientId?.trim();
473
- const clientSecret = options.clientSecret?.trim();
1073
+ assertNoCredentialsFileAuthConflicts(options);
1074
+ const fileCredentials = options.credentialsFile ? resolveCredentialsFileAuth(options.credentialsFile, url) : void 0;
1075
+ const accessToken = resolveHttpAccessToken(options) ?? fileCredentials?.accessToken;
1076
+ const refreshToken = normalizeOptionalAuthValue(options.refreshToken) ?? fileCredentials?.refreshToken;
1077
+ const clientId = normalizeOptionalAuthValue(options.clientId) ?? fileCredentials?.clientId;
1078
+ const clientSecret = normalizeOptionalAuthValue(options.clientSecret) ?? fileCredentials?.clientSecret;
474
1079
  if (refreshToken && accessToken) {
475
1080
  throw usageError(
476
1081
  "--refresh-token cannot be used together with --access-token or --oauth-access-token."
@@ -498,17 +1103,18 @@ function parseServerConfig(options) {
498
1103
  if (!command) {
499
1104
  throw usageError("Missing stdio command.");
500
1105
  }
501
- if (options.accessToken || options.oauthAccessToken || options.refreshToken || options.clientId || options.clientSecret || (options.header?.length ?? 0) > 0) {
1106
+ if (options.accessToken || options.oauthAccessToken || options.refreshToken || options.clientId || options.clientSecret || options.credentialsFile || (options.header?.length ?? 0) > 0) {
502
1107
  throw usageError(
503
- "--access-token, --oauth-access-token, --refresh-token, --client-id, --client-secret, and --header can only be used together with --url."
1108
+ "--access-token, --oauth-access-token, --refresh-token, --client-id, --client-secret, --credentials-file, and --header can only be used together with --url."
504
1109
  );
505
1110
  }
506
1111
  return {
507
1112
  command,
508
- args: parseCommandArgs(options.commandArgs),
1113
+ args: parseCommandArgs(options.args, options.commandArgs),
509
1114
  env: parseEnvironmentOption(options.env),
1115
+ ...cwd ? { cwd } : {},
510
1116
  ...clientCapabilities ? { clientCapabilities } : {},
511
- stderr: "ignore",
1117
+ stderr: "pipe",
512
1118
  timeout: options.timeout
513
1119
  };
514
1120
  }
@@ -518,7 +1124,7 @@ function addGlobalOptions(program) {
518
1124
  "Request timeout in milliseconds",
519
1125
  (value) => parsePositiveInteger(value, "Timeout"),
520
1126
  3e4
521
- ).option("--rpc", "Include RPC logs in JSON output").option("--format <format>", "Output format");
1127
+ ).option("--rpc", "Include RPC logs in JSON output").option("--quiet", "Suppress non-result progress output").option("--format <format>", "Output format");
522
1128
  }
523
1129
  function describeTarget(options) {
524
1130
  return options.url?.trim() || options.command?.trim() || "__cli__";
@@ -537,11 +1143,12 @@ function parseHeader(entry) {
537
1143
  }
538
1144
  return [key, value];
539
1145
  }
540
- function parseCommandArgs(values) {
541
- if (!values || values.length === 0) {
1146
+ function parseCommandArgs(values, legacyValues) {
1147
+ const combined = [...values ?? [], ...legacyValues ?? []];
1148
+ if (combined.length === 0) {
542
1149
  return void 0;
543
1150
  }
544
- return values;
1151
+ return combined;
545
1152
  }
546
1153
  function parseEnvironmentOption(values) {
547
1154
  if (!values || values.length === 0) {
@@ -575,9 +1182,45 @@ function resolveClientCapabilities(value) {
575
1182
  }
576
1183
  return parseUnknownRecord(value, "Client capabilities");
577
1184
  }
1185
+ function resolveTargetTransport(options, hasUrl, hasCommand) {
1186
+ const transport = resolveTransportOption(options.transport);
1187
+ if (!transport) {
1188
+ if (hasUrl === hasCommand) {
1189
+ throw usageError("Specify exactly one target: either --url or --command.");
1190
+ }
1191
+ return hasUrl ? "http" : "stdio";
1192
+ }
1193
+ if (transport === "http") {
1194
+ if (!hasUrl) {
1195
+ throw usageError("--transport http requires --url.");
1196
+ }
1197
+ if (hasCommand) {
1198
+ throw usageError("--command can only be used with --transport stdio.");
1199
+ }
1200
+ return transport;
1201
+ }
1202
+ if (!hasCommand) {
1203
+ throw usageError("--transport stdio requires --command.");
1204
+ }
1205
+ if (hasUrl) {
1206
+ throw usageError("--url can only be used with --transport http.");
1207
+ }
1208
+ return transport;
1209
+ }
1210
+ function resolveTransportOption(value) {
1211
+ if (value === void 0) {
1212
+ return void 0;
1213
+ }
1214
+ if (value === "http" || value === "stdio") {
1215
+ return value;
1216
+ }
1217
+ throw usageError(
1218
+ `Invalid transport "${value}". Use "http" or "stdio".`
1219
+ );
1220
+ }
578
1221
  function resolveHttpAccessToken(options) {
579
- const accessToken = options.accessToken?.trim();
580
- const oauthAccessToken = options.oauthAccessToken?.trim();
1222
+ const accessToken = normalizeOptionalAuthValue(options.accessToken);
1223
+ const oauthAccessToken = normalizeOptionalAuthValue(options.oauthAccessToken);
581
1224
  if (accessToken && oauthAccessToken && accessToken !== oauthAccessToken) {
582
1225
  throw usageError(
583
1226
  "--access-token and --oauth-access-token must match when both are provided."
@@ -585,131 +1228,953 @@ function resolveHttpAccessToken(options) {
585
1228
  }
586
1229
  return accessToken ?? oauthAccessToken;
587
1230
  }
588
-
589
- // src/commands/apps.ts
590
- var APPS_CHECK_IDS_BY_CATEGORY = {
591
- tools: [
592
- "ui-tools-present",
593
- "ui-tool-metadata-valid",
594
- "ui-tool-input-schema-valid"
595
- ],
596
- resources: [
597
- "ui-listed-resources-valid",
598
- "ui-resources-readable",
599
- "ui-resource-contents-valid",
600
- "ui-resource-meta-valid"
601
- ]
602
- };
603
- function registerAppsCommands(program) {
604
- const apps = program.command("apps").description("MCP Apps utilities, widget extraction, and conformance checks");
605
- addSharedServerOptions(
606
- apps.command("conformance").description("Run MCP Apps server conformance checks").option(
607
- "--category <category>",
608
- "Check category to run. Repeat for multiple. Default: all.",
609
- (value, previous = []) => [...previous, value],
610
- []
611
- ).option(
612
- "--check-id <id>",
613
- "Specific check ID to run. Repeat for multiple. Default: all.",
614
- (value, previous = []) => [...previous, value],
615
- []
616
- )
617
- ).action(async (options, command) => {
618
- const globalOptions = getGlobalOptions(command);
619
- const target = describeTarget(options);
620
- const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
621
- const config = {
622
- ...buildAppsConformanceConfig({
623
- ...options,
624
- timeout: globalOptions.timeout
625
- }),
626
- ...collector ? { rpcLogger: collector.rpcLogger } : {}
627
- };
628
- const result = await new sdk.MCPAppsConformanceTest(config).run();
629
- writeResult(
630
- withRpcLogsIfRequested(result, collector, globalOptions),
631
- globalOptions.format
1231
+ function normalizeOptionalAuthValue(value) {
1232
+ const trimmed = value?.trim();
1233
+ return trimmed ? trimmed : void 0;
1234
+ }
1235
+ var FALLBACK_INSPECTOR_BASE_URL = "http://127.0.0.1:6274";
1236
+ var DEFAULT_START_TIMEOUT_MS = 3e4;
1237
+ var DEFAULT_COMMAND_TIMEOUT_MS = 3e4;
1238
+ var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
1239
+ var COMMAND_FETCH_TIMEOUT_BUFFER_MS = 2e3;
1240
+ var HEALTH_FETCH_TIMEOUT_MS = 2e3;
1241
+ var SESSION_TOKEN_TIMEOUT_MS = 3e3;
1242
+ var STOP_FETCH_TIMEOUT_MS = 3e3;
1243
+ var STARTUP_LOG_MAX_BYTES = 1024 * 1024;
1244
+ var TOKEN_TTL_MS = 5 * 6e4;
1245
+ var tokenCache = /* @__PURE__ */ new Map();
1246
+ var tokenRequests = /* @__PURE__ */ new Map();
1247
+ function normalizeInspectorBaseUrl(baseUrl) {
1248
+ const value = baseUrl?.trim() || process.env.MCPJAM_INSPECTOR_URL?.trim() || FALLBACK_INSPECTOR_BASE_URL;
1249
+ try {
1250
+ const parsed = new URL(value);
1251
+ parsed.hash = "";
1252
+ parsed.search = "";
1253
+ return parsed.href.replace(/\/$/, "");
1254
+ } catch (error) {
1255
+ throw operationalError(
1256
+ `Invalid Inspector URL "${value}".`,
1257
+ error instanceof Error ? error.message : String(error)
632
1258
  );
633
- if (!result.passed) {
634
- setProcessExitCode(1);
1259
+ }
1260
+ }
1261
+ function buildInspectorUrl(baseUrl, tab) {
1262
+ if (!tab || !tab.trim()) {
1263
+ return baseUrl;
1264
+ }
1265
+ return `${baseUrl}/#${tab.trim()}`;
1266
+ }
1267
+ async function ensureInspector(options = {}) {
1268
+ const baseUrl = normalizeInspectorBaseUrl(options.baseUrl);
1269
+ const health = await getInspectorHealth(baseUrl);
1270
+ if (health.healthy) {
1271
+ if (options.openBrowser && !health.hasActiveClient) {
1272
+ openUrl(buildInspectorUrl(baseUrl, options.tab));
635
1273
  }
636
- });
637
- addSharedServerOptions(
638
- 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(
639
- "--csp-mode <mode>",
640
- "CSP mode: permissive or widget-declared"
641
- ).option("--template <uri>", "Optional ui:// template override").option("--view-mode <mode>", "Widget view mode").option("--view-params <json>", "Widget view params as JSON")
642
- ).action(async (options, command) => {
643
- const globalOptions = getGlobalOptions(command);
644
- const target = describeTarget(options);
645
- const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
646
- const resourceUri = resolveAliasedStringOption(
647
- options,
648
- [
649
- { key: "resourceUri", flag: "--resource-uri" },
650
- { key: "uri", flag: "--uri" }
651
- ],
652
- "Widget resource URI",
653
- { required: true }
1274
+ return { baseUrl, started: false };
1275
+ }
1276
+ if (!options.startIfNeeded) {
1277
+ throw operationalError(
1278
+ "Inspector is not running. Run `mcpjam inspector open` first or pass an Inspector-backed option that starts it."
654
1279
  );
655
- const config = parseServerConfig({
656
- ...options,
657
- timeout: globalOptions.timeout
1280
+ }
1281
+ await startInspector(baseUrl, options.timeoutMs ?? DEFAULT_START_TIMEOUT_MS);
1282
+ clearInspectorSessionTokenCache(baseUrl);
1283
+ if (options.openBrowser) {
1284
+ openUrl(buildInspectorUrl(baseUrl, options.tab));
1285
+ }
1286
+ return { baseUrl, started: true };
1287
+ }
1288
+ async function stopInspector(baseUrl) {
1289
+ const normalized = normalizeInspectorBaseUrl(baseUrl);
1290
+ if (!await isInspectorHealthy(normalized)) {
1291
+ return { stopped: false, baseUrl: normalized };
1292
+ }
1293
+ const fetchShutdown = async () => {
1294
+ const token = await fetchInspectorSessionToken(normalized);
1295
+ return await fetch(`${normalized}/api/shutdown`, {
1296
+ method: "POST",
1297
+ headers: {
1298
+ "X-MCP-Session-Auth": `Bearer ${token}`
1299
+ },
1300
+ signal: AbortSignal.timeout(STOP_FETCH_TIMEOUT_MS)
658
1301
  });
659
- const result = await withEphemeralManager(
660
- config,
661
- (manager, serverId) => buildMcpWidgetContent(manager, serverId, {
662
- resourceUri,
663
- toolId: options.toolId,
664
- toolName: options.toolName,
665
- toolInput: parseJsonRecord(options.toolInput, "Tool input") ?? {},
666
- toolOutput: parseJsonValue(options.toolOutput),
667
- theme: parseTheme(options.theme),
668
- cspMode: parseCspMode(options.cspMode),
669
- template: options.template,
670
- viewMode: options.viewMode,
671
- viewParams: parseJsonRecord(options.viewParams, "View params")
672
- }),
673
- {
674
- timeout: globalOptions.timeout,
675
- rpcLogger: collector?.rpcLogger
676
- }
1302
+ };
1303
+ try {
1304
+ let response = await fetchShutdown();
1305
+ if (isAuthFailure(response)) {
1306
+ clearInspectorSessionTokenCache(normalized);
1307
+ response = await fetchShutdown();
1308
+ }
1309
+ if (response.ok) {
1310
+ clearInspectorSessionTokenCache(normalized);
1311
+ }
1312
+ return { stopped: response.ok, baseUrl: normalized };
1313
+ } catch {
1314
+ return { stopped: false, baseUrl: normalized };
1315
+ }
1316
+ }
1317
+ var InspectorApiClient = class {
1318
+ baseUrl;
1319
+ constructor(options = {}) {
1320
+ this.baseUrl = normalizeInspectorBaseUrl(options.baseUrl);
1321
+ }
1322
+ async ensure(options = {}) {
1323
+ return ensureInspector({ ...options, baseUrl: this.baseUrl });
1324
+ }
1325
+ async connectServer(serverId, serverConfig) {
1326
+ return this.request("/api/mcp/connect", {
1327
+ method: "POST",
1328
+ body: { serverId, serverConfig }
1329
+ });
1330
+ }
1331
+ async listServers() {
1332
+ return this.request("/api/mcp/servers");
1333
+ }
1334
+ async getServerStatus(serverId) {
1335
+ return this.request(
1336
+ `/api/mcp/servers/status/${encodeURIComponent(serverId)}`
677
1337
  );
678
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
679
- });
680
- addSharedServerOptions(
681
- 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(
682
- "--tool-response-metadata <json>",
683
- "Tool response metadata as a JSON object"
684
- ).option("--theme <theme>", "Widget theme: light or dark").option(
685
- "--csp-mode <mode>",
686
- "CSP mode: permissive or widget-declared"
687
- ).option("--locale <locale>", "Locale override").option("--device-type <type>", "Device type: mobile, tablet, or desktop")
688
- ).action(async (options, command) => {
689
- const globalOptions = getGlobalOptions(command);
690
- const target = describeTarget(options);
691
- const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
692
- const resourceUri = resolveAliasedStringOption(
693
- options,
694
- [
695
- { key: "resourceUri", flag: "--resource-uri" },
696
- { key: "uri", flag: "--uri" }
697
- ],
698
- "Widget resource URI",
699
- { required: true }
1338
+ }
1339
+ async getInitInfo(serverId) {
1340
+ return this.request(
1341
+ `/api/mcp/servers/init-info/${encodeURIComponent(serverId)}`
700
1342
  );
701
- const config = parseServerConfig({
702
- ...options,
703
- timeout: globalOptions.timeout
1343
+ }
1344
+ async listTools(serverId, options = {}) {
1345
+ return this.request("/api/mcp/tools/list", {
1346
+ method: "POST",
1347
+ body: { serverId, ...options }
704
1348
  });
705
- const result = await withEphemeralManager(
706
- config,
707
- (manager, serverId) => buildChatGptWidgetContent(manager, serverId, {
708
- uri: resourceUri,
1349
+ }
1350
+ async executeTool(serverId, toolName, parameters = {}) {
1351
+ return this.request("/api/mcp/tools/execute", {
1352
+ method: "POST",
1353
+ body: { serverId, toolName, parameters }
1354
+ });
1355
+ }
1356
+ async respondToElicitation(executionId, requestId, response) {
1357
+ return this.request("/api/mcp/tools/respond", {
1358
+ method: "POST",
1359
+ body: { executionId, requestId, response }
1360
+ });
1361
+ }
1362
+ async executeCommand(request) {
1363
+ const commandTimeoutMs = typeof request.timeoutMs === "number" && request.timeoutMs > 0 ? request.timeoutMs : DEFAULT_COMMAND_TIMEOUT_MS;
1364
+ const fetchCommand = async () => {
1365
+ const token = await fetchInspectorSessionToken(this.baseUrl);
1366
+ return await fetch(`${this.baseUrl}/api/mcp/command`, {
1367
+ method: "POST",
1368
+ headers: {
1369
+ "Content-Type": "application/json",
1370
+ "X-MCP-Session-Auth": `Bearer ${token}`
1371
+ },
1372
+ body: JSON.stringify(request),
1373
+ signal: AbortSignal.timeout(
1374
+ commandTimeoutMs + COMMAND_FETCH_TIMEOUT_BUFFER_MS
1375
+ )
1376
+ });
1377
+ };
1378
+ let response;
1379
+ try {
1380
+ response = await fetchCommand();
1381
+ if (isAuthFailure(response)) {
1382
+ clearInspectorSessionTokenCache(this.baseUrl);
1383
+ response = await fetchCommand();
1384
+ }
1385
+ } catch (error) {
1386
+ throw operationalError(
1387
+ `Failed to contact Inspector at ${this.baseUrl}.`,
1388
+ error instanceof Error ? error.message : String(error)
1389
+ );
1390
+ }
1391
+ if (isAuthFailure(response)) {
1392
+ throw operationalError(
1393
+ `Inspector command request failed authentication with ${response.status}.`
1394
+ );
1395
+ }
1396
+ const payload = await readResponsePayload(response);
1397
+ if (isInspectorCommandResponse(payload)) {
1398
+ return payload;
1399
+ }
1400
+ if (!response.ok) {
1401
+ throw operationalError(
1402
+ getErrorMessage(payload) ?? `Inspector command request failed with ${response.status}.`,
1403
+ payload
1404
+ );
1405
+ }
1406
+ throw operationalError("Inspector command response was invalid.", payload);
1407
+ }
1408
+ async request(path6, init = {}) {
1409
+ const fetchRequest = async () => {
1410
+ const token = await fetchInspectorSessionToken(this.baseUrl);
1411
+ const { body: initBody, timeoutMs, ...fetchInit } = init;
1412
+ const headers = new Headers(fetchInit.headers);
1413
+ headers.set("X-MCP-Session-Auth", `Bearer ${token}`);
1414
+ let body;
1415
+ if (initBody !== void 0) {
1416
+ headers.set("Content-Type", "application/json");
1417
+ body = JSON.stringify(initBody);
1418
+ }
1419
+ return await fetch(`${this.baseUrl}${path6}`, {
1420
+ ...fetchInit,
1421
+ signal: fetchInit.signal ?? AbortSignal.timeout(timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS),
1422
+ headers,
1423
+ body
1424
+ });
1425
+ };
1426
+ let response;
1427
+ try {
1428
+ response = await fetchRequest();
1429
+ if (isAuthFailure(response)) {
1430
+ clearInspectorSessionTokenCache(this.baseUrl);
1431
+ response = await fetchRequest();
1432
+ }
1433
+ } catch (error) {
1434
+ throw operationalError(
1435
+ `Failed to contact Inspector at ${this.baseUrl}.`,
1436
+ error instanceof Error ? error.message : String(error)
1437
+ );
1438
+ }
1439
+ const payload = await readResponsePayload(response);
1440
+ if (!response.ok) {
1441
+ throw operationalError(
1442
+ getErrorMessage(payload) ?? `Inspector request ${path6} failed with ${response.status}.`,
1443
+ payload
1444
+ );
1445
+ }
1446
+ return payload;
1447
+ }
1448
+ };
1449
+ async function fetchInspectorSessionToken(baseUrl) {
1450
+ const normalizedBaseUrl = normalizeInspectorBaseUrl(baseUrl);
1451
+ const cached = tokenCache.get(normalizedBaseUrl);
1452
+ if (cached && Date.now() - cached.fetchedAt < TOKEN_TTL_MS) {
1453
+ return cached.token;
1454
+ }
1455
+ const pending = tokenRequests.get(normalizedBaseUrl);
1456
+ if (pending) {
1457
+ return pending;
1458
+ }
1459
+ const request = fetchFreshInspectorSessionToken(normalizedBaseUrl).finally(
1460
+ () => {
1461
+ tokenRequests.delete(normalizedBaseUrl);
1462
+ }
1463
+ );
1464
+ tokenRequests.set(normalizedBaseUrl, request);
1465
+ return request;
1466
+ }
1467
+ function clearInspectorSessionTokenCache(baseUrl) {
1468
+ if (!baseUrl) {
1469
+ tokenCache.clear();
1470
+ tokenRequests.clear();
1471
+ return;
1472
+ }
1473
+ const normalizedBaseUrl = normalizeInspectorBaseUrl(baseUrl);
1474
+ tokenCache.delete(normalizedBaseUrl);
1475
+ tokenRequests.delete(normalizedBaseUrl);
1476
+ }
1477
+ async function fetchFreshInspectorSessionToken(normalizedBaseUrl) {
1478
+ let response;
1479
+ try {
1480
+ response = await fetch(`${normalizedBaseUrl}/api/session-token`, {
1481
+ signal: AbortSignal.timeout(SESSION_TOKEN_TIMEOUT_MS)
1482
+ });
1483
+ } catch (error) {
1484
+ throw operationalError(
1485
+ "Failed to contact the local Inspector session-token endpoint.",
1486
+ error instanceof Error ? error.message : String(error)
1487
+ );
1488
+ }
1489
+ if (!response.ok) {
1490
+ throw operationalError(
1491
+ `Inspector session-token request failed with ${response.status}.`
1492
+ );
1493
+ }
1494
+ const body = await response.json();
1495
+ if (typeof body.token !== "string" || !body.token) {
1496
+ throw operationalError("Inspector session-token response was invalid.");
1497
+ }
1498
+ tokenCache.set(normalizedBaseUrl, {
1499
+ token: body.token,
1500
+ fetchedAt: Date.now()
1501
+ });
1502
+ return body.token;
1503
+ }
1504
+ function getInspectorStartScriptPath() {
1505
+ return fileURLToPath(
1506
+ new URL("../../../mcpjam-inspector/bin/start.js", import.meta.url)
1507
+ );
1508
+ }
1509
+ async function getInspectorHealth(baseUrl, timeoutMs = HEALTH_FETCH_TIMEOUT_MS) {
1510
+ try {
1511
+ const response = await fetch(`${baseUrl}/health`, {
1512
+ signal: AbortSignal.timeout(timeoutMs)
1513
+ });
1514
+ if (!response.ok) {
1515
+ return { healthy: false, hasActiveClient: false };
1516
+ }
1517
+ const body = await response.json();
1518
+ return {
1519
+ healthy: true,
1520
+ hasActiveClient: body.hasActiveClient === true
1521
+ };
1522
+ } catch {
1523
+ return { healthy: false, hasActiveClient: false };
1524
+ }
1525
+ }
1526
+ async function isInspectorHealthy(baseUrl) {
1527
+ const status = await getInspectorHealth(baseUrl);
1528
+ return status.healthy;
1529
+ }
1530
+ function getNpxExecutable(platform = process.platform) {
1531
+ return platform === "win32" ? "npx.cmd" : "npx";
1532
+ }
1533
+ async function startInspector(baseUrl, timeoutMs) {
1534
+ const parsedUrl = new URL(baseUrl);
1535
+ const port = parsedUrl.port || "6274";
1536
+ const startScriptPath = getInspectorStartScriptPath();
1537
+ const hasStartScript = existsSync(startScriptPath);
1538
+ const args = hasStartScript ? [startScriptPath, "--port", port] : ["-y", "@mcpjam/inspector@latest", "--port", port];
1539
+ const executable = hasStartScript ? process.execPath : getNpxExecutable();
1540
+ const logPath = getInspectorStartupLogPath();
1541
+ const logFd = openStartupLogFile(logPath);
1542
+ let child;
1543
+ try {
1544
+ child = spawn(executable, args, {
1545
+ cwd: hasStartScript ? path2.dirname(startScriptPath) : process.cwd(),
1546
+ detached: true,
1547
+ stdio: ["ignore", logFd, logFd],
1548
+ env: {
1549
+ ...process.env,
1550
+ HOST: parsedUrl.hostname
1551
+ }
1552
+ });
1553
+ } finally {
1554
+ closeSync(logFd);
1555
+ }
1556
+ child.unref();
1557
+ const startedAt = Date.now();
1558
+ while (Date.now() - startedAt < timeoutMs) {
1559
+ if (await isInspectorHealthy(baseUrl)) {
1560
+ return;
1561
+ }
1562
+ await delay(250);
1563
+ }
1564
+ throw operationalError(
1565
+ `Inspector did not become ready within ${timeoutMs}ms. Startup log: ${logPath}`
1566
+ );
1567
+ }
1568
+ function isAuthFailure(response) {
1569
+ return response.status === 401 || response.status === 403;
1570
+ }
1571
+ function getInspectorStartupLogPath() {
1572
+ return path2.join(os.tmpdir(), "mcpjam-inspector-startup.log");
1573
+ }
1574
+ function openStartupLogFile(logPath) {
1575
+ try {
1576
+ if (existsSync(logPath) && statSync(logPath).size > STARTUP_LOG_MAX_BYTES) {
1577
+ renameSync(logPath, `${logPath}.1`);
1578
+ }
1579
+ } catch {
1580
+ }
1581
+ return openSync(logPath, "a");
1582
+ }
1583
+ function openUrl(url) {
1584
+ if (process.env.MCPJAM_CLI_DISABLE_BROWSER_OPEN === "1") {
1585
+ return;
1586
+ }
1587
+ const platform = process.platform;
1588
+ const child = platform === "darwin" ? spawn("open", [url], { detached: true, stdio: "ignore" }) : platform === "win32" ? spawn("cmd", ["/c", "start", "", url], {
1589
+ detached: true,
1590
+ stdio: "ignore"
1591
+ }) : spawn("xdg-open", [url], { detached: true, stdio: "ignore" });
1592
+ child.on("error", () => {
1593
+ });
1594
+ child.unref();
1595
+ }
1596
+ function delay(ms) {
1597
+ return new Promise((resolve) => {
1598
+ setTimeout(resolve, ms);
1599
+ });
1600
+ }
1601
+ async function readResponsePayload(response) {
1602
+ const text = await response.text();
1603
+ if (!text) {
1604
+ return null;
1605
+ }
1606
+ try {
1607
+ return JSON.parse(text);
1608
+ } catch {
1609
+ return text;
1610
+ }
1611
+ }
1612
+ function getErrorMessage(payload) {
1613
+ if (!payload || typeof payload !== "object") {
1614
+ return typeof payload === "string" ? payload : void 0;
1615
+ }
1616
+ const record = payload;
1617
+ if (typeof record.error === "string") {
1618
+ return record.error;
1619
+ }
1620
+ if (typeof record.message === "string") {
1621
+ return record.message;
1622
+ }
1623
+ return void 0;
1624
+ }
1625
+ function isInspectorCommandResponse(value) {
1626
+ if (!value || typeof value !== "object") {
1627
+ return false;
1628
+ }
1629
+ const record = value;
1630
+ if (typeof record.id !== "string") {
1631
+ return false;
1632
+ }
1633
+ if (record.status === "success") {
1634
+ return true;
1635
+ }
1636
+ if (record.status !== "error") {
1637
+ return false;
1638
+ }
1639
+ const error = record.error;
1640
+ return Boolean(
1641
+ error && typeof error === "object" && typeof error.code === "string" && typeof error.message === "string"
1642
+ );
1643
+ }
1644
+ async function listToolsWithMetadata(manager, params) {
1645
+ const result = await manager.listTools(
1646
+ params.serverId,
1647
+ params.cursor ? { cursor: params.cursor } : void 0
1648
+ );
1649
+ const tools = result.tools ?? [];
1650
+ const toolsMetadata = manager.getAllToolsMetadata(params.serverId);
1651
+ const tokenCount = params.modelId ? estimateTokensFromChars(JSON.stringify(tools)) : void 0;
1652
+ return {
1653
+ tools,
1654
+ nextCursor: result.nextCursor,
1655
+ toolsMetadata,
1656
+ ...tokenCount === void 0 ? {} : { tokenCount }
1657
+ };
1658
+ }
1659
+ function estimateTokensFromChars(text) {
1660
+ return Math.ceil(text.length / 4);
1661
+ }
1662
+
1663
+ // src/commands/apps-debug.ts
1664
+ function registerAppsDebugCommand(parent) {
1665
+ addRetryOptions(
1666
+ addSharedServerOptions(
1667
+ parent.command("debug").description("Debug an MCP App tool call from the CLI").requiredOption("--tool-name <name>", "Tool name to execute").option(
1668
+ "--params <json>",
1669
+ "Tool parameters as JSON, @path, or - for stdin"
1670
+ ).option(
1671
+ "--ui",
1672
+ "Open the Inspector UI to render the App after execution"
1673
+ ).option("--inspector-url <url>", "Local Inspector base URL (with --ui)").option(
1674
+ "--server-name <name>",
1675
+ "Server name inside Inspector (with --ui)"
1676
+ ).option(
1677
+ "--protocol <protocol>",
1678
+ 'Render protocol: "mcp-apps" or "openai-sdk" (with --ui)'
1679
+ ).option(
1680
+ "--device <device>",
1681
+ 'Render device: "mobile", "tablet", "desktop", or "custom" (with --ui)'
1682
+ ).option(
1683
+ "--theme <theme>",
1684
+ 'Render theme: "light" or "dark" (with --ui)'
1685
+ ).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")
1686
+ )
1687
+ ).action(async (options, command) => {
1688
+ const globalOptions = getGlobalOptions(command);
1689
+ const retryPolicy = parseRetryPolicy(options);
1690
+ const target = describeTarget(options);
1691
+ const toolName = options.toolName;
1692
+ const params = parseJsonRecord(options.params, "Tool parameters") ?? {};
1693
+ const serverName = typeof options.serverName === "string" && options.serverName.trim() ? options.serverName.trim() : buildInspectorServerName(options);
1694
+ const config = parseServerConfig({
1695
+ ...options,
1696
+ timeout: globalOptions.timeout
1697
+ });
1698
+ const sdkResult = await runSdkAppsDebug({
1699
+ config,
1700
+ params,
1701
+ retryPolicy,
1702
+ toolName
1703
+ });
1704
+ const uiResult = options.ui ? await runUiRender({
1705
+ baseUrl: options.inspectorUrl,
1706
+ config,
1707
+ params,
1708
+ renderContext: {
1709
+ protocol: parseRenderProtocol(options.protocol),
1710
+ deviceType: parseRenderDevice(options.device),
1711
+ theme: parseTheme(options.theme),
1712
+ locale: trimOptional(options.locale),
1713
+ timeZone: trimOptional(options.timeZone)
1714
+ },
1715
+ serverName,
1716
+ timeoutMs: globalOptions.timeout,
1717
+ toolName,
1718
+ toolResult: sdkResult.execution
1719
+ }) : void 0;
1720
+ const inspectorRenderError = uiResult ? findInspectorRenderError(uiResult) : void 0;
1721
+ const sdkExecutionError = normalizeSdkExecutionError(sdkResult.execution);
1722
+ const payload = {
1723
+ success: !inspectorRenderError && !sdkExecutionError,
1724
+ command: "apps debug",
1725
+ inspectorUi: Boolean(options.ui),
1726
+ target,
1727
+ toolName,
1728
+ params,
1729
+ ...sdkResult,
1730
+ ...uiResult ? { inspectorRender: uiResult } : {},
1731
+ ...inspectorRenderError ? { error: inspectorRenderError } : sdkExecutionError ? { error: sdkExecutionError } : {}
1732
+ };
1733
+ if (inspectorRenderError || sdkExecutionError) {
1734
+ setProcessExitCode(1);
1735
+ }
1736
+ if (options.out) {
1737
+ const artifactPath = await writeJsonArtifact(options.out, payload);
1738
+ writeResult({ ...payload, artifactPath }, globalOptions.format);
1739
+ return;
1740
+ }
1741
+ writeResult(payload, globalOptions.format);
1742
+ });
1743
+ }
1744
+ async function runSdkAppsDebug(options) {
1745
+ return withEphemeralManager(
1746
+ options.config,
1747
+ async (manager, serverId) => {
1748
+ const toolsData = await listToolsWithMetadata(manager, { serverId });
1749
+ const execution = await manager.executeTool(
1750
+ serverId,
1751
+ options.toolName,
1752
+ options.params
1753
+ );
1754
+ return buildAppsDebugResult({
1755
+ execution,
1756
+ toolsData,
1757
+ toolName: options.toolName
1758
+ });
1759
+ },
1760
+ {
1761
+ retryPolicy: options.retryPolicy
1762
+ }
1763
+ );
1764
+ }
1765
+ async function runUiRender(options) {
1766
+ const client = new InspectorApiClient({ baseUrl: options.baseUrl });
1767
+ const ensureResult = await client.ensure({
1768
+ openBrowser: true,
1769
+ startIfNeeded: true,
1770
+ tab: "app-builder",
1771
+ timeoutMs: options.timeoutMs
1772
+ });
1773
+ await client.connectServer(options.serverName, options.config);
1774
+ const renderResult = await runInspectorAppRender({
1775
+ client,
1776
+ params: options.params,
1777
+ renderContext: options.renderContext,
1778
+ serverName: options.serverName,
1779
+ timeoutMs: options.timeoutMs,
1780
+ toolName: options.toolName,
1781
+ toolResult: options.toolResult
1782
+ });
1783
+ return {
1784
+ baseUrl: ensureResult.baseUrl,
1785
+ inspectorStarted: ensureResult.started,
1786
+ ...renderResult
1787
+ };
1788
+ }
1789
+ async function runInspectorAppRender(options) {
1790
+ const openAppBuilder = await executeInspectorCommandWithClient(options, {
1791
+ type: "openAppBuilder",
1792
+ payload: { serverName: options.serverName },
1793
+ timeoutMs: options.timeoutMs
1794
+ });
1795
+ if (openAppBuilder.status === "error") {
1796
+ return { openAppBuilder };
1797
+ }
1798
+ const contextPayload = compactRecord(options.renderContext);
1799
+ const setAppContext = Object.keys(contextPayload).length > 0 ? await executeInspectorCommandWithClient(options, {
1800
+ type: "setAppContext",
1801
+ payload: contextPayload,
1802
+ timeoutMs: options.timeoutMs
1803
+ }) : void 0;
1804
+ if (setAppContext?.status === "error") {
1805
+ return { openAppBuilder, setAppContext };
1806
+ }
1807
+ const renderToolResult = await executeInspectorCommandWithClient(options, {
1808
+ type: "renderToolResult",
1809
+ payload: {
1810
+ surface: "app-builder",
1811
+ serverName: options.serverName,
1812
+ toolName: options.toolName,
1813
+ parameters: options.params,
1814
+ result: options.toolResult
1815
+ },
1816
+ timeoutMs: options.timeoutMs
1817
+ });
1818
+ if (renderToolResult.status === "error") {
1819
+ return {
1820
+ openAppBuilder,
1821
+ ...setAppContext ? { setAppContext } : {},
1822
+ renderToolResult
1823
+ };
1824
+ }
1825
+ const snapshotApp = await executeInspectorCommandWithClient(options, {
1826
+ type: "snapshotApp",
1827
+ payload: { surface: "app-builder" },
1828
+ timeoutMs: options.timeoutMs
1829
+ });
1830
+ return {
1831
+ openAppBuilder,
1832
+ ...setAppContext ? { setAppContext } : {},
1833
+ renderToolResult,
1834
+ snapshot: snapshotApp
1835
+ };
1836
+ }
1837
+ async function executeInspectorCommandWithClient(options, request) {
1838
+ const startedAt = Date.now();
1839
+ const deadline = startedAt + options.timeoutMs;
1840
+ do {
1841
+ const response = await options.client.executeCommand(request);
1842
+ const retryable = response.status === "error" && (response.error.code === "no_active_client" || response.error.code === "unsupported_in_mode" || response.error.code === "disconnected_server");
1843
+ if (!retryable || Date.now() >= deadline) {
1844
+ return response;
1845
+ }
1846
+ await delay(500);
1847
+ } while (true);
1848
+ }
1849
+ function findInspectorRenderError(renderResult) {
1850
+ const priority = [
1851
+ "renderToolResult",
1852
+ "setAppContext",
1853
+ "openAppBuilder",
1854
+ "snapshot",
1855
+ "snapshotApp"
1856
+ ];
1857
+ for (const key of priority) {
1858
+ const value = renderResult[key];
1859
+ if (value && typeof value === "object" && value.status === "error") {
1860
+ return value.error;
1861
+ }
1862
+ }
1863
+ return void 0;
1864
+ }
1865
+ function normalizeSdkExecutionError(execution) {
1866
+ if (!execution || typeof execution !== "object") {
1867
+ return void 0;
1868
+ }
1869
+ const record = execution;
1870
+ const result = record.result && typeof record.result === "object" ? record.result : record;
1871
+ if (result.isError !== true) {
1872
+ return void 0;
1873
+ }
1874
+ const message = extractSdkErrorMessage(result) ?? "Tool execution failed.";
1875
+ return {
1876
+ code: "tool_execution_failed",
1877
+ message,
1878
+ details: execution
1879
+ };
1880
+ }
1881
+ function extractSdkErrorMessage(result) {
1882
+ if (typeof result.error === "string") {
1883
+ return result.error;
1884
+ }
1885
+ if (typeof result.message === "string") {
1886
+ return result.message;
1887
+ }
1888
+ const content = result.content;
1889
+ if (!Array.isArray(content)) {
1890
+ return void 0;
1891
+ }
1892
+ const text = content.map(
1893
+ (entry) => entry && typeof entry === "object" && typeof entry.text === "string" ? entry.text : void 0
1894
+ ).filter((entry) => Boolean(entry?.trim())).join("\n");
1895
+ return text || void 0;
1896
+ }
1897
+ function buildAppsDebugResult(options) {
1898
+ const toolsData = normalizeToolsData(options.toolsData);
1899
+ const tool = toolsData.tools.find((entry) => entry.name === options.toolName);
1900
+ const toolMetadata = toolsData.toolsMetadata[options.toolName] ?? {};
1901
+ const ui = extractToolUiMetadata(toolMetadata);
1902
+ return {
1903
+ tools: {
1904
+ count: toolsData.tools.length,
1905
+ matched: Boolean(tool),
1906
+ ...tool ? { tool } : {}
1907
+ },
1908
+ toolsMetadata: toolsData.toolsMetadata,
1909
+ toolMetadata,
1910
+ ui,
1911
+ execution: options.execution
1912
+ };
1913
+ }
1914
+ function normalizeToolsData(value) {
1915
+ if (!value || typeof value !== "object") {
1916
+ return { tools: [], toolsMetadata: {} };
1917
+ }
1918
+ const record = value;
1919
+ const tools = Array.isArray(record.tools) ? record.tools.filter(
1920
+ (tool) => Boolean(
1921
+ tool && typeof tool === "object" && typeof tool.name === "string"
1922
+ )
1923
+ ) : [];
1924
+ const toolsMetadata = record.toolsMetadata && typeof record.toolsMetadata === "object" && !Array.isArray(record.toolsMetadata) ? record.toolsMetadata : {};
1925
+ return { tools, toolsMetadata };
1926
+ }
1927
+ function extractToolUiMetadata(meta) {
1928
+ const nested = meta.ui;
1929
+ const mcpAppsResourceUri = nested && typeof nested === "object" ? nested.resourceUri : void 0;
1930
+ const legacyResourceUri = meta["ui/resourceUri"];
1931
+ const openAiOutputTemplate = meta["openai/outputTemplate"];
1932
+ return {
1933
+ resourceUri: typeof mcpAppsResourceUri === "string" ? mcpAppsResourceUri : typeof legacyResourceUri === "string" ? legacyResourceUri : typeof openAiOutputTemplate === "string" ? openAiOutputTemplate : null,
1934
+ mcpAppsResourceUri: typeof mcpAppsResourceUri === "string" ? mcpAppsResourceUri : null,
1935
+ legacyResourceUri: typeof legacyResourceUri === "string" ? legacyResourceUri : null,
1936
+ openAiOutputTemplate: typeof openAiOutputTemplate === "string" ? openAiOutputTemplate : null
1937
+ };
1938
+ }
1939
+ function parseRenderProtocol(value) {
1940
+ if (value === void 0) return void 0;
1941
+ if (value === "mcp-apps" || value === "openai-sdk") return value;
1942
+ throw usageError(
1943
+ `Invalid protocol "${value}". Use "mcp-apps" or "openai-sdk".`
1944
+ );
1945
+ }
1946
+ function parseRenderDevice(value) {
1947
+ if (value === void 0) return void 0;
1948
+ if (value === "mobile" || value === "tablet" || value === "desktop" || value === "custom") {
1949
+ return value;
1950
+ }
1951
+ throw usageError(
1952
+ `Invalid device "${value}". Use "mobile", "tablet", "desktop", or "custom".`
1953
+ );
1954
+ }
1955
+ function compactRecord(record) {
1956
+ return Object.fromEntries(
1957
+ Object.entries(record).filter(([, value]) => value !== void 0)
1958
+ );
1959
+ }
1960
+ function trimOptional(value) {
1961
+ const trimmed = value?.trim();
1962
+ return trimmed ? trimmed : void 0;
1963
+ }
1964
+ function buildInspectorServerName(options) {
1965
+ if (typeof options.url === "string" && options.url.trim()) {
1966
+ try {
1967
+ const parsed = new URL(options.url);
1968
+ const host = parsed.port ? `${parsed.hostname}-${parsed.port}` : parsed.hostname;
1969
+ const raw = `${host}${parsed.pathname}`.replace(/\/+$/, "").replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-+|-+$/g, "") || parsed.hostname;
1970
+ return raw || "inspector-server";
1971
+ } catch {
1972
+ return "inspector-server";
1973
+ }
1974
+ }
1975
+ if (typeof options.command === "string" && options.command.trim()) {
1976
+ return path2.basename(options.command.trim()).replace(/\.[a-z0-9]+$/i, "").replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "inspector-server";
1977
+ }
1978
+ return "inspector-server";
1979
+ }
1980
+
1981
+ // src/commands/apps.ts
1982
+ var APPS_CHECK_IDS_BY_CATEGORY = {
1983
+ tools: [
1984
+ "ui-tools-present",
1985
+ "ui-tool-metadata-valid",
1986
+ "ui-tool-input-schema-valid"
1987
+ ],
1988
+ resources: [
1989
+ "ui-listed-resources-valid",
1990
+ "ui-resources-readable",
1991
+ "ui-resource-contents-valid",
1992
+ "ui-resource-meta-valid"
1993
+ ]
1994
+ };
1995
+ function getConformanceGlobals(command, reporter) {
1996
+ const globalOptions = command.optsWithGlobals();
1997
+ return {
1998
+ format: resolveConformanceOutputFormatForCli(
1999
+ globalOptions.format,
2000
+ process.stdout.isTTY,
2001
+ reporter
2002
+ ),
2003
+ timeout: globalOptions.timeout ?? 3e4,
2004
+ rpc: globalOptions.rpc ?? false,
2005
+ quiet: globalOptions.quiet ?? false
2006
+ };
2007
+ }
2008
+ function writeConformanceOutput(output) {
2009
+ process.stdout.write(output.endsWith("\n") ? output : `${output}
2010
+ `);
2011
+ }
2012
+ function registerAppsCommands(program) {
2013
+ const apps = program.command("apps").description(
2014
+ "MCP Apps utilities, widget extraction, and conformance checks"
2015
+ );
2016
+ addSharedServerOptions(
2017
+ apps.command("conformance").description("Run MCP Apps server conformance checks").option(
2018
+ "--category <category>",
2019
+ "Check category to run. Repeat for multiple. Default: all.",
2020
+ (value, previous = []) => [...previous, value],
2021
+ []
2022
+ ).option(
2023
+ "--check-id <id>",
2024
+ "Specific check ID to run. Repeat for multiple. Default: all.",
2025
+ (value, previous = []) => [...previous, value],
2026
+ []
2027
+ ).option(
2028
+ "--reporter <reporter>",
2029
+ "Structured reporter output: json-summary or junit-xml"
2030
+ )
2031
+ ).action(async (options, command) => {
2032
+ const reporter = parseReporterFormat(options.reporter);
2033
+ const globalOptions = getConformanceGlobals(command, reporter);
2034
+ const target = describeTarget(options);
2035
+ const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2036
+ const config = {
2037
+ ...buildAppsConformanceConfig({
2038
+ ...options,
2039
+ timeout: globalOptions.timeout
2040
+ }),
2041
+ ...collector ? { rpcLogger: collector.rpcLogger } : {}
2042
+ };
2043
+ const result = await new MCPAppsConformanceTest(config).run();
2044
+ const outputResult = reporter ? result : withRpcLogsIfRequested(
2045
+ result,
2046
+ collector,
2047
+ globalOptions
2048
+ );
2049
+ writeConformanceOutput(
2050
+ renderConformanceForCli(outputResult, reporter, globalOptions.format)
2051
+ );
2052
+ if (!result.passed) {
2053
+ setProcessExitCode(1);
2054
+ }
2055
+ });
2056
+ apps.command("conformance-suite").description("Run MCP Apps conformance runs from a JSON config file").requiredOption("--config <path>", "Path to JSON config file").option(
2057
+ "--reporter <reporter>",
2058
+ "Structured reporter output: json-summary or junit-xml"
2059
+ ).action(async (options, command) => {
2060
+ const reporter = parseReporterFormat(options.reporter);
2061
+ const globalOptions = getConformanceGlobals(command, reporter);
2062
+ const config = loadAppsSuiteConfig(options.config);
2063
+ const target = config.target.command ?? config.target.url ?? "apps-suite";
2064
+ const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2065
+ const suite = new MCPAppsConformanceSuite({
2066
+ ...config,
2067
+ target: {
2068
+ ...config.target,
2069
+ ...collector ? { rpcLogger: collector.rpcLogger } : {}
2070
+ }
2071
+ });
2072
+ const result = await suite.run();
2073
+ const outputResult = reporter ? result : withRpcLogsIfRequested(
2074
+ result,
2075
+ collector,
2076
+ globalOptions
2077
+ );
2078
+ writeConformanceOutput(
2079
+ renderConformanceForCli(outputResult, reporter, globalOptions.format)
2080
+ );
2081
+ if (!result.passed) {
2082
+ setProcessExitCode(1);
2083
+ }
2084
+ });
2085
+ registerAppsDebugCommand(apps);
2086
+ addRetryOptions(
2087
+ addSharedServerOptions(
2088
+ apps.command("mcp-widget").description("Fetch hosted-style MCP App widget content").requiredOption("--resource-uri <uri>", "Widget resource URI").requiredOption(
2089
+ "--tool-id <id>",
2090
+ "Tool call id used for runtime injection"
2091
+ ).requiredOption(
2092
+ "--tool-name <name>",
2093
+ "Tool name used for runtime injection"
2094
+ ).option(
2095
+ "--tool-input <json>",
2096
+ "Tool input payload as JSON, @path, or - for stdin"
2097
+ ).option(
2098
+ "--tool-output <json>",
2099
+ "Tool output payload as JSON, @path, or - for stdin"
2100
+ ).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(
2101
+ "--view-params <json>",
2102
+ "Widget view params as JSON, @path, or - for stdin"
2103
+ )
2104
+ )
2105
+ ).action(async (options, command) => {
2106
+ const globalOptions = getGlobalOptions(command);
2107
+ const retryPolicy = parseRetryPolicy(options);
2108
+ const target = describeTarget(options);
2109
+ const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2110
+ const config = parseServerConfig({
2111
+ ...options,
2112
+ timeout: globalOptions.timeout
2113
+ });
2114
+ const result = await withEphemeralManager(
2115
+ config,
2116
+ (manager, serverId) => buildMcpWidgetContent(manager, serverId, {
2117
+ resourceUri: options.resourceUri,
709
2118
  toolId: options.toolId,
710
2119
  toolName: options.toolName,
711
2120
  toolInput: parseJsonRecord(options.toolInput, "Tool input") ?? {},
712
- toolOutput: parseJsonValue(options.toolOutput),
2121
+ toolOutput: parseJsonInputValue(options.toolOutput, "Tool output"),
2122
+ theme: parseTheme(options.theme),
2123
+ cspMode: parseCspMode(options.cspMode),
2124
+ template: options.template,
2125
+ viewMode: options.viewMode,
2126
+ viewParams: parseJsonRecord(options.viewParams, "View params")
2127
+ }),
2128
+ {
2129
+ timeout: globalOptions.timeout,
2130
+ rpcLogger: collector?.rpcLogger,
2131
+ retryPolicy
2132
+ }
2133
+ );
2134
+ writeResult(
2135
+ withRpcLogsIfRequested(result, collector, globalOptions),
2136
+ globalOptions.format
2137
+ );
2138
+ });
2139
+ addRetryOptions(
2140
+ addSharedServerOptions(
2141
+ apps.command("chatgpt-widget").description("Fetch hosted-style ChatGPT App widget content").requiredOption("--resource-uri <uri>", "Widget resource URI").requiredOption(
2142
+ "--tool-id <id>",
2143
+ "Tool call id used for runtime injection"
2144
+ ).requiredOption(
2145
+ "--tool-name <name>",
2146
+ "Tool name used for runtime injection"
2147
+ ).option(
2148
+ "--tool-input <json>",
2149
+ "Tool input payload as JSON, @path, or - for stdin"
2150
+ ).option(
2151
+ "--tool-output <json>",
2152
+ "Tool output payload as JSON, @path, or - for stdin"
2153
+ ).option(
2154
+ "--tool-response-metadata <json>",
2155
+ "Tool response metadata as JSON, @path, or - for stdin"
2156
+ ).option("--theme <theme>", "Widget theme: light or dark").option("--csp-mode <mode>", "CSP mode: permissive or widget-declared").option("--locale <locale>", "Locale override").option(
2157
+ "--device-type <type>",
2158
+ "Device type: mobile, tablet, or desktop"
2159
+ )
2160
+ )
2161
+ ).action(async (options, command) => {
2162
+ const globalOptions = getGlobalOptions(command);
2163
+ const retryPolicy = parseRetryPolicy(options);
2164
+ const target = describeTarget(options);
2165
+ const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2166
+ const config = parseServerConfig({
2167
+ ...options,
2168
+ timeout: globalOptions.timeout
2169
+ });
2170
+ const result = await withEphemeralManager(
2171
+ config,
2172
+ (manager, serverId) => buildChatGptWidgetContent(manager, serverId, {
2173
+ uri: options.resourceUri,
2174
+ toolId: options.toolId,
2175
+ toolName: options.toolName,
2176
+ toolInput: parseJsonRecord(options.toolInput, "Tool input") ?? {},
2177
+ toolOutput: parseJsonInputValue(options.toolOutput, "Tool output"),
713
2178
  toolResponseMetadata: parseJsonRecord(
714
2179
  options.toolResponseMetadata,
715
2180
  "Tool response metadata"
@@ -721,33 +2186,16 @@ function registerAppsCommands(program) {
721
2186
  }),
722
2187
  {
723
2188
  timeout: globalOptions.timeout,
724
- rpcLogger: collector?.rpcLogger
2189
+ rpcLogger: collector?.rpcLogger,
2190
+ retryPolicy
725
2191
  }
726
2192
  );
727
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
2193
+ writeResult(
2194
+ withRpcLogsIfRequested(result, collector, globalOptions),
2195
+ globalOptions.format
2196
+ );
728
2197
  });
729
2198
  }
730
- function parseJsonValue(value) {
731
- if (value === void 0) {
732
- return void 0;
733
- }
734
- try {
735
- return JSON.parse(value);
736
- } catch (error) {
737
- throw usageError("Value must be valid JSON.", {
738
- source: error instanceof Error ? error.message : String(error)
739
- });
740
- }
741
- }
742
- function parseTheme(value) {
743
- if (value === void 0) {
744
- return void 0;
745
- }
746
- if (value === "light" || value === "dark") {
747
- return value;
748
- }
749
- throw usageError(`Invalid theme "${value}". Use "light" or "dark".`);
750
- }
751
2199
  function parseCspMode(value) {
752
2200
  if (value === void 0) {
753
2201
  return void 0;
@@ -778,7 +2226,7 @@ function buildAppsConformanceConfig(options) {
778
2226
  const categories = options.category?.filter(Boolean);
779
2227
  const invalidCategories = collectInvalidEntries(
780
2228
  categories,
781
- sdk.MCP_APPS_CHECK_CATEGORIES
2229
+ MCP_APPS_CHECK_CATEGORIES
782
2230
  );
783
2231
  if (invalidCategories.length > 0) {
784
2232
  throw usageError(
@@ -786,7 +2234,7 @@ function buildAppsConformanceConfig(options) {
786
2234
  );
787
2235
  }
788
2236
  const checkIds = options.checkId?.filter(Boolean);
789
- const invalidCheckIds = collectInvalidEntries(checkIds, sdk.MCP_APPS_CHECK_IDS);
2237
+ const invalidCheckIds = collectInvalidEntries(checkIds, MCP_APPS_CHECK_IDS);
790
2238
  if (invalidCheckIds.length > 0) {
791
2239
  throw usageError(
792
2240
  `Unknown check id${invalidCheckIds.length === 1 ? "" : "s"}: ${invalidCheckIds.join(", ")}`
@@ -807,6 +2255,9 @@ function buildAppsConformanceConfig(options) {
807
2255
  function registerProtocolCommands(program) {
808
2256
  const protocol = program.command("protocol").description("MCP protocol inspection and conformance checks");
809
2257
  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(
2258
+ "--credentials-file <path>",
2259
+ "Load OAuth access token from a file created by oauth login --credentials-out"
2260
+ ).option(
810
2261
  "--header <header>",
811
2262
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
812
2263
  (value, previous = []) => [...previous, value],
@@ -826,19 +2277,46 @@ function registerProtocolCommands(program) {
826
2277
  "Specific check ID to run. Repeat for multiple. Default: all.",
827
2278
  (value, previous = []) => [...previous, value],
828
2279
  []
2280
+ ).option(
2281
+ "--reporter <reporter>",
2282
+ "Structured reporter output: json-summary or junit-xml"
829
2283
  ).action(async (options, command) => {
830
- const format = getFormat(command);
2284
+ const reporter = parseReporterFormat(options.reporter);
2285
+ const format = getFormat(command, reporter);
831
2286
  const config = buildConfig(options);
832
- const result = await new sdk.MCPConformanceTest(config).run();
833
- writeResult(result, format);
2287
+ const result = await new MCPConformanceTest(config).run();
2288
+ writeConformanceOutput2(renderConformanceForCli(result, reporter, format));
2289
+ if (!result.passed) {
2290
+ setProcessExitCode(1);
2291
+ }
2292
+ });
2293
+ protocol.command("conformance-suite").description(
2294
+ "Run a matrix of MCP protocol conformance checks from a JSON config file"
2295
+ ).requiredOption("--config <path>", "Path to JSON config file").option(
2296
+ "--reporter <reporter>",
2297
+ "Structured reporter output: json-summary or junit-xml"
2298
+ ).action(async (options, command) => {
2299
+ const reporter = parseReporterFormat(options.reporter);
2300
+ const format = getFormat(command, reporter);
2301
+ const config = loadProtocolSuiteConfig(options.config);
2302
+ const result = await new MCPConformanceSuite(config).run();
2303
+ writeConformanceOutput2(renderConformanceForCli(result, reporter, format));
834
2304
  if (!result.passed) {
835
2305
  setProcessExitCode(1);
836
2306
  }
837
2307
  });
838
2308
  }
839
- function getFormat(command) {
2309
+ function getFormat(command, reporter) {
840
2310
  const opts = command.optsWithGlobals();
841
- return resolveOutputFormat(opts.format, process.stdout.isTTY);
2311
+ return resolveConformanceOutputFormatForCli(
2312
+ opts.format,
2313
+ process.stdout.isTTY,
2314
+ reporter
2315
+ );
2316
+ }
2317
+ function writeConformanceOutput2(output) {
2318
+ process.stdout.write(output.endsWith("\n") ? output : `${output}
2319
+ `);
842
2320
  }
843
2321
  function collectInvalidEntries2(values, allowedValues) {
844
2322
  return (values ?? []).filter((value) => !allowedValues.includes(value));
@@ -854,203 +2332,41 @@ function buildConfig(options) {
854
2332
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
855
2333
  throw usageError(`Invalid URL scheme: ${serverUrl}`);
856
2334
  }
857
- const customHeaders = parseHeadersOption(options.header);
858
- const categories = options.category?.filter(Boolean);
859
- const invalidCategories = collectInvalidEntries2(
860
- categories,
861
- sdk.MCP_CHECK_CATEGORIES
862
- );
863
- if (invalidCategories.length > 0) {
864
- throw usageError(
865
- invalidCategories.length === 1 ? `Unknown category: ${invalidCategories[0]}` : `Unknown categories: ${invalidCategories.join(", ")}`
866
- );
867
- }
868
- const checkIds = options.checkId?.filter(Boolean);
869
- const invalidCheckIds = collectInvalidEntries2(checkIds, sdk.MCP_CHECK_IDS);
870
- if (invalidCheckIds.length > 0) {
871
- throw usageError(
872
- `Unknown check id${invalidCheckIds.length === 1 ? "" : "s"}: ${invalidCheckIds.join(", ")}`
873
- );
874
- }
875
- return {
876
- serverUrl,
877
- accessToken: options.accessToken,
878
- customHeaders,
879
- checkTimeout: options.checkTimeout ?? 15e3,
880
- ...categories && categories.length > 0 ? { categories } : {},
881
- ...checkIds && checkIds.length > 0 ? { checkIds } : {}
882
- };
883
- }
884
-
885
- // src/lib/oauth-enums.ts
886
- var VALID_PROTOCOL_VERSIONS = /* @__PURE__ */ new Set([
887
- "2025-03-26",
888
- "2025-06-18",
889
- "2025-11-25"
890
- ]);
891
- var VALID_REGISTRATION_STRATEGIES = /* @__PURE__ */ new Set([
892
- "cimd",
893
- "dcr",
894
- "preregistered"
895
- ]);
896
- var VALID_AUTH_MODES = /* @__PURE__ */ new Set([
897
- "headless",
898
- "interactive",
899
- "client_credentials"
900
- ]);
901
- function assertValidUrl(value, label) {
902
- if (typeof value !== "string" || !value.trim()) {
903
- throw usageError(`${label} is required and must be a non-empty string`);
904
- }
905
- try {
906
- new URL(value);
907
- } catch {
908
- throw usageError(`Invalid ${label}: ${value}`);
909
- }
910
- }
911
- function assertEnum(value, allowed, label) {
912
- if (typeof value !== "string" || !allowed.has(value)) {
913
- throw usageError(
914
- `Invalid ${label} "${String(value)}". Allowed: ${[...allowed].join(", ")}`
915
- );
916
- }
917
- }
918
- function validateFlow(flow, defaults, index) {
919
- const protocolVersion = flow.protocolVersion ?? defaults?.protocolVersion;
920
- if (!protocolVersion) {
921
- throw usageError(
922
- `flows[${index}]: protocolVersion is required (not set in flow or defaults)`
923
- );
924
- }
925
- assertEnum(protocolVersion, VALID_PROTOCOL_VERSIONS, `flows[${index}].protocolVersion`);
926
- const registrationStrategy = flow.registrationStrategy ?? defaults?.registrationStrategy;
927
- if (!registrationStrategy) {
928
- throw usageError(
929
- `flows[${index}]: registrationStrategy is required (not set in flow or defaults)`
930
- );
931
- }
932
- assertEnum(
933
- registrationStrategy,
934
- VALID_REGISTRATION_STRATEGIES,
935
- `flows[${index}].registrationStrategy`
936
- );
937
- const auth = flow.auth ?? defaults?.auth;
938
- if (auth?.mode) {
939
- assertEnum(auth.mode, VALID_AUTH_MODES, `flows[${index}].auth.mode`);
940
- }
941
- }
942
- function loadSuiteConfig(filePath) {
943
- let raw;
944
- try {
945
- raw = fs.readFileSync(filePath, "utf-8");
946
- } catch (error) {
947
- throw usageError(
948
- `Cannot read config file "${filePath}": ${error instanceof Error ? error.message : String(error)}`
949
- );
950
- }
951
- let config;
952
- try {
953
- config = JSON.parse(raw);
954
- } catch {
955
- throw usageError(`Config file "${filePath}" is not valid JSON`);
956
- }
957
- if (typeof config !== "object" || config === null || Array.isArray(config)) {
958
- throw usageError("Config file must be a JSON object");
959
- }
960
- assertValidUrl(config.serverUrl, "serverUrl");
961
- const flows = config.flows;
962
- if (!Array.isArray(flows) || flows.length === 0) {
963
- throw usageError('Config file must have a non-empty "flows" array');
964
- }
965
- const defaults = config.defaults;
966
- for (let i = 0; i < flows.length; i++) {
967
- const flow = flows[i];
968
- if (typeof flow !== "object" || flow === null || Array.isArray(flow)) {
969
- throw usageError(`flows[${i}] must be an object`);
970
- }
971
- validateFlow(flow, defaults, i);
972
- }
973
- return config;
974
- }
975
-
976
- // src/lib/junit-xml.ts
977
- function escapeXml(value) {
978
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
979
- }
980
- function stepToTestCase(step, classname) {
981
- const name = escapeXml(step.title || step.step);
982
- const time = (step.durationMs / 1e3).toFixed(3);
983
- const cls = escapeXml(classname);
984
- if (step.status === "skipped") {
985
- return ` <testcase name="${name}" classname="${cls}" time="${time}">
986
- <skipped/>
987
- </testcase>`;
988
- }
989
- if (step.status === "failed") {
990
- const message = escapeXml(step.error?.message ?? "Unknown failure");
991
- const details = step.httpAttempts.map((attempt) => {
992
- const req = `${attempt.request.method} ${attempt.request.url}`;
993
- const res = attempt.response ? `${attempt.response.status} ${attempt.response.statusText}` : "No response";
994
- return `${req} \u2192 ${res}`;
995
- }).join("\n");
996
- const body = details ? escapeXml(details) : "";
997
- return ` <testcase name="${name}" classname="${cls}" time="${time}">
998
- <failure message="${message}">${body}</failure>
999
- </testcase>`;
1000
- }
1001
- return ` <testcase name="${name}" classname="${cls}" time="${time}"/>`;
1002
- }
1003
- function flowToTestSuite(result) {
1004
- const name = escapeXml(result.label);
1005
- const tests = result.steps.length;
1006
- const failures = result.steps.filter((s) => s.status === "failed").length;
1007
- const skipped = result.steps.filter((s) => s.status === "skipped").length;
1008
- const time = (result.durationMs / 1e3).toFixed(3);
1009
- const classname = result.serverUrl;
1010
- const cases = result.steps.map((step) => stepToTestCase(step, classname)).join("\n");
1011
- return ` <testsuite name="${name}" tests="${tests}" failures="${failures}" skipped="${skipped}" time="${time}">
1012
- ${cases}
1013
- </testsuite>`;
1014
- }
1015
- function suiteResultToJUnitXml(result) {
1016
- const name = escapeXml(result.name);
1017
- const tests = result.results.reduce((sum, r) => sum + r.steps.length, 0);
1018
- const failures = result.results.reduce(
1019
- (sum, r) => sum + r.steps.filter((s) => s.status === "failed").length,
1020
- 0
2335
+ const customHeaders = parseHeadersOption(options.header);
2336
+ assertNoCredentialsFileAuthConflicts(options);
2337
+ const accessToken = options.credentialsFile ? resolveCredentialsFileAccessToken(options.credentialsFile, serverUrl) : options.accessToken;
2338
+ const categories = options.category?.filter(Boolean);
2339
+ const invalidCategories = collectInvalidEntries2(
2340
+ categories,
2341
+ MCP_CHECK_CATEGORIES
1021
2342
  );
1022
- const time = (result.durationMs / 1e3).toFixed(3);
1023
- const suites = result.results.map(flowToTestSuite).join("\n");
1024
- return `<?xml version="1.0" encoding="UTF-8"?>
1025
- <testsuites name="${name}" tests="${tests}" failures="${failures}" time="${time}">
1026
- ${suites}
1027
- </testsuites>
1028
- `;
1029
- }
1030
- function singleResultToJUnitXml(result, label) {
1031
- const suiteResult = {
1032
- name: "OAuth Conformance",
1033
- serverUrl: result.serverUrl,
1034
- passed: result.passed,
1035
- results: [
1036
- {
1037
- ...result,
1038
- label: `${result.protocolVersion}/${result.registrationStrategy}`
1039
- }
1040
- ],
1041
- summary: result.summary,
1042
- durationMs: result.durationMs
2343
+ if (invalidCategories.length > 0) {
2344
+ throw usageError(
2345
+ invalidCategories.length === 1 ? `Unknown category: ${invalidCategories[0]}` : `Unknown categories: ${invalidCategories.join(", ")}`
2346
+ );
2347
+ }
2348
+ const checkIds = options.checkId?.filter(Boolean);
2349
+ const invalidCheckIds = collectInvalidEntries2(checkIds, MCP_CHECK_IDS);
2350
+ if (invalidCheckIds.length > 0) {
2351
+ throw usageError(
2352
+ `Unknown check id${invalidCheckIds.length === 1 ? "" : "s"}: ${invalidCheckIds.join(", ")}`
2353
+ );
2354
+ }
2355
+ return {
2356
+ serverUrl,
2357
+ accessToken,
2358
+ customHeaders,
2359
+ checkTimeout: options.checkTimeout ?? 15e3,
2360
+ ...categories && categories.length > 0 ? { categories } : {},
2361
+ ...checkIds && checkIds.length > 0 ? { checkIds } : {}
1043
2362
  };
1044
- return suiteResultToJUnitXml(suiteResult);
1045
2363
  }
1046
-
1047
- // src/lib/oauth-output.ts
1048
2364
  function parseOAuthOutputFormat(value) {
1049
- if (value === "json" || value === "human" || value === "junit-xml") {
2365
+ if (value === "json" || value === "human") {
1050
2366
  return value;
1051
2367
  }
1052
2368
  throw usageError(
1053
- `Invalid output format "${value}". Use "json", "human", or "junit-xml".`
2369
+ `Invalid output format "${value}". Use "json" or "human".`
1054
2370
  );
1055
2371
  }
1056
2372
  function resolveOAuthOutputFormat(value, isTTY) {
@@ -1059,9 +2375,7 @@ function resolveOAuthOutputFormat(value, isTTY) {
1059
2375
  function renderOAuthConformanceResult(result, format) {
1060
2376
  switch (format) {
1061
2377
  case "human":
1062
- return sdk.formatOAuthConformanceHuman(result);
1063
- case "junit-xml":
1064
- return singleResultToJUnitXml(result);
2378
+ return formatOAuthConformanceHuman(result);
1065
2379
  case "json":
1066
2380
  return JSON.stringify(result);
1067
2381
  }
@@ -1069,9 +2383,7 @@ function renderOAuthConformanceResult(result, format) {
1069
2383
  function renderOAuthConformanceSuiteResult(result, format) {
1070
2384
  switch (format) {
1071
2385
  case "human":
1072
- return sdk.formatOAuthConformanceSuiteHuman(result);
1073
- case "junit-xml":
1074
- return suiteResultToJUnitXml(result);
2386
+ return formatOAuthConformanceSuiteHuman(result);
1075
2387
  case "json":
1076
2388
  return JSON.stringify(result);
1077
2389
  }
@@ -1094,7 +2406,7 @@ async function writeCommandDebugArtifact(options, dependencies = {}) {
1094
2406
  ]
1095
2407
  });
1096
2408
  const artifactPath = await writeDebugArtifact(options.outputPath, payload);
1097
- if (options.format === "human") {
2409
+ if (options.format === "human" && !options.quiet) {
1098
2410
  process.stderr.write(`Debug artifact: ${artifactPath}
1099
2411
  `);
1100
2412
  }
@@ -1129,11 +2441,11 @@ function buildCommandArtifactError(code, message, details) {
1129
2441
  };
1130
2442
  }
1131
2443
  async function writeDebugArtifact(outputPath, payload) {
1132
- const resolvedPath = path__default.default.resolve(process.cwd(), outputPath);
2444
+ const resolvedPath = path2.resolve(process.cwd(), outputPath);
1133
2445
  const redactedPayload = redactSensitiveValue(payload);
1134
2446
  try {
1135
- await promises.mkdir(path__default.default.dirname(resolvedPath), { recursive: true });
1136
- await promises.writeFile(
2447
+ await mkdir(path2.dirname(resolvedPath), { recursive: true });
2448
+ await writeFile(
1137
2449
  resolvedPath,
1138
2450
  `${JSON.stringify(redactedPayload, null, 2)}
1139
2451
  `,
@@ -1151,7 +2463,7 @@ async function writeDebugArtifact(outputPath, payload) {
1151
2463
  }
1152
2464
  async function collectDoctorSnapshot(options, dependencies = {}) {
1153
2465
  try {
1154
- const runDoctor = dependencies.runDoctor ?? sdk.runServerDoctor;
2466
+ const runDoctor = dependencies.runDoctor ?? runServerDoctor;
1155
2467
  return {
1156
2468
  snapshot: await runDoctor({
1157
2469
  ...options.input,
@@ -1277,27 +2589,55 @@ function getOAuthFormat(command) {
1277
2589
  const opts = command.optsWithGlobals();
1278
2590
  return resolveOAuthOutputFormat(opts.format, process.stdout.isTTY);
1279
2591
  }
1280
- function getStructuredOAuthFormat(command) {
1281
- const format = getOAuthFormat(command);
1282
- if (format === "junit-xml") {
1283
- throw usageError(
1284
- 'The oauth metadata/proxy commands only support --format "json" or "human".'
1285
- );
1286
- }
1287
- return format;
2592
+ function getOAuthConformanceFormat(command, reporter) {
2593
+ const opts = command.optsWithGlobals();
2594
+ return resolveConformanceOutputFormatForCli(
2595
+ opts.format,
2596
+ process.stdout.isTTY,
2597
+ reporter
2598
+ );
1288
2599
  }
1289
2600
  function writeOAuthOutput(output) {
1290
2601
  process.stdout.write(output.endsWith("\n") ? output : `${output}
1291
2602
  `);
1292
2603
  }
2604
+ function buildOAuthLoginDebugOutcome(options) {
2605
+ if (options.commandError !== void 0) {
2606
+ return {
2607
+ status: "error",
2608
+ error: options.commandError
2609
+ };
2610
+ }
2611
+ if (options.credentialsFileError !== void 0) {
2612
+ return {
2613
+ status: "error",
2614
+ result: options.result,
2615
+ error: options.credentialsFileError
2616
+ };
2617
+ }
2618
+ if (options.result?.completed) {
2619
+ return {
2620
+ status: "success",
2621
+ result: options.result
2622
+ };
2623
+ }
2624
+ return {
2625
+ status: "error",
2626
+ result: options.result,
2627
+ error: buildCommandArtifactError(
2628
+ "OAUTH_LOGIN_INCOMPLETE",
2629
+ options.result?.error?.message ?? "OAuth login did not complete."
2630
+ )
2631
+ };
2632
+ }
1293
2633
  function registerOAuthCommands(program) {
1294
2634
  const oauth = program.command("oauth").description("Run MCP OAuth login, proxy, and conformance flows");
1295
- oauth.command("login").description("Run an OAuth login flow against an HTTP MCP server").requiredOption("--url <url>", "MCP server URL").requiredOption(
2635
+ oauth.command("login").description("Run an OAuth login flow against an HTTP MCP server").requiredOption("--url <url>", "MCP server URL").option(
1296
2636
  "--protocol-version <version>",
1297
- "OAuth protocol version: 2025-03-26, 2025-06-18, or 2025-11-25"
1298
- ).requiredOption(
2637
+ "OAuth protocol override: 2025-03-26, 2025-06-18, or 2025-11-25"
2638
+ ).option(
1299
2639
  "--registration <strategy>",
1300
- "Registration strategy: dcr, preregistered, or cimd"
2640
+ "Registration override: dcr, preregistered, or cimd"
1301
2641
  ).option(
1302
2642
  "--auth-mode <mode>",
1303
2643
  "Authorization mode: headless, interactive, or client_credentials",
@@ -1324,16 +2664,20 @@ function registerOAuthCommands(program) {
1324
2664
  ).option(
1325
2665
  "--debug-out <path>",
1326
2666
  "Write a structured debug artifact to a file"
2667
+ ).option(
2668
+ "--credentials-out <path>",
2669
+ "Write OAuth credentials to <path> (mode 0600); stdout output has secret fields redacted to [SAVED_TO_FILE]"
1327
2670
  ).action(async (options, command) => {
1328
- const format = getStructuredOAuthFormat(command);
1329
- const config = buildOAuthConformanceConfig(
2671
+ const globalOptions = getGlobalOptions(command);
2672
+ const format = getOAuthFormat(command);
2673
+ const config = buildOAuthLoginConfig(
1330
2674
  options,
1331
2675
  {
1332
2676
  defaultAuthMode: "interactive"
1333
2677
  }
1334
2678
  );
1335
2679
  const snapshotCollector = options.debugOut ? createCliRpcLogCollector({ __cli__: config.serverUrl }) : void 0;
1336
- const isTTY = process.stderr.isTTY;
2680
+ const isTTY = process.stderr.isTTY && !globalOptions.quiet;
1337
2681
  if (isTTY) {
1338
2682
  config.onProgress = (message) => {
1339
2683
  process.stderr.write(`\r\x1B[K${message}`);
@@ -1342,7 +2686,7 @@ function registerOAuthCommands(program) {
1342
2686
  let result;
1343
2687
  let commandError;
1344
2688
  try {
1345
- result = await sdk.runOAuthLogin(config);
2689
+ result = await runOAuthLogin(config);
1346
2690
  } catch (error) {
1347
2691
  commandError = error;
1348
2692
  } finally {
@@ -1355,28 +2699,32 @@ function registerOAuthCommands(program) {
1355
2699
  config.serverUrl,
1356
2700
  snapshotConfig
1357
2701
  );
2702
+ let credentialsFilePath;
2703
+ let credentialsFileError;
2704
+ if (commandError === void 0 && result && options.credentialsOut && hasCredentialsToSave(result)) {
2705
+ try {
2706
+ credentialsFilePath = await writeCredentialsFile(
2707
+ options.credentialsOut,
2708
+ result
2709
+ );
2710
+ } catch (error) {
2711
+ credentialsFileError = error;
2712
+ }
2713
+ }
1358
2714
  await writeCommandDebugArtifact({
1359
2715
  outputPath: options.debugOut,
1360
2716
  format,
2717
+ quiet: globalOptions.quiet,
1361
2718
  commandName: "oauth login",
1362
2719
  commandInput: summarizeOAuthLoginCommandInput(
1363
2720
  options
1364
2721
  ),
1365
2722
  target,
1366
- outcome: commandError ? {
1367
- status: "error",
1368
- error: commandError
1369
- } : result?.completed ? {
1370
- status: "success",
1371
- result
1372
- } : {
1373
- status: "error",
2723
+ outcome: buildOAuthLoginDebugOutcome({
2724
+ commandError,
1374
2725
  result,
1375
- error: buildCommandArtifactError(
1376
- "OAUTH_LOGIN_INCOMPLETE",
1377
- result?.error?.message ?? "OAuth login did not complete."
1378
- )
1379
- },
2726
+ credentialsFileError
2727
+ }),
1380
2728
  snapshot: options.debugOut ? {
1381
2729
  input: {
1382
2730
  config: snapshotConfig,
@@ -1392,7 +2740,17 @@ function registerOAuthCommands(program) {
1392
2740
  if (!result) {
1393
2741
  throw cliError("INTERNAL_ERROR", "OAuth login did not return a result.");
1394
2742
  }
1395
- writeResult(result, format);
2743
+ if (options.credentialsOut) {
2744
+ writeResult(
2745
+ redactCredentialsFromResult(result, credentialsFilePath),
2746
+ format
2747
+ );
2748
+ if (credentialsFileError) {
2749
+ throw credentialsFileError;
2750
+ }
2751
+ } else {
2752
+ writeResult(result, format);
2753
+ }
1396
2754
  if (!result.completed) {
1397
2755
  setProcessExitCode(1);
1398
2756
  }
@@ -1432,11 +2790,17 @@ function registerOAuthCommands(program) {
1432
2790
  ).option(
1433
2791
  "--print-url",
1434
2792
  "In interactive mode, print the consent URL to stderr instead of launching a browser"
2793
+ ).option(
2794
+ "--reporter <reporter>",
2795
+ "Structured reporter output: json-summary or junit-xml"
1435
2796
  ).action(async (options, command) => {
1436
- const format = getOAuthFormat(command);
2797
+ const reporter = parseReporterFormat(options.reporter);
2798
+ const format = getOAuthConformanceFormat(command, reporter);
1437
2799
  const config = buildOAuthConformanceConfig(options);
1438
- const result = await new sdk.OAuthConformanceTest(config).run();
1439
- writeOAuthOutput(renderOAuthConformanceResult(result, format));
2800
+ const result = await new OAuthConformanceTest(config).run();
2801
+ writeOAuthOutput(
2802
+ reporter ? renderConformanceReporterResult(result, reporter) : renderOAuthConformanceResult(result, format)
2803
+ );
1440
2804
  if (!result.passed) {
1441
2805
  setProcessExitCode(1);
1442
2806
  }
@@ -1449,9 +2813,13 @@ function registerOAuthCommands(program) {
1449
2813
  ).option(
1450
2814
  "--verify-call-tool <name>",
1451
2815
  "Also call the named tool after listing"
2816
+ ).option(
2817
+ "--reporter <reporter>",
2818
+ "Structured reporter output: json-summary or junit-xml"
1452
2819
  ).action(async (options, command) => {
1453
- const format = getOAuthFormat(command);
1454
- const config = loadSuiteConfig(options.config);
2820
+ const reporter = parseReporterFormat(options.reporter);
2821
+ const format = getOAuthConformanceFormat(command, reporter);
2822
+ const config = loadOAuthSuiteConfig(options.config);
1455
2823
  if (options.verifyTools || options.verifyCallTool) {
1456
2824
  const cliVerification = {
1457
2825
  listTools: true,
@@ -1465,43 +2833,56 @@ function registerOAuthCommands(program) {
1465
2833
  verification: { ...config.defaults?.verification, ...cliVerification }
1466
2834
  };
1467
2835
  }
1468
- const suite = new sdk.OAuthConformanceSuite(config);
2836
+ const suite = new OAuthConformanceSuite(config);
1469
2837
  const result = await suite.run();
1470
- writeOAuthOutput(renderOAuthConformanceSuiteResult(result, format));
2838
+ writeOAuthOutput(
2839
+ reporter ? renderConformanceReporterResult(result, reporter) : renderOAuthConformanceSuiteResult(result, format)
2840
+ );
1471
2841
  if (!result.passed) {
1472
2842
  setProcessExitCode(1);
1473
2843
  }
1474
2844
  });
1475
2845
  oauth.command("metadata").description("Fetch OAuth metadata from a URL").requiredOption("--url <url>", "OAuth metadata URL").action(async (options, command) => {
2846
+ const format = getOAuthFormat(command);
1476
2847
  const result = await runOAuthMetadata(options.url);
1477
- writeResult(result, getStructuredOAuthFormat(command));
2848
+ writeResult(result, format);
1478
2849
  });
1479
2850
  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(
1480
2851
  "--header <header>",
1481
2852
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
1482
2853
  (value, previous = []) => [...previous, value],
1483
2854
  []
1484
- ).option("--body <value>", "Request body as JSON or raw string").action(async (options, command) => {
2855
+ ).option(
2856
+ "--body <value>",
2857
+ "Request body as JSON, raw string, @path, or - for stdin"
2858
+ ).action(async (options, command) => {
2859
+ const format = getOAuthFormat(command);
1485
2860
  const result = await runOAuthProxy(options);
1486
- writeResult(result, getStructuredOAuthFormat(command));
2861
+ writeResult(result, format);
1487
2862
  });
1488
2863
  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(
1489
2864
  "--header <header>",
1490
2865
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
1491
2866
  (value, previous = []) => [...previous, value],
1492
2867
  []
1493
- ).option("--body <value>", "Request body as JSON or raw string").action(async (options, command) => {
2868
+ ).option(
2869
+ "--body <value>",
2870
+ "Request body as JSON, raw string, @path, or - for stdin"
2871
+ ).action(async (options, command) => {
2872
+ const format = getOAuthFormat(command);
1494
2873
  const result = await runOAuthDebugProxy(
1495
2874
  options
1496
2875
  );
1497
- writeResult(result, getStructuredOAuthFormat(command));
2876
+ writeResult(result, format);
1498
2877
  });
1499
2878
  }
1500
2879
  function buildOAuthConformanceConfig(options, defaults) {
1501
2880
  const serverUrl = options.url.trim();
1502
2881
  assertValidUrl2(serverUrl, "server URL");
1503
- const protocolVersion = parseProtocolVersion(options.protocolVersion);
1504
- const registrationStrategy = parseRegistrationStrategy(options.registration);
2882
+ const protocolVersion = parseRequiredProtocolVersion(options.protocolVersion);
2883
+ const registrationStrategy = parseRequiredRegistrationStrategy(
2884
+ options.registration
2885
+ );
1505
2886
  const authMode = parseAuthMode(
1506
2887
  options.authMode ?? defaults?.defaultAuthMode ?? "interactive"
1507
2888
  );
@@ -1576,9 +2957,97 @@ function buildOAuthConformanceConfig(options, defaults) {
1576
2957
  oauthConformanceChecks: options.conformanceChecks ?? false
1577
2958
  };
1578
2959
  }
2960
+ function buildOAuthLoginConfig(options, defaults) {
2961
+ const serverUrl = options.url.trim();
2962
+ assertValidUrl2(serverUrl, "server URL");
2963
+ const protocolVersion = options.protocolVersion ? parseProtocolVersion(options.protocolVersion) : void 0;
2964
+ const registrationStrategy = options.registration ? parseRegistrationStrategy(options.registration) : void 0;
2965
+ const authMode = parseAuthMode(
2966
+ options.authMode ?? defaults?.defaultAuthMode ?? "interactive"
2967
+ );
2968
+ if (options.printUrl && authMode !== "interactive") {
2969
+ throw usageError(
2970
+ "--print-url only applies to --auth-mode interactive. Headless and client_credentials modes do not open a browser."
2971
+ );
2972
+ }
2973
+ if (protocolVersion !== void 0 && registrationStrategy === "cimd" && protocolVersion !== "2025-11-25") {
2974
+ throw usageError(
2975
+ `CIMD registration is not supported for protocol version ${protocolVersion}.`
2976
+ );
2977
+ }
2978
+ if (authMode === "client_credentials" && registrationStrategy === "cimd") {
2979
+ throw usageError(
2980
+ "--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."
2981
+ );
2982
+ }
2983
+ const clientId = options.clientId?.trim();
2984
+ const clientSecret = options.clientSecret;
2985
+ const clientMetadataUrl = options.clientMetadataUrl?.trim();
2986
+ const redirectUrl = options.redirectUrl?.trim();
2987
+ if (registrationStrategy === "preregistered" && !clientId) {
2988
+ throw usageError(
2989
+ "--client-id is required when --registration preregistered is used."
2990
+ );
2991
+ }
2992
+ if (registrationStrategy === "preregistered" && authMode === "client_credentials" && !clientSecret) {
2993
+ throw usageError(
2994
+ "--client-secret is required for preregistered client_credentials runs."
2995
+ );
2996
+ }
2997
+ if (clientMetadataUrl) {
2998
+ assertValidUrl2(clientMetadataUrl, "client metadata URL");
2999
+ }
3000
+ if (redirectUrl) {
3001
+ assertValidUrl2(redirectUrl, "redirect URL");
3002
+ }
3003
+ const customHeaders = parseHeadersOption(options.header);
3004
+ const client = {};
3005
+ if (clientId) {
3006
+ client.preregistered = {
3007
+ clientId,
3008
+ ...clientSecret ? { clientSecret } : {}
3009
+ };
3010
+ }
3011
+ if (clientMetadataUrl) {
3012
+ client.clientIdMetadataUrl = clientMetadataUrl;
3013
+ }
3014
+ const verification = options.verifyTools || options.verifyCallTool ? {
3015
+ listTools: options.verifyTools ?? !!options.verifyCallTool,
3016
+ ...options.verifyCallTool ? { callTool: { name: options.verifyCallTool } } : {}
3017
+ } : void 0;
3018
+ const auth = buildAuthConfig(
3019
+ authMode,
3020
+ registrationStrategy ?? "dcr",
3021
+ clientId,
3022
+ clientSecret
3023
+ );
3024
+ if (options.printUrl && auth.mode === "interactive") {
3025
+ auth.openUrl = async (url) => {
3026
+ process.stderr.write(`OAUTH_CONSENT_URL: ${url}
3027
+ `);
3028
+ };
3029
+ }
3030
+ return {
3031
+ serverUrl,
3032
+ ...protocolVersion ? { protocolVersion } : {},
3033
+ ...registrationStrategy ? { registrationStrategy } : {},
3034
+ protocolMode: protocolVersion ?? "auto",
3035
+ registrationMode: registrationStrategy ?? "auto",
3036
+ auth,
3037
+ client,
3038
+ scopes: options.scopes?.trim() || void 0,
3039
+ customHeaders,
3040
+ redirectUrl,
3041
+ stepTimeout: options.stepTimeout ?? 3e4,
3042
+ verification,
3043
+ oauthConformanceChecks: false
3044
+ };
3045
+ }
1579
3046
  function summarizeOAuthLoginCommandInput(options) {
1580
3047
  return {
1581
3048
  serverUrl: options.url.trim(),
3049
+ protocolMode: options.protocolVersion ?? "auto",
3050
+ registrationMode: options.registration ?? "auto",
1582
3051
  protocolVersion: options.protocolVersion,
1583
3052
  registration: options.registration,
1584
3053
  authMode: options.authMode ?? "interactive",
@@ -1651,6 +3120,14 @@ function parseProtocolVersion(value) {
1651
3120
  `Invalid protocol version "${value}". Use ${[...VALID_PROTOCOL_VERSIONS].join(", ")}.`
1652
3121
  );
1653
3122
  }
3123
+ function parseRequiredProtocolVersion(value) {
3124
+ if (!value) {
3125
+ throw usageError(
3126
+ "--protocol-version is required for oauth conformance flows."
3127
+ );
3128
+ }
3129
+ return parseProtocolVersion(value);
3130
+ }
1654
3131
  function parseRegistrationStrategy(value) {
1655
3132
  if (VALID_REGISTRATION_STRATEGIES.has(value)) {
1656
3133
  return value;
@@ -1659,6 +3136,14 @@ function parseRegistrationStrategy(value) {
1659
3136
  `Invalid registration strategy "${value}". Use ${[...VALID_REGISTRATION_STRATEGIES].join(", ")}.`
1660
3137
  );
1661
3138
  }
3139
+ function parseRequiredRegistrationStrategy(value) {
3140
+ if (!value) {
3141
+ throw usageError(
3142
+ "--registration is required for oauth conformance flows."
3143
+ );
3144
+ }
3145
+ return parseRegistrationStrategy(value);
3146
+ }
1662
3147
  function parseAuthMode(value) {
1663
3148
  if (VALID_AUTH_MODES.has(value)) {
1664
3149
  return value;
@@ -1669,7 +3154,7 @@ function parseAuthMode(value) {
1669
3154
  }
1670
3155
  async function runOAuthMetadata(url) {
1671
3156
  try {
1672
- const result = await sdk.fetchOAuthMetadata(url, true);
3157
+ const result = await fetchOAuthMetadata(url, true);
1673
3158
  if ("status" in result && result.status !== void 0) {
1674
3159
  throw cliError(
1675
3160
  statusToErrorCode(result.status),
@@ -1683,7 +3168,7 @@ async function runOAuthMetadata(url) {
1683
3168
  }
1684
3169
  async function runOAuthProxy(options) {
1685
3170
  try {
1686
- return await sdk.executeOAuthProxy({
3171
+ return await executeOAuthProxy({
1687
3172
  url: options.url,
1688
3173
  method: options.method,
1689
3174
  headers: parseHeadersOption(options.header),
@@ -1696,7 +3181,7 @@ async function runOAuthProxy(options) {
1696
3181
  }
1697
3182
  async function runOAuthDebugProxy(options) {
1698
3183
  try {
1699
- return await sdk.executeDebugOAuthProxy({
3184
+ return await executeDebugOAuthProxy({
1700
3185
  url: options.url,
1701
3186
  method: options.method,
1702
3187
  headers: parseHeadersOption(options.header),
@@ -1711,14 +3196,15 @@ function parseProxyBody(value) {
1711
3196
  if (value === void 0) {
1712
3197
  return void 0;
1713
3198
  }
3199
+ const source = readInputSource(value, "Request body");
1714
3200
  try {
1715
- return JSON.parse(value);
3201
+ return JSON.parse(source);
1716
3202
  } catch {
1717
- return value;
3203
+ return source;
1718
3204
  }
1719
3205
  }
1720
3206
  function mapOAuthProxyError(error) {
1721
- if (error instanceof sdk.OAuthProxyError) {
3207
+ if (error instanceof OAuthProxyError) {
1722
3208
  return cliError(statusToErrorCode(error.status), error.message);
1723
3209
  }
1724
3210
  return error;
@@ -1735,10 +3221,13 @@ function statusToErrorCode(status) {
1735
3221
  }
1736
3222
  function registerPromptCommands(program) {
1737
3223
  const prompts = program.command("prompts").description("List and fetch MCP prompts");
1738
- addSharedServerOptions(
1739
- prompts.command("list").description("List prompts exposed by an MCP server").option("--cursor <cursor>", "Pagination cursor")
3224
+ addRetryOptions(
3225
+ addSharedServerOptions(
3226
+ prompts.command("list").description("List prompts exposed by an MCP server").option("--cursor <cursor>", "Pagination cursor")
3227
+ )
1740
3228
  ).action(async (options, command) => {
1741
3229
  const globalOptions = getGlobalOptions(command);
3230
+ const retryPolicy = parseRetryPolicy(options);
1742
3231
  const target = describeTarget(options);
1743
3232
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
1744
3233
  const config = parseServerConfig({
@@ -1747,18 +3236,28 @@ function registerPromptCommands(program) {
1747
3236
  });
1748
3237
  const result = await withEphemeralManager(
1749
3238
  config,
1750
- (manager, serverId) => sdk.listPrompts(manager, { serverId, cursor: options.cursor }),
3239
+ (manager, serverId) => listPrompts(manager, { serverId, cursor: options.cursor }),
1751
3240
  {
1752
3241
  timeout: globalOptions.timeout,
1753
- rpcLogger: collector?.rpcLogger
3242
+ rpcLogger: collector?.rpcLogger,
3243
+ retryPolicy
1754
3244
  }
1755
3245
  );
1756
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
3246
+ writeResult(
3247
+ withRpcLogsIfRequested(result, collector, globalOptions),
3248
+ globalOptions.format
3249
+ );
1757
3250
  });
1758
- addSharedServerOptions(
1759
- 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")
3251
+ addRetryOptions(
3252
+ addSharedServerOptions(
3253
+ 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(
3254
+ "--prompt-args <json>",
3255
+ "Prompt arguments as JSON, @path, or - for stdin"
3256
+ )
3257
+ )
1760
3258
  ).action(async (options, command) => {
1761
3259
  const globalOptions = getGlobalOptions(command);
3260
+ const retryPolicy = parseRetryPolicy(options);
1762
3261
  const target = describeTarget(options);
1763
3262
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
1764
3263
  const promptName = resolveAliasedStringOption(
@@ -1777,25 +3276,32 @@ function registerPromptCommands(program) {
1777
3276
  const promptArguments = parsePromptArguments(options.promptArgs);
1778
3277
  const result = await withEphemeralManager(
1779
3278
  config,
1780
- (manager, serverId) => sdk.getPrompt(manager, {
3279
+ (manager, serverId) => getPrompt(manager, {
1781
3280
  serverId,
1782
3281
  name: promptName,
1783
3282
  arguments: promptArguments
1784
3283
  }),
1785
3284
  {
1786
3285
  timeout: globalOptions.timeout,
1787
- rpcLogger: collector?.rpcLogger
3286
+ rpcLogger: collector?.rpcLogger,
3287
+ retryPolicy
1788
3288
  }
1789
3289
  );
1790
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
3290
+ writeResult(
3291
+ withRpcLogsIfRequested(result, collector, globalOptions),
3292
+ globalOptions.format
3293
+ );
1791
3294
  });
1792
3295
  }
1793
3296
  function registerResourcesCommands(program) {
1794
3297
  const resources = program.command("resources").description("List and read MCP resources");
1795
- addSharedServerOptions(
1796
- resources.command("list").description("List resources exposed by an MCP server").option("--cursor <cursor>", "Pagination cursor")
3298
+ addRetryOptions(
3299
+ addSharedServerOptions(
3300
+ resources.command("list").description("List resources exposed by an MCP server").option("--cursor <cursor>", "Pagination cursor")
3301
+ )
1797
3302
  ).action(async (options, command) => {
1798
3303
  const globalOptions = getGlobalOptions(command);
3304
+ const retryPolicy = parseRetryPolicy(options);
1799
3305
  const target = describeTarget(options);
1800
3306
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
1801
3307
  const config = parseServerConfig({
@@ -1804,18 +3310,25 @@ function registerResourcesCommands(program) {
1804
3310
  });
1805
3311
  const result = await withEphemeralManager(
1806
3312
  config,
1807
- (manager, serverId) => sdk.listResources(manager, { serverId, cursor: options.cursor }),
3313
+ (manager, serverId) => listResources(manager, { serverId, cursor: options.cursor }),
1808
3314
  {
1809
3315
  timeout: globalOptions.timeout,
1810
- rpcLogger: collector?.rpcLogger
3316
+ rpcLogger: collector?.rpcLogger,
3317
+ retryPolicy
1811
3318
  }
1812
3319
  );
1813
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
3320
+ writeResult(
3321
+ withRpcLogsIfRequested(result, collector, globalOptions),
3322
+ globalOptions.format
3323
+ );
1814
3324
  });
1815
- addSharedServerOptions(
1816
- resources.command("read").description("Read a resource from an MCP server").option("--resource-uri <uri>", "Resource URI").option("--uri <uri>", "Alias for --resource-uri")
3325
+ addRetryOptions(
3326
+ addSharedServerOptions(
3327
+ resources.command("read").description("Read a resource from an MCP server").option("--resource-uri <uri>", "Resource URI").option("--uri <uri>", "Alias for --resource-uri")
3328
+ )
1817
3329
  ).action(async (options, command) => {
1818
3330
  const globalOptions = getGlobalOptions(command);
3331
+ const retryPolicy = parseRetryPolicy(options);
1819
3332
  const target = describeTarget(options);
1820
3333
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
1821
3334
  const resourceUri = resolveAliasedStringOption(
@@ -1833,18 +3346,25 @@ function registerResourcesCommands(program) {
1833
3346
  });
1834
3347
  const result = await withEphemeralManager(
1835
3348
  config,
1836
- (manager, serverId) => sdk.readResource(manager, { serverId, uri: resourceUri }),
3349
+ (manager, serverId) => readResource(manager, { serverId, uri: resourceUri }),
1837
3350
  {
1838
3351
  timeout: globalOptions.timeout,
1839
- rpcLogger: collector?.rpcLogger
3352
+ rpcLogger: collector?.rpcLogger,
3353
+ retryPolicy
1840
3354
  }
1841
3355
  );
1842
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
3356
+ writeResult(
3357
+ withRpcLogsIfRequested(result, collector, globalOptions),
3358
+ globalOptions.format
3359
+ );
1843
3360
  });
1844
- addSharedServerOptions(
1845
- resources.command("templates").description("List resource templates exposed by an MCP server").option("--cursor <cursor>", "Pagination cursor")
3361
+ addRetryOptions(
3362
+ addSharedServerOptions(
3363
+ resources.command("templates").description("List resource templates exposed by an MCP server").option("--cursor <cursor>", "Pagination cursor")
3364
+ )
1846
3365
  ).action(async (options, command) => {
1847
3366
  const globalOptions = getGlobalOptions(command);
3367
+ const retryPolicy = parseRetryPolicy(options);
1848
3368
  const target = describeTarget(options);
1849
3369
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
1850
3370
  const config = parseServerConfig({
@@ -1859,105 +3379,55 @@ function registerResourcesCommands(program) {
1859
3379
  ),
1860
3380
  {
1861
3381
  timeout: globalOptions.timeout,
1862
- rpcLogger: collector?.rpcLogger
3382
+ rpcLogger: collector?.rpcLogger,
3383
+ retryPolicy
1863
3384
  }
1864
3385
  );
1865
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
3386
+ writeResult(
3387
+ withRpcLogsIfRequested(result, collector, globalOptions),
3388
+ globalOptions.format
3389
+ );
1866
3390
  });
1867
3391
  }
1868
-
1869
- // src/lib/server-ops.ts
1870
- async function listToolsWithMetadata(manager, params) {
1871
- const result = await manager.listTools(
1872
- params.serverId,
1873
- params.cursor ? { cursor: params.cursor } : void 0
1874
- );
1875
- const tools = result.tools ?? [];
1876
- const toolsMetadata = manager.getAllToolsMetadata(params.serverId);
1877
- const tokenCount = params.modelId ? estimateTokensFromChars(JSON.stringify(tools)) : void 0;
1878
- return {
1879
- tools,
1880
- nextCursor: result.nextCursor,
1881
- toolsMetadata,
1882
- ...tokenCount === void 0 ? {} : { tokenCount }
1883
- };
1884
- }
1885
- async function exportServerSnapshot(manager, serverId, target) {
1886
- const [toolsResult, resourcesResult, promptsResult, resourceTemplatesResult] = await Promise.all([
1887
- manager.listTools(serverId),
1888
- manager.listResources(serverId),
1889
- manager.listPrompts(serverId),
1890
- manager.listResourceTemplates(serverId).catch(() => ({
1891
- resourceTemplates: []
1892
- }))
1893
- ]);
1894
- return {
1895
- target,
1896
- exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
1897
- initInfo: manager.getInitializationInfo(serverId) ?? null,
1898
- capabilities: manager.getServerCapabilities(serverId) ?? null,
1899
- tools: (toolsResult.tools ?? []).map((tool) => ({
1900
- name: tool.name,
1901
- description: tool.description,
1902
- inputSchema: tool.inputSchema,
1903
- outputSchema: tool.outputSchema
1904
- })),
1905
- toolsMetadata: manager.getAllToolsMetadata(serverId),
1906
- resources: (resourcesResult.resources ?? []).map((resource) => ({
1907
- uri: resource.uri,
1908
- name: resource.name,
1909
- description: resource.description,
1910
- mimeType: resource.mimeType
1911
- })),
1912
- resourceTemplates: (resourceTemplatesResult.resourceTemplates ?? []).map(
1913
- (template) => ({
1914
- uriTemplate: template.uriTemplate,
1915
- name: template.name,
1916
- description: template.description,
1917
- mimeType: template.mimeType
1918
- })
1919
- ),
1920
- prompts: (promptsResult.prompts ?? []).map((prompt) => ({
1921
- name: prompt.name,
1922
- description: prompt.description,
1923
- arguments: prompt.arguments
1924
- }))
1925
- };
1926
- }
1927
- function estimateTokensFromChars(text) {
1928
- return Math.ceil(text.length / 4);
1929
- }
1930
-
1931
- // src/commands/server.ts
1932
3392
  function registerServerCommands(program) {
1933
3393
  const server = program.command("server").description("Inspect MCP server connectivity and capabilities");
1934
- 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(
1935
- "--oauth-access-token <token>",
1936
- "OAuth bearer access token for HTTP servers"
1937
- ).option(
1938
- "--header <header>",
1939
- 'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
1940
- (value, previous = []) => [...previous, value],
1941
- []
1942
- ).option(
1943
- "--client-capabilities <json>",
1944
- "Client capabilities advertised in the initialize probe as a JSON object"
1945
- ).option(
1946
- "--protocol-version <version>",
1947
- "OAuth/MCP protocol version hint used for the initialize probe",
1948
- "2025-11-25"
1949
- ).option(
1950
- "--timeout <ms>",
1951
- "Request timeout in milliseconds",
1952
- (value) => parsePositiveInteger(value, "Timeout")
1953
- ).option(
1954
- "--debug-out <path>",
1955
- "Write a structured debug artifact to a file"
3394
+ addRetryOptions(
3395
+ server.command("probe").description(
3396
+ "Probe an HTTP MCP server without using the full client connect flow"
3397
+ ).requiredOption("--url <url>", "HTTP MCP server URL").option("--access-token <token>", "Bearer access token for HTTP servers").option(
3398
+ "--oauth-access-token <token>",
3399
+ "OAuth bearer access token for HTTP servers"
3400
+ ).option(
3401
+ "--credentials-file <path>",
3402
+ "Load OAuth access token from a file created by oauth login --credentials-out"
3403
+ ).option(
3404
+ "--header <header>",
3405
+ 'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
3406
+ (value, previous = []) => [...previous, value],
3407
+ []
3408
+ ).option(
3409
+ "--client-capabilities <json>",
3410
+ "Client capabilities as JSON, @path, or - for stdin"
3411
+ ).option(
3412
+ "--protocol-version <version>",
3413
+ "OAuth/MCP protocol version hint used for the initialize probe",
3414
+ "2025-11-25"
3415
+ ).option(
3416
+ "--timeout <ms>",
3417
+ "Request timeout in milliseconds",
3418
+ (value) => parsePositiveInteger(value, "Timeout")
3419
+ ).option(
3420
+ "--debug-out <path>",
3421
+ "Write a structured debug artifact to a file"
3422
+ )
1956
3423
  ).action(async (options, command) => {
1957
3424
  const globalOptions = getGlobalOptions(command);
3425
+ const retryPolicy = parseRetryPolicy(options);
1958
3426
  const protocolVersion = options.protocolVersion;
3427
+ const accessToken = resolveServerProbeAccessToken(options);
1959
3428
  const config = parseServerConfig({
1960
3429
  ...options,
3430
+ ...options.credentialsFile ? { accessToken, credentialsFile: void 0 } : {},
1961
3431
  timeout: options.timeout ?? globalOptions.timeout
1962
3432
  });
1963
3433
  const target = describeTarget(options);
@@ -1975,13 +3445,14 @@ function registerServerCommands(program) {
1975
3445
  if (!probeUrl) {
1976
3446
  throw usageError("HTTP probe requires --url.");
1977
3447
  }
1978
- result = await sdk.probeMcpServer({
3448
+ result = await probeMcpServer({
1979
3449
  url: probeUrl,
1980
3450
  protocolVersion,
1981
3451
  headers: parseHeadersOption(options.header),
1982
- accessToken: resolveHttpAccessToken(options),
3452
+ accessToken,
1983
3453
  clientCapabilities: "clientCapabilities" in config ? config.clientCapabilities : void 0,
1984
- timeoutMs: options.timeout ?? globalOptions.timeout
3454
+ timeoutMs: options.timeout ?? globalOptions.timeout,
3455
+ retryPolicy
1985
3456
  });
1986
3457
  } catch (error) {
1987
3458
  commandError = error;
@@ -1989,6 +3460,7 @@ function registerServerCommands(program) {
1989
3460
  await writeCommandDebugArtifact({
1990
3461
  outputPath: options.debugOut,
1991
3462
  format: globalOptions.format,
3463
+ quiet: globalOptions.quiet,
1992
3464
  commandName: "server probe",
1993
3465
  commandInput: {
1994
3466
  protocolVersion,
@@ -2029,10 +3501,13 @@ function registerServerCommands(program) {
2029
3501
  setProcessExitCode(1);
2030
3502
  }
2031
3503
  });
2032
- addSharedServerOptions(
2033
- server.command("doctor").description("Run a stateless diagnostic sweep against an MCP server").option("--out <path>", "Write the doctor JSON artifact to a file")
3504
+ addRetryOptions(
3505
+ addSharedServerOptions(
3506
+ server.command("doctor").description("Run a stateless diagnostic sweep against an MCP server").option("--out <path>", "Write the doctor JSON artifact to a file")
3507
+ )
2034
3508
  ).action(async (options, command) => {
2035
3509
  const globalOptions = getGlobalOptions(command);
3510
+ const retryPolicy = parseRetryPolicy(options);
2036
3511
  const target = describeTarget(options);
2037
3512
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2038
3513
  const config = parseServerConfig({
@@ -2040,14 +3515,13 @@ function registerServerCommands(program) {
2040
3515
  timeout: globalOptions.timeout
2041
3516
  });
2042
3517
  const doctorTarget = summarizeServerDoctorTarget(target, config);
2043
- const result = await sdk.runServerDoctor(
2044
- {
2045
- config,
2046
- target: doctorTarget,
2047
- timeout: globalOptions.timeout,
2048
- rpcLogger: collector?.rpcLogger
2049
- }
2050
- );
3518
+ const result = await runServerDoctor({
3519
+ config,
3520
+ target: doctorTarget,
3521
+ timeout: globalOptions.timeout,
3522
+ rpcLogger: collector?.rpcLogger,
3523
+ retryPolicy
3524
+ });
2051
3525
  const jsonPayload = globalOptions.rpc ? attachCliRpcLogs(result, collector) : result;
2052
3526
  const artifactPath = options.out ? await writeDebugArtifact(options.out, jsonPayload) : void 0;
2053
3527
  if (globalOptions.format === "human") {
@@ -2062,10 +3536,13 @@ function registerServerCommands(program) {
2062
3536
  setProcessExitCode(1);
2063
3537
  }
2064
3538
  });
2065
- addSharedServerOptions(
2066
- server.command("info").description("Get initialization info for an MCP server")
3539
+ addRetryOptions(
3540
+ addSharedServerOptions(
3541
+ server.command("info").description("Get initialization info for an MCP server")
3542
+ )
2067
3543
  ).action(async (options, command) => {
2068
3544
  const globalOptions = getGlobalOptions(command);
3545
+ const retryPolicy = parseRetryPolicy(options);
2069
3546
  const target = describeTarget(options);
2070
3547
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2071
3548
  const config = parseServerConfig({
@@ -2085,18 +3562,22 @@ function registerServerCommands(program) {
2085
3562
  },
2086
3563
  {
2087
3564
  timeout: globalOptions.timeout,
2088
- rpcLogger: collector?.rpcLogger
3565
+ rpcLogger: collector?.rpcLogger,
3566
+ retryPolicy
2089
3567
  }
2090
3568
  );
2091
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
3569
+ writeResult(
3570
+ withRpcLogsIfRequested(result, collector, globalOptions),
3571
+ globalOptions.format
3572
+ );
2092
3573
  });
2093
- addSharedServerOptions(
2094
- server.command("validate").description("Connect to a server and verify the debugger surface works")
2095
- ).option(
2096
- "--debug-out <path>",
2097
- "Write a structured debug artifact to a file"
2098
- ).action(async (options, command) => {
3574
+ addRetryOptions(
3575
+ addSharedServerOptions(
3576
+ server.command("validate").description("Connect to a server and verify the debugger surface works")
3577
+ )
3578
+ ).option("--debug-out <path>", "Write a structured debug artifact to a file").action(async (options, command) => {
2099
3579
  const globalOptions = getGlobalOptions(command);
3580
+ const retryPolicy = parseRetryPolicy(options);
2100
3581
  const target = describeTarget(options);
2101
3582
  const primaryCollector = globalOptions.rpc || options.debugOut ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2102
3583
  const snapshotCollector = options.debugOut ? createCliRpcLogCollector({ __cli__: target }) : void 0;
@@ -2121,7 +3602,8 @@ function registerServerCommands(program) {
2121
3602
  },
2122
3603
  {
2123
3604
  timeout: globalOptions.timeout,
2124
- rpcLogger: primaryCollector?.rpcLogger
3605
+ rpcLogger: primaryCollector?.rpcLogger,
3606
+ retryPolicy
2125
3607
  }
2126
3608
  );
2127
3609
  } catch (error) {
@@ -2130,6 +3612,7 @@ function registerServerCommands(program) {
2130
3612
  await writeCommandDebugArtifact({
2131
3613
  outputPath: options.debugOut,
2132
3614
  format: globalOptions.format,
3615
+ quiet: globalOptions.quiet,
2133
3616
  commandName: "server validate",
2134
3617
  commandInput: {},
2135
3618
  target: targetSummary,
@@ -2158,10 +3641,13 @@ function registerServerCommands(program) {
2158
3641
  globalOptions.format
2159
3642
  );
2160
3643
  });
2161
- addSharedServerOptions(
2162
- server.command("ping").description("Ping an MCP server")
3644
+ addRetryOptions(
3645
+ addSharedServerOptions(
3646
+ server.command("ping").description("Ping an MCP server")
3647
+ )
2163
3648
  ).action(async (options, command) => {
2164
3649
  const globalOptions = getGlobalOptions(command);
3650
+ const retryPolicy = parseRetryPolicy(options);
2165
3651
  const target = describeTarget(options);
2166
3652
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2167
3653
  const config = parseServerConfig({
@@ -2177,15 +3663,22 @@ function registerServerCommands(program) {
2177
3663
  }),
2178
3664
  {
2179
3665
  timeout: globalOptions.timeout,
2180
- rpcLogger: collector?.rpcLogger
3666
+ rpcLogger: collector?.rpcLogger,
3667
+ retryPolicy
2181
3668
  }
2182
3669
  );
2183
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
3670
+ writeResult(
3671
+ withRpcLogsIfRequested(result, collector, globalOptions),
3672
+ globalOptions.format
3673
+ );
2184
3674
  });
2185
- addSharedServerOptions(
2186
- server.command("capabilities").description("Get resolved server capabilities")
3675
+ addRetryOptions(
3676
+ addSharedServerOptions(
3677
+ server.command("capabilities").description("Get resolved server capabilities")
3678
+ )
2187
3679
  ).action(async (options, command) => {
2188
3680
  const globalOptions = getGlobalOptions(command);
3681
+ const retryPolicy = parseRetryPolicy(options);
2189
3682
  const target = describeTarget(options);
2190
3683
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2191
3684
  const config = parseServerConfig({
@@ -2200,38 +3693,243 @@ function registerServerCommands(program) {
2200
3693
  }),
2201
3694
  {
2202
3695
  timeout: globalOptions.timeout,
2203
- rpcLogger: collector?.rpcLogger
3696
+ rpcLogger: collector?.rpcLogger,
3697
+ retryPolicy
2204
3698
  }
2205
3699
  );
2206
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
3700
+ writeResult(
3701
+ withRpcLogsIfRequested(result, collector, globalOptions),
3702
+ globalOptions.format
3703
+ );
2207
3704
  });
2208
- addSharedServerOptions(
2209
- server.command("export").description("Export server tools, resources, prompts, and capabilities")
3705
+ addRetryOptions(
3706
+ addSharedServerOptions(
3707
+ server.command("export").description(
3708
+ "Export server tools, resources, prompts, and capabilities"
3709
+ ).option(
3710
+ "--stable",
3711
+ "Emit the deterministic versioned snapshot format for baselines"
3712
+ )
3713
+ )
2210
3714
  ).action(async (options, command) => {
2211
3715
  const globalOptions = getGlobalOptions(command);
3716
+ const retryPolicy = parseRetryPolicy(options);
2212
3717
  const target = describeTarget(options);
2213
3718
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2214
3719
  const config = parseServerConfig({
2215
3720
  ...options,
2216
3721
  timeout: globalOptions.timeout
2217
3722
  });
2218
- const result = await withEphemeralManager(
3723
+ const snapshot = await collectServerSnapshot({
2219
3724
  config,
2220
- (manager, serverId) => exportServerSnapshot(manager, serverId, target),
2221
- {
3725
+ target,
3726
+ timeout: globalOptions.timeout,
3727
+ rpcLogger: collector?.rpcLogger,
3728
+ retryPolicy,
3729
+ clientName: "mcpjam",
3730
+ serverId: "__cli__"
3731
+ });
3732
+ const result = options.stable ? serializeStableServerSnapshot(snapshot) : serializeServerSnapshot(snapshot, { mode: "raw" });
3733
+ writeResult(
3734
+ options.stable ? result : withRpcLogsIfRequested(result, collector, globalOptions),
3735
+ globalOptions.format
3736
+ );
3737
+ });
3738
+ addRetryOptions(
3739
+ addSharedServerOptions(
3740
+ server.command("diff").description(
3741
+ "Compare a server snapshot baseline against a live or file snapshot"
3742
+ ).option(
3743
+ "--baseline <path>",
3744
+ "Compare a baseline file to a live server target"
3745
+ ).option(
3746
+ "--left <path>",
3747
+ "Left snapshot file for file-vs-file comparison"
3748
+ ).option(
3749
+ "--right <path>",
3750
+ "Right snapshot file for file-vs-file comparison"
3751
+ ).option(
3752
+ "--fail-on <policy>",
3753
+ "Diff failure policy: breaking, any, or none"
3754
+ ).option(
3755
+ "--reporter <reporter>",
3756
+ "Structured reporter output: json-summary or junit-xml"
3757
+ ).option("--out <path>", "Write the raw diff JSON artifact to a file")
3758
+ )
3759
+ ).action(async (options, command) => {
3760
+ const globalOptions = getGlobalOptions(command);
3761
+ const retryPolicy = parseRetryPolicy(options);
3762
+ const reporter = parseReporterFormat(
3763
+ options.reporter
3764
+ );
3765
+ const mode = resolveServerDiffMode(options);
3766
+ let rawDiff;
3767
+ let collector;
3768
+ if (mode.kind === "baseline-live") {
3769
+ const target = describeTarget(options);
3770
+ collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
3771
+ const config = parseServerConfig({
3772
+ ...options,
3773
+ timeout: globalOptions.timeout
3774
+ });
3775
+ const baselineSnapshot = await readSnapshotFile(mode.baselinePath);
3776
+ const currentSnapshot = await collectServerSnapshot({
3777
+ config,
3778
+ target,
2222
3779
  timeout: globalOptions.timeout,
2223
- rpcLogger: collector?.rpcLogger
3780
+ rpcLogger: collector?.rpcLogger,
3781
+ retryPolicy,
3782
+ clientName: "mcpjam",
3783
+ serverId: "__cli__"
3784
+ });
3785
+ rawDiff = createServerDiffResult(
3786
+ baselineSnapshot,
3787
+ currentSnapshot,
3788
+ parseDiffFailOn(options.failOn)
3789
+ );
3790
+ } else {
3791
+ if (hasServerTargetOptions(options)) {
3792
+ throw usageError(
3793
+ "Do not pass live target options together with --left/--right file comparison."
3794
+ );
2224
3795
  }
2225
- );
2226
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
3796
+ const [leftSnapshot, rightSnapshot] = await Promise.all([
3797
+ readSnapshotFile(mode.leftPath),
3798
+ readSnapshotFile(mode.rightPath)
3799
+ ]);
3800
+ rawDiff = createServerDiffResult(
3801
+ leftSnapshot,
3802
+ rightSnapshot,
3803
+ parseDiffFailOn(options.failOn)
3804
+ );
3805
+ }
3806
+ if (options.out) {
3807
+ await writeJsonArtifact(options.out, rawDiff);
3808
+ }
3809
+ if (reporter) {
3810
+ writeReporterResult(
3811
+ reporter,
3812
+ buildServerDiffReport(rawDiff, {
3813
+ metadata: mode.kind === "baseline-live" ? {
3814
+ comparisonMode: mode.kind,
3815
+ baselinePath: mode.baselinePath
3816
+ } : {
3817
+ comparisonMode: mode.kind,
3818
+ leftPath: mode.leftPath,
3819
+ rightPath: mode.rightPath
3820
+ }
3821
+ })
3822
+ );
3823
+ } else {
3824
+ writeResult(
3825
+ withRpcLogsIfRequested(rawDiff, collector, globalOptions),
3826
+ globalOptions.format
3827
+ );
3828
+ }
3829
+ if (!rawDiff.passed) {
3830
+ setProcessExitCode(1);
3831
+ }
2227
3832
  });
2228
3833
  }
3834
+ function resolveServerProbeAccessToken(options) {
3835
+ assertNoCredentialsFileAuthConflicts(options);
3836
+ if (options.credentialsFile) {
3837
+ const url = options.url?.trim();
3838
+ if (!url) {
3839
+ throw usageError("--credentials-file requires --url.");
3840
+ }
3841
+ return resolveCredentialsFileAccessToken(options.credentialsFile, url);
3842
+ }
3843
+ return resolveHttpAccessToken(options);
3844
+ }
3845
+ function hasServerTargetOptions(options) {
3846
+ return typeof options.url === "string" || typeof options.command === "string";
3847
+ }
3848
+ function resolveServerDiffMode(options) {
3849
+ const baselinePath = toOptionalString(options.baseline);
3850
+ const leftPath = toOptionalString(options.left);
3851
+ const rightPath = toOptionalString(options.right);
3852
+ if (baselinePath && (leftPath || rightPath)) {
3853
+ throw usageError(
3854
+ "Specify either --baseline with a live target or --left/--right for file comparison."
3855
+ );
3856
+ }
3857
+ if (baselinePath) {
3858
+ return {
3859
+ kind: "baseline-live",
3860
+ baselinePath
3861
+ };
3862
+ }
3863
+ if (leftPath && rightPath) {
3864
+ return {
3865
+ kind: "file-file",
3866
+ leftPath,
3867
+ rightPath
3868
+ };
3869
+ }
3870
+ if (leftPath || rightPath) {
3871
+ throw usageError(
3872
+ "Both --left and --right are required for file comparison."
3873
+ );
3874
+ }
3875
+ throw usageError(
3876
+ "Specify either --baseline with a live target or --left/--right for file comparison."
3877
+ );
3878
+ }
3879
+ function parseDiffFailOn(value) {
3880
+ if (value === void 0) {
3881
+ return void 0;
3882
+ }
3883
+ if (value === "breaking" || value === "any" || value === "none") {
3884
+ return value;
3885
+ }
3886
+ throw usageError(
3887
+ `Invalid fail-on policy "${value}". Use "breaking", "any", or "none".`
3888
+ );
3889
+ }
3890
+ async function readSnapshotFile(filePath) {
3891
+ let contents;
3892
+ try {
3893
+ contents = await readFile(filePath, "utf8");
3894
+ } catch (error) {
3895
+ throw operationalError(`Failed to read snapshot file "${filePath}".`, {
3896
+ source: error instanceof Error ? error.message : String(error)
3897
+ });
3898
+ }
3899
+ try {
3900
+ return JSON.parse(contents);
3901
+ } catch (error) {
3902
+ throw usageError(`Snapshot file "${filePath}" must contain valid JSON.`, {
3903
+ source: error instanceof Error ? error.message : String(error)
3904
+ });
3905
+ }
3906
+ }
3907
+ function toOptionalString(value) {
3908
+ if (typeof value !== "string") {
3909
+ return void 0;
3910
+ }
3911
+ const normalized = value.trim();
3912
+ return normalized.length > 0 ? normalized : void 0;
3913
+ }
3914
+ function createServerDiffResult(left, right, failOn) {
3915
+ try {
3916
+ return diffServerSnapshots(left, right, { failOn });
3917
+ } catch (error) {
3918
+ if (error instanceof ServerSnapshotFormatError) {
3919
+ throw usageError(error.message);
3920
+ }
3921
+ throw error;
3922
+ }
3923
+ }
2229
3924
  function registerToolsCommands(program) {
2230
3925
  const tools = program.command("tools").description("List and invoke MCP server tools");
2231
- addSharedServerOptions(
2232
- 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")
3926
+ addRetryOptions(
3927
+ addSharedServerOptions(
3928
+ 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")
3929
+ )
2233
3930
  ).action(async (options, command) => {
2234
3931
  const globalOptions = getGlobalOptions(command);
3932
+ const retryPolicy = parseRetryPolicy(options);
2235
3933
  const target = describeTarget(options);
2236
3934
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
2237
3935
  const config = parseServerConfig({
@@ -2247,13 +3945,29 @@ function registerToolsCommands(program) {
2247
3945
  }),
2248
3946
  {
2249
3947
  timeout: globalOptions.timeout,
2250
- rpcLogger: collector?.rpcLogger
3948
+ rpcLogger: collector?.rpcLogger,
3949
+ retryPolicy
2251
3950
  }
2252
3951
  );
2253
- writeResult(withRpcLogsIfRequested(result, collector, globalOptions), globalOptions.format);
3952
+ writeResult(
3953
+ withRpcLogsIfRequested(result, collector, globalOptions),
3954
+ globalOptions.format
3955
+ );
2254
3956
  });
2255
3957
  addSharedServerOptions(
2256
- 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(
3958
+ tools.command("call").description("Call an MCP tool").option("--tool-name <tool>", "Tool name").option("--name <tool>", "Alias for --tool-name").option(
3959
+ "--tool-args <json>",
3960
+ "Tool parameter object as JSON, @path, or - for stdin"
3961
+ ).option("--params <json>", "Alias for --tool-args").option(
3962
+ "--validate-response",
3963
+ "Validate the MCP tool-call envelope returned by the server"
3964
+ ).option(
3965
+ "--expect-success",
3966
+ "Evaluate the tool-call outcome policy against isError"
3967
+ ).option(
3968
+ "--reporter <reporter>",
3969
+ "Structured reporter output: json-summary or junit-xml"
3970
+ ).option(
2257
3971
  "--debug-out <path>",
2258
3972
  "Write a structured debug artifact to a file"
2259
3973
  )
@@ -2266,6 +3980,9 @@ function registerToolsCommands(program) {
2266
3980
  ...options,
2267
3981
  timeout: globalOptions.timeout
2268
3982
  });
3983
+ const reporter = parseReporterFormat(
3984
+ options.reporter
3985
+ );
2269
3986
  const toolName = resolveAliasedStringOption(
2270
3987
  options,
2271
3988
  [
@@ -2285,8 +4002,16 @@ function registerToolsCommands(program) {
2285
4002
  );
2286
4003
  const params = parseJsonRecord(paramsInput, "Tool parameters") ?? {};
2287
4004
  const targetSummary = summarizeServerDoctorTarget(target, config);
4005
+ const shouldValidateResponse = options.validateResponse === true;
4006
+ const shouldExpectSuccess = options.expectSuccess === true;
4007
+ if (reporter && !shouldValidateResponse && !shouldExpectSuccess) {
4008
+ throw usageError(
4009
+ "--reporter requires --validate-response and/or --expect-success."
4010
+ );
4011
+ }
2288
4012
  let result;
2289
4013
  let commandError;
4014
+ const startedAt = Date.now();
2290
4015
  try {
2291
4016
  result = await withEphemeralManager(
2292
4017
  config,
@@ -2302,6 +4027,7 @@ function registerToolsCommands(program) {
2302
4027
  await writeCommandDebugArtifact({
2303
4028
  outputPath: options.debugOut,
2304
4029
  format: globalOptions.format,
4030
+ quiet: globalOptions.quiet,
2305
4031
  commandName: "tools call",
2306
4032
  commandInput: {
2307
4033
  toolName,
@@ -2328,20 +4054,325 @@ function registerToolsCommands(program) {
2328
4054
  if (commandError) {
2329
4055
  throw commandError;
2330
4056
  }
4057
+ const validationResult = shouldValidateResponse || shouldExpectSuccess ? validateToolCallResult(result, {
4058
+ envelope: shouldValidateResponse,
4059
+ outcome: shouldExpectSuccess ? { failOnIsError: true } : void 0
4060
+ }) : void 0;
4061
+ if (reporter) {
4062
+ writeReporterResult(
4063
+ reporter,
4064
+ buildToolCallValidationReport(validationResult, {
4065
+ durationMs: Date.now() - startedAt,
4066
+ rawResult: result,
4067
+ metadata: {
4068
+ toolName
4069
+ }
4070
+ })
4071
+ );
4072
+ } else {
4073
+ writeResult(
4074
+ withRpcLogsIfRequested(result, primaryCollector, globalOptions),
4075
+ globalOptions.format
4076
+ );
4077
+ }
4078
+ if (validationResult && !validationResult.passed) {
4079
+ setProcessExitCode(1);
4080
+ }
4081
+ if (isCallToolResultError(result)) {
4082
+ setProcessExitCode(1);
4083
+ }
4084
+ });
4085
+ }
4086
+
4087
+ // src/commands/inspector.ts
4088
+ function addInspectorUrlOption(command) {
4089
+ return command.option("--inspector-url <url>", "Local Inspector base URL");
4090
+ }
4091
+ function resolveInspectorBaseUrl(options) {
4092
+ return normalizeInspectorBaseUrl(
4093
+ typeof options.inspectorUrl === "string" ? options.inspectorUrl : void 0
4094
+ );
4095
+ }
4096
+ function registerInspectorCommands(program) {
4097
+ const inspector = program.command("inspector").description("Start or attach to the local MCPJam Inspector");
4098
+ addInspectorUrlOption(
4099
+ inspector.command("open").description("Start or attach to the local Inspector and open the UI")
4100
+ ).option("--tab <tab>", "Open the Inspector on a specific tab").action(async (options, command) => {
4101
+ const globalOptions = getGlobalOptions(command);
4102
+ const baseUrl = resolveInspectorBaseUrl(options);
4103
+ const tab = typeof options.tab === "string" && options.tab.trim().length > 0 ? options.tab.trim() : void 0;
4104
+ const result = await ensureInspector({
4105
+ baseUrl,
4106
+ openBrowser: true,
4107
+ startIfNeeded: true,
4108
+ tab,
4109
+ timeoutMs: globalOptions.timeout
4110
+ });
2331
4111
  writeResult(
2332
- withRpcLogsIfRequested(result, primaryCollector, globalOptions),
4112
+ {
4113
+ success: true,
4114
+ started: result.started,
4115
+ baseUrl: result.baseUrl,
4116
+ url: buildInspectorUrl(result.baseUrl, tab),
4117
+ ...tab ? { tab } : {}
4118
+ },
4119
+ globalOptions.format
4120
+ );
4121
+ });
4122
+ addInspectorUrlOption(
4123
+ inspector.command("start").description(
4124
+ "Start the local Inspector in the background without opening a browser"
4125
+ )
4126
+ ).action(async (options, command) => {
4127
+ const globalOptions = getGlobalOptions(command);
4128
+ const baseUrl = resolveInspectorBaseUrl(options);
4129
+ const result = await ensureInspector({
4130
+ baseUrl,
4131
+ openBrowser: false,
4132
+ startIfNeeded: true,
4133
+ timeoutMs: globalOptions.timeout
4134
+ });
4135
+ writeResult(
4136
+ {
4137
+ success: true,
4138
+ started: result.started,
4139
+ baseUrl: result.baseUrl
4140
+ },
4141
+ globalOptions.format
4142
+ );
4143
+ });
4144
+ addInspectorUrlOption(
4145
+ inspector.command("stop").description("Stop the local Inspector if it is running")
4146
+ ).action(async (options, command) => {
4147
+ const globalOptions = getGlobalOptions(command);
4148
+ const baseUrl = resolveInspectorBaseUrl(options);
4149
+ const result = await stopInspector(baseUrl);
4150
+ writeResult(
4151
+ {
4152
+ success: true,
4153
+ stopped: result.stopped,
4154
+ baseUrl: result.baseUrl
4155
+ },
2333
4156
  globalOptions.format
2334
4157
  );
2335
- if (sdk.isCallToolResultError(result)) {
2336
- setProcessExitCode(1);
2337
- }
2338
4158
  });
2339
4159
  }
4160
+ var DEFAULT_UPDATE_PACKAGE_NAME = "@mcpjam/cli";
4161
+ var UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
4162
+ var UPDATE_CACHE_FILE = "update-check.json";
4163
+ var BACKGROUND_FETCH_SCRIPT = `
4164
+ const fs = require("node:fs");
4165
+ const https = require("node:https");
4166
+ const path = require("node:path");
4167
+
4168
+ const cachePath = process.argv[1];
4169
+ const packageName = process.argv[2];
4170
+
4171
+ if (!cachePath || !packageName) {
4172
+ process.exit(0);
4173
+ }
4174
+
4175
+ const maxResponseBytes = 1024 * 1024;
4176
+ const registryPackageName = encodeURIComponent(packageName);
4177
+ const request = https.get(
4178
+ "https://registry.npmjs.org/" + registryPackageName + "/latest",
4179
+ {
4180
+ headers: {
4181
+ accept: "application/json",
4182
+ "user-agent": packageName + " update notifier",
4183
+ },
4184
+ },
4185
+ (response) => {
4186
+ if (response.statusCode !== 200) {
4187
+ response.resume();
4188
+ return;
4189
+ }
4190
+
4191
+ const chunks = [];
4192
+ let bytes = 0;
4193
+
4194
+ response.on("error", () => {});
4195
+ response.on("data", (chunk) => {
4196
+ bytes += chunk.length;
4197
+ if (bytes > maxResponseBytes) {
4198
+ request.destroy();
4199
+ return;
4200
+ }
4201
+ chunks.push(chunk);
4202
+ });
4203
+
4204
+ response.on("end", () => {
4205
+ try {
4206
+ const body = Buffer.concat(chunks, bytes).toString("utf8");
4207
+ const payload = JSON.parse(body);
4208
+ if (typeof payload.version !== "string") {
4209
+ return;
4210
+ }
4211
+
4212
+ fs.mkdirSync(path.dirname(cachePath), { recursive: true });
4213
+ const temporaryPath = cachePath + "." + process.pid + ".tmp";
4214
+ fs.writeFileSync(
4215
+ temporaryPath,
4216
+ JSON.stringify({
4217
+ latestVersion: payload.version,
4218
+ checkedAt: Date.now(),
4219
+ }),
4220
+ "utf8",
4221
+ );
4222
+ fs.renameSync(temporaryPath, cachePath);
4223
+ } catch {
4224
+ // Silently ignore: update cache refresh is best-effort.
4225
+ }
4226
+ });
4227
+ },
4228
+ );
4229
+
4230
+ request.setTimeout(2500, () => {
4231
+ request.destroy();
4232
+ });
4233
+ request.on("error", () => {});
4234
+ `;
4235
+ function getUpdateCacheDir(options = {}) {
4236
+ const env = options.env ?? process.env;
4237
+ const platform = options.platform ?? process.platform;
4238
+ const homeDirectory = options.homeDirectory ?? homedir();
4239
+ if (platform === "win32") {
4240
+ return join(
4241
+ env.LOCALAPPDATA || join(homeDirectory, "AppData", "Local"),
4242
+ "mcpjam",
4243
+ "Cache"
4244
+ );
4245
+ }
4246
+ if (platform === "darwin") {
4247
+ return join(homeDirectory, "Library", "Caches", "mcpjam");
4248
+ }
4249
+ return join(env.XDG_CACHE_HOME || join(homeDirectory, ".cache"), "mcpjam");
4250
+ }
4251
+ function getUpdateCachePath(options = {}) {
4252
+ return join(getUpdateCacheDir(options), UPDATE_CACHE_FILE);
4253
+ }
4254
+ function readUpdateCache(cachePath) {
4255
+ try {
4256
+ const payload = JSON.parse(readFileSync(cachePath, "utf8"));
4257
+ if (!payload || typeof payload !== "object" || Array.isArray(payload) || typeof payload.latestVersion !== "string" || typeof payload.checkedAt !== "number" || !Number.isFinite(payload.checkedAt)) {
4258
+ return null;
4259
+ }
4260
+ return {
4261
+ latestVersion: payload.latestVersion,
4262
+ checkedAt: payload.checkedAt
4263
+ };
4264
+ } catch {
4265
+ return null;
4266
+ }
4267
+ }
4268
+ function isUpdateCacheFresh(cache, now = Date.now()) {
4269
+ return now - cache.checkedAt < UPDATE_CHECK_INTERVAL_MS;
4270
+ }
4271
+ function shouldSkipUpdateCheck(options = {}) {
4272
+ const env = options.env ?? process.env;
4273
+ const isStderrTTY = options.isStderrTTY ?? Boolean(process.stderr.isTTY);
4274
+ return Boolean(
4275
+ env.CI || env.NO_UPDATE_NOTIFIER || env.MCPJAM_NO_UPDATE_CHECK || !isStderrTTY
4276
+ );
4277
+ }
4278
+ function isNewerVersion(latest, current) {
4279
+ const latestVersion = parseStableVersion(latest);
4280
+ const currentVersion = parseStableVersion(current);
4281
+ if (!latestVersion || !currentVersion) {
4282
+ return false;
4283
+ }
4284
+ for (let index = 0; index < latestVersion.length; index += 1) {
4285
+ if (latestVersion[index] > currentVersion[index]) {
4286
+ return true;
4287
+ }
4288
+ if (latestVersion[index] < currentVersion[index]) {
4289
+ return false;
4290
+ }
4291
+ }
4292
+ return false;
4293
+ }
4294
+ function spawnBackgroundFetch(cachePath, packageName = DEFAULT_UPDATE_PACKAGE_NAME, options = {}) {
4295
+ try {
4296
+ const spawn2 = options.spawn ?? spawn;
4297
+ const child = spawn2(
4298
+ options.execPath ?? process.execPath,
4299
+ ["-e", BACKGROUND_FETCH_SCRIPT, cachePath, packageName],
4300
+ {
4301
+ detached: true,
4302
+ stdio: "ignore"
4303
+ }
4304
+ );
4305
+ child.on("error", () => {
4306
+ });
4307
+ child.unref();
4308
+ } catch {
4309
+ }
4310
+ }
4311
+ function printUpdateNotification(currentVersion, latestVersion, packageName = DEFAULT_UPDATE_PACKAGE_NAME, stderr = process.stderr) {
4312
+ stderr.write(
4313
+ `Update available: ${packageName} ${currentVersion} -> ${latestVersion}
4314
+ Run npm install -g ${packageName} to update
4315
+ `
4316
+ );
4317
+ }
4318
+ function checkForUpdates(currentVersion, options = {}) {
4319
+ try {
4320
+ const env = options.env ?? process.env;
4321
+ if (shouldSkipUpdateCheck({
4322
+ env,
4323
+ isStderrTTY: options.isStderrTTY
4324
+ })) {
4325
+ return;
4326
+ }
4327
+ const now = typeof options.now === "function" ? options.now() : options.now ?? Date.now();
4328
+ const packageName = options.packageName ?? DEFAULT_UPDATE_PACKAGE_NAME;
4329
+ const cachePath = options.cachePath ?? getUpdateCachePath({
4330
+ env
4331
+ });
4332
+ const cache = readUpdateCache(cachePath);
4333
+ if (cache) {
4334
+ const hasNewerCachedVersion = isNewerVersion(
4335
+ cache.latestVersion,
4336
+ currentVersion
4337
+ );
4338
+ if (hasNewerCachedVersion) {
4339
+ printUpdateNotification(
4340
+ currentVersion,
4341
+ cache.latestVersion,
4342
+ packageName,
4343
+ options.stderr
4344
+ );
4345
+ }
4346
+ if (isUpdateCacheFresh(cache, now)) {
4347
+ return;
4348
+ }
4349
+ }
4350
+ const fetchSpawner = options.spawnBackgroundFetch ?? spawnBackgroundFetch;
4351
+ fetchSpawner(cachePath, packageName);
4352
+ } catch {
4353
+ }
4354
+ }
4355
+ function parseStableVersion(value) {
4356
+ if (typeof value !== "string") {
4357
+ return null;
4358
+ }
4359
+ const normalized = value.startsWith("v") ? value.slice(1) : value;
4360
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(normalized);
4361
+ if (!match) {
4362
+ return null;
4363
+ }
4364
+ const parts = match.slice(1).map((part) => Number(part));
4365
+ if (!parts.every((part) => Number.isSafeInteger(part) && part >= 0)) {
4366
+ return null;
4367
+ }
4368
+ return [parts[0], parts[1], parts[2]];
4369
+ }
2340
4370
 
2341
4371
  // src/index.ts
4372
+ var pkgVersion = package_default.version;
2342
4373
  async function main(argv = process.argv) {
2343
4374
  const program = addGlobalOptions(
2344
- new commander.Command().name("mcpjam").version(version, "-v, --version", "output the CLI version").description(
4375
+ new Command().name("mcpjam").version(pkgVersion, "-v, --version", "output the CLI version").description(
2345
4376
  "Test, debug, and validate MCP servers. Health checks, OAuth conformance, tool-surface diffing, and structured triage from the terminal or CI."
2346
4377
  ).allowExcessArguments(false).exitOverride().configureOutput({
2347
4378
  writeOut: (value) => process.stdout.write(value),
@@ -2356,33 +4387,77 @@ async function main(argv = process.argv) {
2356
4387
  registerAppsCommands(program);
2357
4388
  registerOAuthCommands(program);
2358
4389
  registerProtocolCommands(program);
4390
+ registerInspectorCommands(program);
2359
4391
  if (argv.length <= 2) {
2360
4392
  program.outputHelp();
2361
- return 0;
4393
+ return {
4394
+ exitCode: 0,
4395
+ shouldCheckForUpdates: false
4396
+ };
2362
4397
  }
2363
4398
  try {
2364
4399
  await program.parseAsync(argv);
2365
4400
  const exitCode = process.exitCode;
2366
4401
  if (typeof exitCode === "number") {
2367
- return exitCode;
4402
+ return {
4403
+ exitCode,
4404
+ shouldCheckForUpdates: true
4405
+ };
2368
4406
  }
2369
- return Number(exitCode ?? 0) || 0;
4407
+ return {
4408
+ exitCode: Number(exitCode ?? 0) || 0,
4409
+ shouldCheckForUpdates: true
4410
+ };
2370
4411
  } catch (error) {
2371
4412
  const format = detectOutputFormatFromArgv(argv);
2372
- if (error instanceof commander.CommanderError) {
4413
+ if (error instanceof CommanderError) {
2373
4414
  if (error.code === "commander.helpDisplayed" || error.code === "commander.version") {
2374
- return 0;
4415
+ return {
4416
+ exitCode: 0,
4417
+ shouldCheckForUpdates: false
4418
+ };
2375
4419
  }
2376
4420
  writeError(usageError(error.message), format);
2377
- return 2;
4421
+ return {
4422
+ exitCode: 2,
4423
+ shouldCheckForUpdates: false
4424
+ };
2378
4425
  }
2379
4426
  const normalizedError = normalizeCliError(error);
2380
4427
  writeError(normalizedError, format);
2381
- return normalizedError.exitCode;
4428
+ return {
4429
+ exitCode: normalizedError.exitCode,
4430
+ shouldCheckForUpdates: false
4431
+ };
2382
4432
  }
2383
4433
  }
2384
- void main().then((exitCode) => {
2385
- process.exitCode = exitCode;
2386
- });
4434
+ async function runCliEntrypoint(argv = process.argv, dependencies = {}) {
4435
+ const result = await main(argv);
4436
+ process.exitCode = result.exitCode;
4437
+ if (result.exitCode === 0 && result.shouldCheckForUpdates) {
4438
+ (dependencies.checkForUpdates ?? checkForUpdates)(pkgVersion);
4439
+ }
4440
+ return result;
4441
+ }
4442
+ function isDirectRun(importMetaUrl, argv = process.argv) {
4443
+ const entrypoint = argv[1];
4444
+ if (!entrypoint) {
4445
+ return false;
4446
+ }
4447
+ const entrypointUrl = pathToFileURL(entrypoint).href;
4448
+ if (importMetaUrl === entrypointUrl) {
4449
+ return true;
4450
+ }
4451
+ try {
4452
+ return importMetaUrl === pathToFileURL(realpathSync(entrypoint)).href;
4453
+ } catch {
4454
+ return false;
4455
+ }
4456
+ }
4457
+ if (isDirectRun(import.meta.url)) {
4458
+ void runCliEntrypoint();
4459
+ }
4460
+
4461
+ export { isDirectRun, main, runCliEntrypoint };
2387
4462
  //# sourceMappingURL=index.js.map
2388
4463
  //# sourceMappingURL=index.js.map