@mcpjam/cli 2.1.0 → 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.1.0";
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,8 +244,389 @@ function extractHtmlFromResourceContent(content) {
228
244
  }
229
245
  return "";
230
246
  }
247
+
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
+ );
274
+ }
275
+ let config;
276
+ try {
277
+ config = JSON.parse(raw);
278
+ } catch {
279
+ throw usageError(`Config file "${filePath}" is not valid JSON`);
280
+ }
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".`
493
+ );
494
+ }
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".`
599
+ );
600
+ }
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
+ }
231
628
  async function withEphemeralManager(config, fn, options) {
232
- return sdk.withEphemeralClient(config, fn, {
629
+ return withEphemeralClient(config, fn, {
233
630
  serverId: "__cli__",
234
631
  clientName: "mcpjam",
235
632
  timeout: options?.timeout ?? 3e4,
@@ -278,7 +675,7 @@ function getCliRpcLogEvents(collectors) {
278
675
  function redactCliRpcLogs(logs) {
279
676
  return logs.map((event) => ({
280
677
  ...event,
281
- message: sdk.redactSensitiveValue(event.message)
678
+ message: redactSensitiveValue(event.message)
282
679
  }));
283
680
  }
284
681
 
@@ -289,25 +686,241 @@ function withRpcLogsIfRequested(value, collector, options) {
289
686
  }
290
687
  return attachCliRpcLogs(value, collector);
291
688
  }
292
-
293
- // src/lib/server-config.ts
294
- var DEFAULT_CLI_RETRY_POLICY = {
295
- retries: 0,
296
- retryDelayMs: 3e3
297
- };
298
- function collectString(value, previous = []) {
299
- return [...previous, value];
300
- }
301
- function addSharedServerOptions(command) {
302
- return command.option(
303
- "--transport <transport>",
304
- 'Explicit transport type: "http" or "stdio"'
305
- ).option("--url <url>", "HTTP MCP server URL").option("--access-token <token>", "Bearer access token for HTTP servers").option(
306
- "--oauth-access-token <token>",
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;
725
+ }
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(
916
+ "--oauth-access-token <token>",
307
917
  "OAuth bearer access token for HTTP servers"
308
918
  ).option("--refresh-token <token>", "OAuth refresh token for HTTP servers").option("--client-id <id>", "OAuth client ID used with --refresh-token").option(
309
919
  "--client-secret <secret>",
310
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"
311
924
  ).option(
312
925
  "--header <header>",
313
926
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
@@ -315,7 +928,7 @@ function addSharedServerOptions(command) {
315
928
  []
316
929
  ).option(
317
930
  "--client-capabilities <json>",
318
- "Client capabilities advertised to the server as a JSON object"
931
+ "Client capabilities as JSON, @path, or - for stdin"
319
932
  ).option("--command <command>", "Command for a stdio MCP server").option(
320
933
  "--args <arg...>",
321
934
  "Preferred stdio command arguments. Pass multiple values or repeat the flag."
@@ -336,7 +949,8 @@ function getGlobalOptions(command) {
336
949
  process.stdout.isTTY
337
950
  ),
338
951
  timeout: options.timeout ?? 3e4,
339
- rpc: options.rpc ?? false
952
+ rpc: options.rpc ?? false,
953
+ quiet: options.quiet ?? false
340
954
  };
341
955
  }
342
956
  function parsePositiveInteger(value, label = "Value") {
@@ -384,21 +998,7 @@ function parseHeadersOption(headers) {
384
998
  return Object.fromEntries(headers.map(parseHeader));
385
999
  }
386
1000
  function parseJsonRecord(value, label) {
387
- if (value === void 0) {
388
- return void 0;
389
- }
390
- let parsed;
391
- try {
392
- parsed = JSON.parse(value);
393
- } catch (error) {
394
- throw usageError(`${label} must be valid JSON.`, {
395
- source: error instanceof Error ? error.message : String(error)
396
- });
397
- }
398
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
399
- throw usageError(`${label} must be a JSON object.`);
400
- }
401
- return parsed;
1001
+ return parseJsonInputRecord(value, label);
402
1002
  }
403
1003
  function parseUnknownRecord(value, label) {
404
1004
  if (value === void 0) {
@@ -470,10 +1070,12 @@ function parseServerConfig(options) {
470
1070
  throw usageError(`Invalid URL: ${url}`);
471
1071
  }
472
1072
  const headers = parseHeadersOption(options.header);
473
- const accessToken = resolveHttpAccessToken(options);
474
- const refreshToken = options.refreshToken?.trim();
475
- const clientId = options.clientId?.trim();
476
- const clientSecret = options.clientSecret?.trim();
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;
477
1079
  if (refreshToken && accessToken) {
478
1080
  throw usageError(
479
1081
  "--refresh-token cannot be used together with --access-token or --oauth-access-token."
@@ -501,9 +1103,9 @@ function parseServerConfig(options) {
501
1103
  if (!command) {
502
1104
  throw usageError("Missing stdio command.");
503
1105
  }
504
- 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) {
505
1107
  throw usageError(
506
- "--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."
507
1109
  );
508
1110
  }
509
1111
  return {
@@ -522,7 +1124,7 @@ function addGlobalOptions(program) {
522
1124
  "Request timeout in milliseconds",
523
1125
  (value) => parsePositiveInteger(value, "Timeout"),
524
1126
  3e4
525
- ).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");
526
1128
  }
527
1129
  function describeTarget(options) {
528
1130
  return options.url?.trim() || options.command?.trim() || "__cli__";
@@ -613,18 +1215,767 @@ function resolveTransportOption(value) {
613
1215
  return value;
614
1216
  }
615
1217
  throw usageError(
616
- `Invalid transport "${value}". Use "http" or "stdio".`
1218
+ `Invalid transport "${value}". Use "http" or "stdio".`
1219
+ );
1220
+ }
1221
+ function resolveHttpAccessToken(options) {
1222
+ const accessToken = normalizeOptionalAuthValue(options.accessToken);
1223
+ const oauthAccessToken = normalizeOptionalAuthValue(options.oauthAccessToken);
1224
+ if (accessToken && oauthAccessToken && accessToken !== oauthAccessToken) {
1225
+ throw usageError(
1226
+ "--access-token and --oauth-access-token must match when both are provided."
1227
+ );
1228
+ }
1229
+ return accessToken ?? oauthAccessToken;
1230
+ }
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)
1258
+ );
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));
1273
+ }
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."
1279
+ );
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)
1301
+ });
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)}`
1337
+ );
1338
+ }
1339
+ async getInitInfo(serverId) {
1340
+ return this.request(
1341
+ `/api/mcp/servers/init-info/${encodeURIComponent(serverId)}`
1342
+ );
1343
+ }
1344
+ async listTools(serverId, options = {}) {
1345
+ return this.request("/api/mcp/tools/list", {
1346
+ method: "POST",
1347
+ body: { serverId, ...options }
1348
+ });
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".`
617
1953
  );
618
1954
  }
619
- function resolveHttpAccessToken(options) {
620
- const accessToken = options.accessToken?.trim();
621
- const oauthAccessToken = options.oauthAccessToken?.trim();
622
- if (accessToken && oauthAccessToken && accessToken !== oauthAccessToken) {
623
- throw usageError(
624
- "--access-token and --oauth-access-token must match when both are provided."
625
- );
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
+ }
626
1974
  }
627
- return accessToken ?? oauthAccessToken;
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";
628
1979
  }
629
1980
 
630
1981
  // src/commands/apps.ts
@@ -641,6 +1992,23 @@ var APPS_CHECK_IDS_BY_CATEGORY = {
641
1992
  "ui-resource-meta-valid"
642
1993
  ]
643
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
+ }
644
2012
  function registerAppsCommands(program) {
645
2013
  const apps = program.command("apps").description(
646
2014
  "MCP Apps utilities, widget extraction, and conformance checks"
@@ -656,9 +2024,13 @@ function registerAppsCommands(program) {
656
2024
  "Specific check ID to run. Repeat for multiple. Default: all.",
657
2025
  (value, previous = []) => [...previous, value],
658
2026
  []
2027
+ ).option(
2028
+ "--reporter <reporter>",
2029
+ "Structured reporter output: json-summary or junit-xml"
659
2030
  )
660
2031
  ).action(async (options, command) => {
661
- const globalOptions = getGlobalOptions(command);
2032
+ const reporter = parseReporterFormat(options.reporter);
2033
+ const globalOptions = getConformanceGlobals(command, reporter);
662
2034
  const target = describeTarget(options);
663
2035
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
664
2036
  const config = {
@@ -668,39 +2040,73 @@ function registerAppsCommands(program) {
668
2040
  }),
669
2041
  ...collector ? { rpcLogger: collector.rpcLogger } : {}
670
2042
  };
671
- const result = await new sdk.MCPAppsConformanceTest(config).run();
672
- writeResult(
673
- withRpcLogsIfRequested(result, collector, globalOptions),
674
- globalOptions.format
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)
675
2080
  );
676
2081
  if (!result.passed) {
677
2082
  setProcessExitCode(1);
678
2083
  }
679
2084
  });
2085
+ registerAppsDebugCommand(apps);
680
2086
  addRetryOptions(
681
2087
  addSharedServerOptions(
682
- apps.command("mcp-widget").description("Fetch hosted-style MCP App widget content").option("--resource-uri <uri>", "Widget resource URI").option("--uri <uri>", "Alias for --resource-uri").requiredOption(
2088
+ apps.command("mcp-widget").description("Fetch hosted-style MCP App widget content").requiredOption("--resource-uri <uri>", "Widget resource URI").requiredOption(
683
2089
  "--tool-id <id>",
684
2090
  "Tool call id used for runtime injection"
685
2091
  ).requiredOption(
686
2092
  "--tool-name <name>",
687
2093
  "Tool name used for runtime injection"
688
- ).option("--tool-input <json>", "Tool input payload as JSON").option("--tool-output <json>", "Tool output payload as JSON").option("--theme <theme>", "Widget theme: light or dark").option("--csp-mode <mode>", "CSP mode: permissive or widget-declared").option("--template <uri>", "Optional ui:// template override").option("--view-mode <mode>", "Widget view mode").option("--view-params <json>", "Widget view params as JSON")
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
+ )
689
2104
  )
690
2105
  ).action(async (options, command) => {
691
2106
  const globalOptions = getGlobalOptions(command);
692
2107
  const retryPolicy = parseRetryPolicy(options);
693
2108
  const target = describeTarget(options);
694
2109
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
695
- const resourceUri = resolveAliasedStringOption(
696
- options,
697
- [
698
- { key: "resourceUri", flag: "--resource-uri" },
699
- { key: "uri", flag: "--uri" }
700
- ],
701
- "Widget resource URI",
702
- { required: true }
703
- );
704
2110
  const config = parseServerConfig({
705
2111
  ...options,
706
2112
  timeout: globalOptions.timeout
@@ -708,11 +2114,11 @@ function registerAppsCommands(program) {
708
2114
  const result = await withEphemeralManager(
709
2115
  config,
710
2116
  (manager, serverId) => buildMcpWidgetContent(manager, serverId, {
711
- resourceUri,
2117
+ resourceUri: options.resourceUri,
712
2118
  toolId: options.toolId,
713
2119
  toolName: options.toolName,
714
2120
  toolInput: parseJsonRecord(options.toolInput, "Tool input") ?? {},
715
- toolOutput: parseJsonValue(options.toolOutput),
2121
+ toolOutput: parseJsonInputValue(options.toolOutput, "Tool output"),
716
2122
  theme: parseTheme(options.theme),
717
2123
  cspMode: parseCspMode(options.cspMode),
718
2124
  template: options.template,
@@ -732,15 +2138,21 @@ function registerAppsCommands(program) {
732
2138
  });
733
2139
  addRetryOptions(
734
2140
  addSharedServerOptions(
735
- apps.command("chatgpt-widget").description("Fetch hosted-style ChatGPT App widget content").option("--resource-uri <uri>", "Widget resource URI").option("--uri <uri>", "Alias for --resource-uri").requiredOption(
2141
+ apps.command("chatgpt-widget").description("Fetch hosted-style ChatGPT App widget content").requiredOption("--resource-uri <uri>", "Widget resource URI").requiredOption(
736
2142
  "--tool-id <id>",
737
2143
  "Tool call id used for runtime injection"
738
2144
  ).requiredOption(
739
2145
  "--tool-name <name>",
740
2146
  "Tool name used for runtime injection"
741
- ).option("--tool-input <json>", "Tool input payload as JSON").option("--tool-output <json>", "Tool output payload as JSON").option(
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(
742
2154
  "--tool-response-metadata <json>",
743
- "Tool response metadata as a JSON object"
2155
+ "Tool response metadata as JSON, @path, or - for stdin"
744
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(
745
2157
  "--device-type <type>",
746
2158
  "Device type: mobile, tablet, or desktop"
@@ -751,15 +2163,6 @@ function registerAppsCommands(program) {
751
2163
  const retryPolicy = parseRetryPolicy(options);
752
2164
  const target = describeTarget(options);
753
2165
  const collector = globalOptions.rpc ? createCliRpcLogCollector({ __cli__: target }) : void 0;
754
- const resourceUri = resolveAliasedStringOption(
755
- options,
756
- [
757
- { key: "resourceUri", flag: "--resource-uri" },
758
- { key: "uri", flag: "--uri" }
759
- ],
760
- "Widget resource URI",
761
- { required: true }
762
- );
763
2166
  const config = parseServerConfig({
764
2167
  ...options,
765
2168
  timeout: globalOptions.timeout
@@ -767,11 +2170,11 @@ function registerAppsCommands(program) {
767
2170
  const result = await withEphemeralManager(
768
2171
  config,
769
2172
  (manager, serverId) => buildChatGptWidgetContent(manager, serverId, {
770
- uri: resourceUri,
2173
+ uri: options.resourceUri,
771
2174
  toolId: options.toolId,
772
2175
  toolName: options.toolName,
773
2176
  toolInput: parseJsonRecord(options.toolInput, "Tool input") ?? {},
774
- toolOutput: parseJsonValue(options.toolOutput),
2177
+ toolOutput: parseJsonInputValue(options.toolOutput, "Tool output"),
775
2178
  toolResponseMetadata: parseJsonRecord(
776
2179
  options.toolResponseMetadata,
777
2180
  "Tool response metadata"
@@ -793,27 +2196,6 @@ function registerAppsCommands(program) {
793
2196
  );
794
2197
  });
795
2198
  }
796
- function parseJsonValue(value) {
797
- if (value === void 0) {
798
- return void 0;
799
- }
800
- try {
801
- return JSON.parse(value);
802
- } catch (error) {
803
- throw usageError("Value must be valid JSON.", {
804
- source: error instanceof Error ? error.message : String(error)
805
- });
806
- }
807
- }
808
- function parseTheme(value) {
809
- if (value === void 0) {
810
- return void 0;
811
- }
812
- if (value === "light" || value === "dark") {
813
- return value;
814
- }
815
- throw usageError(`Invalid theme "${value}". Use "light" or "dark".`);
816
- }
817
2199
  function parseCspMode(value) {
818
2200
  if (value === void 0) {
819
2201
  return void 0;
@@ -844,7 +2226,7 @@ function buildAppsConformanceConfig(options) {
844
2226
  const categories = options.category?.filter(Boolean);
845
2227
  const invalidCategories = collectInvalidEntries(
846
2228
  categories,
847
- sdk.MCP_APPS_CHECK_CATEGORIES
2229
+ MCP_APPS_CHECK_CATEGORIES
848
2230
  );
849
2231
  if (invalidCategories.length > 0) {
850
2232
  throw usageError(
@@ -852,7 +2234,7 @@ function buildAppsConformanceConfig(options) {
852
2234
  );
853
2235
  }
854
2236
  const checkIds = options.checkId?.filter(Boolean);
855
- const invalidCheckIds = collectInvalidEntries(checkIds, sdk.MCP_APPS_CHECK_IDS);
2237
+ const invalidCheckIds = collectInvalidEntries(checkIds, MCP_APPS_CHECK_IDS);
856
2238
  if (invalidCheckIds.length > 0) {
857
2239
  throw usageError(
858
2240
  `Unknown check id${invalidCheckIds.length === 1 ? "" : "s"}: ${invalidCheckIds.join(", ")}`
@@ -873,6 +2255,9 @@ function buildAppsConformanceConfig(options) {
873
2255
  function registerProtocolCommands(program) {
874
2256
  const protocol = program.command("protocol").description("MCP protocol inspection and conformance checks");
875
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(
876
2261
  "--header <header>",
877
2262
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
878
2263
  (value, previous = []) => [...previous, value],
@@ -892,19 +2277,46 @@ function registerProtocolCommands(program) {
892
2277
  "Specific check ID to run. Repeat for multiple. Default: all.",
893
2278
  (value, previous = []) => [...previous, value],
894
2279
  []
2280
+ ).option(
2281
+ "--reporter <reporter>",
2282
+ "Structured reporter output: json-summary or junit-xml"
895
2283
  ).action(async (options, command) => {
896
- const format = getFormat(command);
2284
+ const reporter = parseReporterFormat(options.reporter);
2285
+ const format = getFormat(command, reporter);
897
2286
  const config = buildConfig(options);
898
- const result = await new sdk.MCPConformanceTest(config).run();
899
- 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));
900
2304
  if (!result.passed) {
901
2305
  setProcessExitCode(1);
902
2306
  }
903
2307
  });
904
2308
  }
905
- function getFormat(command) {
2309
+ function getFormat(command, reporter) {
906
2310
  const opts = command.optsWithGlobals();
907
- 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
+ `);
908
2320
  }
909
2321
  function collectInvalidEntries2(values, allowedValues) {
910
2322
  return (values ?? []).filter((value) => !allowedValues.includes(value));
@@ -921,10 +2333,12 @@ function buildConfig(options) {
921
2333
  throw usageError(`Invalid URL scheme: ${serverUrl}`);
922
2334
  }
923
2335
  const customHeaders = parseHeadersOption(options.header);
2336
+ assertNoCredentialsFileAuthConflicts(options);
2337
+ const accessToken = options.credentialsFile ? resolveCredentialsFileAccessToken(options.credentialsFile, serverUrl) : options.accessToken;
924
2338
  const categories = options.category?.filter(Boolean);
925
2339
  const invalidCategories = collectInvalidEntries2(
926
2340
  categories,
927
- sdk.MCP_CHECK_CATEGORIES
2341
+ MCP_CHECK_CATEGORIES
928
2342
  );
929
2343
  if (invalidCategories.length > 0) {
930
2344
  throw usageError(
@@ -932,7 +2346,7 @@ function buildConfig(options) {
932
2346
  );
933
2347
  }
934
2348
  const checkIds = options.checkId?.filter(Boolean);
935
- const invalidCheckIds = collectInvalidEntries2(checkIds, sdk.MCP_CHECK_IDS);
2349
+ const invalidCheckIds = collectInvalidEntries2(checkIds, MCP_CHECK_IDS);
936
2350
  if (invalidCheckIds.length > 0) {
937
2351
  throw usageError(
938
2352
  `Unknown check id${invalidCheckIds.length === 1 ? "" : "s"}: ${invalidCheckIds.join(", ")}`
@@ -940,183 +2354,19 @@ function buildConfig(options) {
940
2354
  }
941
2355
  return {
942
2356
  serverUrl,
943
- accessToken: options.accessToken,
2357
+ accessToken,
944
2358
  customHeaders,
945
2359
  checkTimeout: options.checkTimeout ?? 15e3,
946
2360
  ...categories && categories.length > 0 ? { categories } : {},
947
2361
  ...checkIds && checkIds.length > 0 ? { checkIds } : {}
948
2362
  };
949
2363
  }
950
-
951
- // src/lib/oauth-enums.ts
952
- var VALID_PROTOCOL_VERSIONS = /* @__PURE__ */ new Set([
953
- "2025-03-26",
954
- "2025-06-18",
955
- "2025-11-25"
956
- ]);
957
- var VALID_REGISTRATION_STRATEGIES = /* @__PURE__ */ new Set([
958
- "cimd",
959
- "dcr",
960
- "preregistered"
961
- ]);
962
- var VALID_AUTH_MODES = /* @__PURE__ */ new Set([
963
- "headless",
964
- "interactive",
965
- "client_credentials"
966
- ]);
967
- function assertValidUrl(value, label) {
968
- if (typeof value !== "string" || !value.trim()) {
969
- throw usageError(`${label} is required and must be a non-empty string`);
970
- }
971
- try {
972
- new URL(value);
973
- } catch {
974
- throw usageError(`Invalid ${label}: ${value}`);
975
- }
976
- }
977
- function assertEnum(value, allowed, label) {
978
- if (typeof value !== "string" || !allowed.has(value)) {
979
- throw usageError(
980
- `Invalid ${label} "${String(value)}". Allowed: ${[...allowed].join(", ")}`
981
- );
982
- }
983
- }
984
- function validateFlow(flow, defaults, index) {
985
- const protocolVersion = flow.protocolVersion ?? defaults?.protocolVersion;
986
- if (!protocolVersion) {
987
- throw usageError(
988
- `flows[${index}]: protocolVersion is required (not set in flow or defaults)`
989
- );
990
- }
991
- assertEnum(protocolVersion, VALID_PROTOCOL_VERSIONS, `flows[${index}].protocolVersion`);
992
- const registrationStrategy = flow.registrationStrategy ?? defaults?.registrationStrategy;
993
- if (!registrationStrategy) {
994
- throw usageError(
995
- `flows[${index}]: registrationStrategy is required (not set in flow or defaults)`
996
- );
997
- }
998
- assertEnum(
999
- registrationStrategy,
1000
- VALID_REGISTRATION_STRATEGIES,
1001
- `flows[${index}].registrationStrategy`
1002
- );
1003
- const auth = flow.auth ?? defaults?.auth;
1004
- if (auth?.mode) {
1005
- assertEnum(auth.mode, VALID_AUTH_MODES, `flows[${index}].auth.mode`);
1006
- }
1007
- }
1008
- function loadSuiteConfig(filePath) {
1009
- let raw;
1010
- try {
1011
- raw = fs.readFileSync(filePath, "utf-8");
1012
- } catch (error) {
1013
- throw usageError(
1014
- `Cannot read config file "${filePath}": ${error instanceof Error ? error.message : String(error)}`
1015
- );
1016
- }
1017
- let config;
1018
- try {
1019
- config = JSON.parse(raw);
1020
- } catch {
1021
- throw usageError(`Config file "${filePath}" is not valid JSON`);
1022
- }
1023
- if (typeof config !== "object" || config === null || Array.isArray(config)) {
1024
- throw usageError("Config file must be a JSON object");
1025
- }
1026
- assertValidUrl(config.serverUrl, "serverUrl");
1027
- const flows = config.flows;
1028
- if (!Array.isArray(flows) || flows.length === 0) {
1029
- throw usageError('Config file must have a non-empty "flows" array');
1030
- }
1031
- const defaults = config.defaults;
1032
- for (let i = 0; i < flows.length; i++) {
1033
- const flow = flows[i];
1034
- if (typeof flow !== "object" || flow === null || Array.isArray(flow)) {
1035
- throw usageError(`flows[${i}] must be an object`);
1036
- }
1037
- validateFlow(flow, defaults, i);
1038
- }
1039
- return config;
1040
- }
1041
-
1042
- // src/lib/junit-xml.ts
1043
- function escapeXml(value) {
1044
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1045
- }
1046
- function stepToTestCase(step, classname) {
1047
- const name = escapeXml(step.title || step.step);
1048
- const time = (step.durationMs / 1e3).toFixed(3);
1049
- const cls = escapeXml(classname);
1050
- if (step.status === "skipped") {
1051
- return ` <testcase name="${name}" classname="${cls}" time="${time}">
1052
- <skipped/>
1053
- </testcase>`;
1054
- }
1055
- if (step.status === "failed") {
1056
- const message = escapeXml(step.error?.message ?? "Unknown failure");
1057
- const details = step.httpAttempts.map((attempt) => {
1058
- const req = `${attempt.request.method} ${attempt.request.url}`;
1059
- const res = attempt.response ? `${attempt.response.status} ${attempt.response.statusText}` : "No response";
1060
- return `${req} \u2192 ${res}`;
1061
- }).join("\n");
1062
- const body = details ? escapeXml(details) : "";
1063
- return ` <testcase name="${name}" classname="${cls}" time="${time}">
1064
- <failure message="${message}">${body}</failure>
1065
- </testcase>`;
1066
- }
1067
- return ` <testcase name="${name}" classname="${cls}" time="${time}"/>`;
1068
- }
1069
- function flowToTestSuite(result) {
1070
- const name = escapeXml(result.label);
1071
- const tests = result.steps.length;
1072
- const failures = result.steps.filter((s) => s.status === "failed").length;
1073
- const skipped = result.steps.filter((s) => s.status === "skipped").length;
1074
- const time = (result.durationMs / 1e3).toFixed(3);
1075
- const classname = result.serverUrl;
1076
- const cases = result.steps.map((step) => stepToTestCase(step, classname)).join("\n");
1077
- return ` <testsuite name="${name}" tests="${tests}" failures="${failures}" skipped="${skipped}" time="${time}">
1078
- ${cases}
1079
- </testsuite>`;
1080
- }
1081
- function suiteResultToJUnitXml(result) {
1082
- const name = escapeXml(result.name);
1083
- const tests = result.results.reduce((sum, r) => sum + r.steps.length, 0);
1084
- const failures = result.results.reduce(
1085
- (sum, r) => sum + r.steps.filter((s) => s.status === "failed").length,
1086
- 0
1087
- );
1088
- const time = (result.durationMs / 1e3).toFixed(3);
1089
- const suites = result.results.map(flowToTestSuite).join("\n");
1090
- return `<?xml version="1.0" encoding="UTF-8"?>
1091
- <testsuites name="${name}" tests="${tests}" failures="${failures}" time="${time}">
1092
- ${suites}
1093
- </testsuites>
1094
- `;
1095
- }
1096
- function singleResultToJUnitXml(result, label) {
1097
- const suiteResult = {
1098
- name: "OAuth Conformance",
1099
- serverUrl: result.serverUrl,
1100
- passed: result.passed,
1101
- results: [
1102
- {
1103
- ...result,
1104
- label: `${result.protocolVersion}/${result.registrationStrategy}`
1105
- }
1106
- ],
1107
- summary: result.summary,
1108
- durationMs: result.durationMs
1109
- };
1110
- return suiteResultToJUnitXml(suiteResult);
1111
- }
1112
-
1113
- // src/lib/oauth-output.ts
1114
2364
  function parseOAuthOutputFormat(value) {
1115
- if (value === "json" || value === "human" || value === "junit-xml") {
2365
+ if (value === "json" || value === "human") {
1116
2366
  return value;
1117
2367
  }
1118
2368
  throw usageError(
1119
- `Invalid output format "${value}". Use "json", "human", or "junit-xml".`
2369
+ `Invalid output format "${value}". Use "json" or "human".`
1120
2370
  );
1121
2371
  }
1122
2372
  function resolveOAuthOutputFormat(value, isTTY) {
@@ -1125,9 +2375,7 @@ function resolveOAuthOutputFormat(value, isTTY) {
1125
2375
  function renderOAuthConformanceResult(result, format) {
1126
2376
  switch (format) {
1127
2377
  case "human":
1128
- return sdk.formatOAuthConformanceHuman(result);
1129
- case "junit-xml":
1130
- return singleResultToJUnitXml(result);
2378
+ return formatOAuthConformanceHuman(result);
1131
2379
  case "json":
1132
2380
  return JSON.stringify(result);
1133
2381
  }
@@ -1135,9 +2383,7 @@ function renderOAuthConformanceResult(result, format) {
1135
2383
  function renderOAuthConformanceSuiteResult(result, format) {
1136
2384
  switch (format) {
1137
2385
  case "human":
1138
- return sdk.formatOAuthConformanceSuiteHuman(result);
1139
- case "junit-xml":
1140
- return suiteResultToJUnitXml(result);
2386
+ return formatOAuthConformanceSuiteHuman(result);
1141
2387
  case "json":
1142
2388
  return JSON.stringify(result);
1143
2389
  }
@@ -1160,7 +2406,7 @@ async function writeCommandDebugArtifact(options, dependencies = {}) {
1160
2406
  ]
1161
2407
  });
1162
2408
  const artifactPath = await writeDebugArtifact(options.outputPath, payload);
1163
- if (options.format === "human") {
2409
+ if (options.format === "human" && !options.quiet) {
1164
2410
  process.stderr.write(`Debug artifact: ${artifactPath}
1165
2411
  `);
1166
2412
  }
@@ -1185,7 +2431,7 @@ function buildDebugArtifactEnvelope(options) {
1185
2431
  if (rpcLogs.length > 0) {
1186
2432
  payload._rpcLogs = rpcLogs;
1187
2433
  }
1188
- return sdk.redactSensitiveValue(payload);
2434
+ return redactSensitiveValue(payload);
1189
2435
  }
1190
2436
  function buildCommandArtifactError(code, message, details) {
1191
2437
  return {
@@ -1195,11 +2441,11 @@ function buildCommandArtifactError(code, message, details) {
1195
2441
  };
1196
2442
  }
1197
2443
  async function writeDebugArtifact(outputPath, payload) {
1198
- const resolvedPath = path__default.default.resolve(process.cwd(), outputPath);
1199
- const redactedPayload = sdk.redactSensitiveValue(payload);
2444
+ const resolvedPath = path2.resolve(process.cwd(), outputPath);
2445
+ const redactedPayload = redactSensitiveValue(payload);
1200
2446
  try {
1201
- await promises.mkdir(path__default.default.dirname(resolvedPath), { recursive: true });
1202
- await promises.writeFile(
2447
+ await mkdir(path2.dirname(resolvedPath), { recursive: true });
2448
+ await writeFile(
1203
2449
  resolvedPath,
1204
2450
  `${JSON.stringify(redactedPayload, null, 2)}
1205
2451
  `,
@@ -1217,7 +2463,7 @@ async function writeDebugArtifact(outputPath, payload) {
1217
2463
  }
1218
2464
  async function collectDoctorSnapshot(options, dependencies = {}) {
1219
2465
  try {
1220
- const runDoctor = dependencies.runDoctor ?? sdk.runServerDoctor;
2466
+ const runDoctor = dependencies.runDoctor ?? runServerDoctor;
1221
2467
  return {
1222
2468
  snapshot: await runDoctor({
1223
2469
  ...options.input,
@@ -1343,27 +2589,55 @@ function getOAuthFormat(command) {
1343
2589
  const opts = command.optsWithGlobals();
1344
2590
  return resolveOAuthOutputFormat(opts.format, process.stdout.isTTY);
1345
2591
  }
1346
- function getStructuredOAuthFormat(command) {
1347
- const format = getOAuthFormat(command);
1348
- if (format === "junit-xml") {
1349
- throw usageError(
1350
- 'The oauth metadata/proxy commands only support --format "json" or "human".'
1351
- );
1352
- }
1353
- return format;
2592
+ function getOAuthConformanceFormat(command, reporter) {
2593
+ const opts = command.optsWithGlobals();
2594
+ return resolveConformanceOutputFormatForCli(
2595
+ opts.format,
2596
+ process.stdout.isTTY,
2597
+ reporter
2598
+ );
1354
2599
  }
1355
2600
  function writeOAuthOutput(output) {
1356
2601
  process.stdout.write(output.endsWith("\n") ? output : `${output}
1357
2602
  `);
1358
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
+ }
1359
2633
  function registerOAuthCommands(program) {
1360
2634
  const oauth = program.command("oauth").description("Run MCP OAuth login, proxy, and conformance flows");
1361
- oauth.command("login").description("Run an OAuth login flow against an HTTP MCP server").requiredOption("--url <url>", "MCP server URL").requiredOption(
2635
+ oauth.command("login").description("Run an OAuth login flow against an HTTP MCP server").requiredOption("--url <url>", "MCP server URL").option(
1362
2636
  "--protocol-version <version>",
1363
- "OAuth protocol version: 2025-03-26, 2025-06-18, or 2025-11-25"
1364
- ).requiredOption(
2637
+ "OAuth protocol override: 2025-03-26, 2025-06-18, or 2025-11-25"
2638
+ ).option(
1365
2639
  "--registration <strategy>",
1366
- "Registration strategy: dcr, preregistered, or cimd"
2640
+ "Registration override: dcr, preregistered, or cimd"
1367
2641
  ).option(
1368
2642
  "--auth-mode <mode>",
1369
2643
  "Authorization mode: headless, interactive, or client_credentials",
@@ -1390,16 +2664,20 @@ function registerOAuthCommands(program) {
1390
2664
  ).option(
1391
2665
  "--debug-out <path>",
1392
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]"
1393
2670
  ).action(async (options, command) => {
1394
- const format = getStructuredOAuthFormat(command);
1395
- const config = buildOAuthConformanceConfig(
2671
+ const globalOptions = getGlobalOptions(command);
2672
+ const format = getOAuthFormat(command);
2673
+ const config = buildOAuthLoginConfig(
1396
2674
  options,
1397
2675
  {
1398
2676
  defaultAuthMode: "interactive"
1399
2677
  }
1400
2678
  );
1401
2679
  const snapshotCollector = options.debugOut ? createCliRpcLogCollector({ __cli__: config.serverUrl }) : void 0;
1402
- const isTTY = process.stderr.isTTY;
2680
+ const isTTY = process.stderr.isTTY && !globalOptions.quiet;
1403
2681
  if (isTTY) {
1404
2682
  config.onProgress = (message) => {
1405
2683
  process.stderr.write(`\r\x1B[K${message}`);
@@ -1408,7 +2686,7 @@ function registerOAuthCommands(program) {
1408
2686
  let result;
1409
2687
  let commandError;
1410
2688
  try {
1411
- result = await sdk.runOAuthLogin(config);
2689
+ result = await runOAuthLogin(config);
1412
2690
  } catch (error) {
1413
2691
  commandError = error;
1414
2692
  } finally {
@@ -1421,28 +2699,32 @@ function registerOAuthCommands(program) {
1421
2699
  config.serverUrl,
1422
2700
  snapshotConfig
1423
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
+ }
1424
2714
  await writeCommandDebugArtifact({
1425
2715
  outputPath: options.debugOut,
1426
2716
  format,
2717
+ quiet: globalOptions.quiet,
1427
2718
  commandName: "oauth login",
1428
2719
  commandInput: summarizeOAuthLoginCommandInput(
1429
2720
  options
1430
2721
  ),
1431
2722
  target,
1432
- outcome: commandError ? {
1433
- status: "error",
1434
- error: commandError
1435
- } : result?.completed ? {
1436
- status: "success",
1437
- result
1438
- } : {
1439
- status: "error",
2723
+ outcome: buildOAuthLoginDebugOutcome({
2724
+ commandError,
1440
2725
  result,
1441
- error: buildCommandArtifactError(
1442
- "OAUTH_LOGIN_INCOMPLETE",
1443
- result?.error?.message ?? "OAuth login did not complete."
1444
- )
1445
- },
2726
+ credentialsFileError
2727
+ }),
1446
2728
  snapshot: options.debugOut ? {
1447
2729
  input: {
1448
2730
  config: snapshotConfig,
@@ -1458,7 +2740,17 @@ function registerOAuthCommands(program) {
1458
2740
  if (!result) {
1459
2741
  throw cliError("INTERNAL_ERROR", "OAuth login did not return a result.");
1460
2742
  }
1461
- 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
+ }
1462
2754
  if (!result.completed) {
1463
2755
  setProcessExitCode(1);
1464
2756
  }
@@ -1498,11 +2790,17 @@ function registerOAuthCommands(program) {
1498
2790
  ).option(
1499
2791
  "--print-url",
1500
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"
1501
2796
  ).action(async (options, command) => {
1502
- const format = getOAuthFormat(command);
2797
+ const reporter = parseReporterFormat(options.reporter);
2798
+ const format = getOAuthConformanceFormat(command, reporter);
1503
2799
  const config = buildOAuthConformanceConfig(options);
1504
- const result = await new sdk.OAuthConformanceTest(config).run();
1505
- writeOAuthOutput(renderOAuthConformanceResult(result, format));
2800
+ const result = await new OAuthConformanceTest(config).run();
2801
+ writeOAuthOutput(
2802
+ reporter ? renderConformanceReporterResult(result, reporter) : renderOAuthConformanceResult(result, format)
2803
+ );
1506
2804
  if (!result.passed) {
1507
2805
  setProcessExitCode(1);
1508
2806
  }
@@ -1515,9 +2813,13 @@ function registerOAuthCommands(program) {
1515
2813
  ).option(
1516
2814
  "--verify-call-tool <name>",
1517
2815
  "Also call the named tool after listing"
2816
+ ).option(
2817
+ "--reporter <reporter>",
2818
+ "Structured reporter output: json-summary or junit-xml"
1518
2819
  ).action(async (options, command) => {
1519
- const format = getOAuthFormat(command);
1520
- const config = loadSuiteConfig(options.config);
2820
+ const reporter = parseReporterFormat(options.reporter);
2821
+ const format = getOAuthConformanceFormat(command, reporter);
2822
+ const config = loadOAuthSuiteConfig(options.config);
1521
2823
  if (options.verifyTools || options.verifyCallTool) {
1522
2824
  const cliVerification = {
1523
2825
  listTools: true,
@@ -1531,43 +2833,56 @@ function registerOAuthCommands(program) {
1531
2833
  verification: { ...config.defaults?.verification, ...cliVerification }
1532
2834
  };
1533
2835
  }
1534
- const suite = new sdk.OAuthConformanceSuite(config);
2836
+ const suite = new OAuthConformanceSuite(config);
1535
2837
  const result = await suite.run();
1536
- writeOAuthOutput(renderOAuthConformanceSuiteResult(result, format));
2838
+ writeOAuthOutput(
2839
+ reporter ? renderConformanceReporterResult(result, reporter) : renderOAuthConformanceSuiteResult(result, format)
2840
+ );
1537
2841
  if (!result.passed) {
1538
2842
  setProcessExitCode(1);
1539
2843
  }
1540
2844
  });
1541
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);
1542
2847
  const result = await runOAuthMetadata(options.url);
1543
- writeResult(result, getStructuredOAuthFormat(command));
2848
+ writeResult(result, format);
1544
2849
  });
1545
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(
1546
2851
  "--header <header>",
1547
2852
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
1548
2853
  (value, previous = []) => [...previous, value],
1549
2854
  []
1550
- ).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);
1551
2860
  const result = await runOAuthProxy(options);
1552
- writeResult(result, getStructuredOAuthFormat(command));
2861
+ writeResult(result, format);
1553
2862
  });
1554
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(
1555
2864
  "--header <header>",
1556
2865
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
1557
2866
  (value, previous = []) => [...previous, value],
1558
2867
  []
1559
- ).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);
1560
2873
  const result = await runOAuthDebugProxy(
1561
2874
  options
1562
2875
  );
1563
- writeResult(result, getStructuredOAuthFormat(command));
2876
+ writeResult(result, format);
1564
2877
  });
1565
2878
  }
1566
2879
  function buildOAuthConformanceConfig(options, defaults) {
1567
2880
  const serverUrl = options.url.trim();
1568
2881
  assertValidUrl2(serverUrl, "server URL");
1569
- const protocolVersion = parseProtocolVersion(options.protocolVersion);
1570
- const registrationStrategy = parseRegistrationStrategy(options.registration);
2882
+ const protocolVersion = parseRequiredProtocolVersion(options.protocolVersion);
2883
+ const registrationStrategy = parseRequiredRegistrationStrategy(
2884
+ options.registration
2885
+ );
1571
2886
  const authMode = parseAuthMode(
1572
2887
  options.authMode ?? defaults?.defaultAuthMode ?? "interactive"
1573
2888
  );
@@ -1642,9 +2957,97 @@ function buildOAuthConformanceConfig(options, defaults) {
1642
2957
  oauthConformanceChecks: options.conformanceChecks ?? false
1643
2958
  };
1644
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
+ }
1645
3046
  function summarizeOAuthLoginCommandInput(options) {
1646
3047
  return {
1647
3048
  serverUrl: options.url.trim(),
3049
+ protocolMode: options.protocolVersion ?? "auto",
3050
+ registrationMode: options.registration ?? "auto",
1648
3051
  protocolVersion: options.protocolVersion,
1649
3052
  registration: options.registration,
1650
3053
  authMode: options.authMode ?? "interactive",
@@ -1717,6 +3120,14 @@ function parseProtocolVersion(value) {
1717
3120
  `Invalid protocol version "${value}". Use ${[...VALID_PROTOCOL_VERSIONS].join(", ")}.`
1718
3121
  );
1719
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
+ }
1720
3131
  function parseRegistrationStrategy(value) {
1721
3132
  if (VALID_REGISTRATION_STRATEGIES.has(value)) {
1722
3133
  return value;
@@ -1725,6 +3136,14 @@ function parseRegistrationStrategy(value) {
1725
3136
  `Invalid registration strategy "${value}". Use ${[...VALID_REGISTRATION_STRATEGIES].join(", ")}.`
1726
3137
  );
1727
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
+ }
1728
3147
  function parseAuthMode(value) {
1729
3148
  if (VALID_AUTH_MODES.has(value)) {
1730
3149
  return value;
@@ -1735,7 +3154,7 @@ function parseAuthMode(value) {
1735
3154
  }
1736
3155
  async function runOAuthMetadata(url) {
1737
3156
  try {
1738
- const result = await sdk.fetchOAuthMetadata(url, true);
3157
+ const result = await fetchOAuthMetadata(url, true);
1739
3158
  if ("status" in result && result.status !== void 0) {
1740
3159
  throw cliError(
1741
3160
  statusToErrorCode(result.status),
@@ -1749,7 +3168,7 @@ async function runOAuthMetadata(url) {
1749
3168
  }
1750
3169
  async function runOAuthProxy(options) {
1751
3170
  try {
1752
- return await sdk.executeOAuthProxy({
3171
+ return await executeOAuthProxy({
1753
3172
  url: options.url,
1754
3173
  method: options.method,
1755
3174
  headers: parseHeadersOption(options.header),
@@ -1762,7 +3181,7 @@ async function runOAuthProxy(options) {
1762
3181
  }
1763
3182
  async function runOAuthDebugProxy(options) {
1764
3183
  try {
1765
- return await sdk.executeDebugOAuthProxy({
3184
+ return await executeDebugOAuthProxy({
1766
3185
  url: options.url,
1767
3186
  method: options.method,
1768
3187
  headers: parseHeadersOption(options.header),
@@ -1777,14 +3196,15 @@ function parseProxyBody(value) {
1777
3196
  if (value === void 0) {
1778
3197
  return void 0;
1779
3198
  }
3199
+ const source = readInputSource(value, "Request body");
1780
3200
  try {
1781
- return JSON.parse(value);
3201
+ return JSON.parse(source);
1782
3202
  } catch {
1783
- return value;
3203
+ return source;
1784
3204
  }
1785
3205
  }
1786
3206
  function mapOAuthProxyError(error) {
1787
- if (error instanceof sdk.OAuthProxyError) {
3207
+ if (error instanceof OAuthProxyError) {
1788
3208
  return cliError(statusToErrorCode(error.status), error.message);
1789
3209
  }
1790
3210
  return error;
@@ -1816,7 +3236,7 @@ function registerPromptCommands(program) {
1816
3236
  });
1817
3237
  const result = await withEphemeralManager(
1818
3238
  config,
1819
- (manager, serverId) => sdk.listPrompts(manager, { serverId, cursor: options.cursor }),
3239
+ (manager, serverId) => listPrompts(manager, { serverId, cursor: options.cursor }),
1820
3240
  {
1821
3241
  timeout: globalOptions.timeout,
1822
3242
  rpcLogger: collector?.rpcLogger,
@@ -1830,7 +3250,10 @@ function registerPromptCommands(program) {
1830
3250
  });
1831
3251
  addRetryOptions(
1832
3252
  addSharedServerOptions(
1833
- prompts.command("get").description("Get a named prompt from an MCP server").option("--prompt-name <prompt>", "Prompt name").option("--name <prompt>", "Alias for --prompt-name").option("--prompt-args <json>", "Prompt arguments as a JSON object")
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
+ )
1834
3257
  )
1835
3258
  ).action(async (options, command) => {
1836
3259
  const globalOptions = getGlobalOptions(command);
@@ -1853,7 +3276,7 @@ function registerPromptCommands(program) {
1853
3276
  const promptArguments = parsePromptArguments(options.promptArgs);
1854
3277
  const result = await withEphemeralManager(
1855
3278
  config,
1856
- (manager, serverId) => sdk.getPrompt(manager, {
3279
+ (manager, serverId) => getPrompt(manager, {
1857
3280
  serverId,
1858
3281
  name: promptName,
1859
3282
  arguments: promptArguments
@@ -1887,7 +3310,7 @@ function registerResourcesCommands(program) {
1887
3310
  });
1888
3311
  const result = await withEphemeralManager(
1889
3312
  config,
1890
- (manager, serverId) => sdk.listResources(manager, { serverId, cursor: options.cursor }),
3313
+ (manager, serverId) => listResources(manager, { serverId, cursor: options.cursor }),
1891
3314
  {
1892
3315
  timeout: globalOptions.timeout,
1893
3316
  rpcLogger: collector?.rpcLogger,
@@ -1923,7 +3346,7 @@ function registerResourcesCommands(program) {
1923
3346
  });
1924
3347
  const result = await withEphemeralManager(
1925
3348
  config,
1926
- (manager, serverId) => sdk.readResource(manager, { serverId, uri: resourceUri }),
3349
+ (manager, serverId) => readResource(manager, { serverId, uri: resourceUri }),
1927
3350
  {
1928
3351
  timeout: globalOptions.timeout,
1929
3352
  rpcLogger: collector?.rpcLogger,
@@ -1966,46 +3389,6 @@ function registerResourcesCommands(program) {
1966
3389
  );
1967
3390
  });
1968
3391
  }
1969
- function parseReporterFormat(value) {
1970
- if (value === void 0) {
1971
- return void 0;
1972
- }
1973
- if (value === "json-summary" || value === "junit-xml") {
1974
- return value;
1975
- }
1976
- throw usageError(
1977
- `Invalid reporter "${value}". Use "json-summary" or "junit-xml".`
1978
- );
1979
- }
1980
- function writeReporterResult(reporter, report) {
1981
- if (reporter === "junit-xml") {
1982
- process.stdout.write(sdk.renderStructuredRunJUnitXml(report));
1983
- return;
1984
- }
1985
- writeResult(sdk.renderStructuredRunJson(report), "json");
1986
- }
1987
- async function writeJsonArtifact(outputPath, payload) {
1988
- const resolvedPath = path__default.default.resolve(process.cwd(), outputPath);
1989
- try {
1990
- await promises.mkdir(path__default.default.dirname(resolvedPath), { recursive: true });
1991
- await promises.writeFile(
1992
- resolvedPath,
1993
- `${JSON.stringify(payload, null, 2)}
1994
- `,
1995
- "utf8"
1996
- );
1997
- } catch (error) {
1998
- throw operationalError(
1999
- `Failed to write JSON artifact to "${resolvedPath}".`,
2000
- {
2001
- source: error instanceof Error ? error.message : String(error)
2002
- }
2003
- );
2004
- }
2005
- return resolvedPath;
2006
- }
2007
-
2008
- // src/commands/server.ts
2009
3392
  function registerServerCommands(program) {
2010
3393
  const server = program.command("server").description("Inspect MCP server connectivity and capabilities");
2011
3394
  addRetryOptions(
@@ -2014,6 +3397,9 @@ function registerServerCommands(program) {
2014
3397
  ).requiredOption("--url <url>", "HTTP MCP server URL").option("--access-token <token>", "Bearer access token for HTTP servers").option(
2015
3398
  "--oauth-access-token <token>",
2016
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"
2017
3403
  ).option(
2018
3404
  "--header <header>",
2019
3405
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
@@ -2021,7 +3407,7 @@ function registerServerCommands(program) {
2021
3407
  []
2022
3408
  ).option(
2023
3409
  "--client-capabilities <json>",
2024
- "Client capabilities advertised in the initialize probe as a JSON object"
3410
+ "Client capabilities as JSON, @path, or - for stdin"
2025
3411
  ).option(
2026
3412
  "--protocol-version <version>",
2027
3413
  "OAuth/MCP protocol version hint used for the initialize probe",
@@ -2038,8 +3424,10 @@ function registerServerCommands(program) {
2038
3424
  const globalOptions = getGlobalOptions(command);
2039
3425
  const retryPolicy = parseRetryPolicy(options);
2040
3426
  const protocolVersion = options.protocolVersion;
3427
+ const accessToken = resolveServerProbeAccessToken(options);
2041
3428
  const config = parseServerConfig({
2042
3429
  ...options,
3430
+ ...options.credentialsFile ? { accessToken, credentialsFile: void 0 } : {},
2043
3431
  timeout: options.timeout ?? globalOptions.timeout
2044
3432
  });
2045
3433
  const target = describeTarget(options);
@@ -2057,11 +3445,11 @@ function registerServerCommands(program) {
2057
3445
  if (!probeUrl) {
2058
3446
  throw usageError("HTTP probe requires --url.");
2059
3447
  }
2060
- result = await sdk.probeMcpServer({
3448
+ result = await probeMcpServer({
2061
3449
  url: probeUrl,
2062
3450
  protocolVersion,
2063
3451
  headers: parseHeadersOption(options.header),
2064
- accessToken: resolveHttpAccessToken(options),
3452
+ accessToken,
2065
3453
  clientCapabilities: "clientCapabilities" in config ? config.clientCapabilities : void 0,
2066
3454
  timeoutMs: options.timeout ?? globalOptions.timeout,
2067
3455
  retryPolicy
@@ -2072,6 +3460,7 @@ function registerServerCommands(program) {
2072
3460
  await writeCommandDebugArtifact({
2073
3461
  outputPath: options.debugOut,
2074
3462
  format: globalOptions.format,
3463
+ quiet: globalOptions.quiet,
2075
3464
  commandName: "server probe",
2076
3465
  commandInput: {
2077
3466
  protocolVersion,
@@ -2126,7 +3515,7 @@ function registerServerCommands(program) {
2126
3515
  timeout: globalOptions.timeout
2127
3516
  });
2128
3517
  const doctorTarget = summarizeServerDoctorTarget(target, config);
2129
- const result = await sdk.runServerDoctor({
3518
+ const result = await runServerDoctor({
2130
3519
  config,
2131
3520
  target: doctorTarget,
2132
3521
  timeout: globalOptions.timeout,
@@ -2223,6 +3612,7 @@ function registerServerCommands(program) {
2223
3612
  await writeCommandDebugArtifact({
2224
3613
  outputPath: options.debugOut,
2225
3614
  format: globalOptions.format,
3615
+ quiet: globalOptions.quiet,
2226
3616
  commandName: "server validate",
2227
3617
  commandInput: {},
2228
3618
  target: targetSummary,
@@ -2330,7 +3720,7 @@ function registerServerCommands(program) {
2330
3720
  ...options,
2331
3721
  timeout: globalOptions.timeout
2332
3722
  });
2333
- const snapshot = await sdk.collectServerSnapshot({
3723
+ const snapshot = await collectServerSnapshot({
2334
3724
  config,
2335
3725
  target,
2336
3726
  timeout: globalOptions.timeout,
@@ -2339,7 +3729,7 @@ function registerServerCommands(program) {
2339
3729
  clientName: "mcpjam",
2340
3730
  serverId: "__cli__"
2341
3731
  });
2342
- const result = options.stable ? sdk.serializeStableServerSnapshot(snapshot) : sdk.serializeServerSnapshot(snapshot, { mode: "raw" });
3732
+ const result = options.stable ? serializeStableServerSnapshot(snapshot) : serializeServerSnapshot(snapshot, { mode: "raw" });
2343
3733
  writeResult(
2344
3734
  options.stable ? result : withRpcLogsIfRequested(result, collector, globalOptions),
2345
3735
  globalOptions.format
@@ -2383,7 +3773,7 @@ function registerServerCommands(program) {
2383
3773
  timeout: globalOptions.timeout
2384
3774
  });
2385
3775
  const baselineSnapshot = await readSnapshotFile(mode.baselinePath);
2386
- const currentSnapshot = await sdk.collectServerSnapshot({
3776
+ const currentSnapshot = await collectServerSnapshot({
2387
3777
  config,
2388
3778
  target,
2389
3779
  timeout: globalOptions.timeout,
@@ -2419,7 +3809,7 @@ function registerServerCommands(program) {
2419
3809
  if (reporter) {
2420
3810
  writeReporterResult(
2421
3811
  reporter,
2422
- sdk.buildServerDiffReport(rawDiff, {
3812
+ buildServerDiffReport(rawDiff, {
2423
3813
  metadata: mode.kind === "baseline-live" ? {
2424
3814
  comparisonMode: mode.kind,
2425
3815
  baselinePath: mode.baselinePath
@@ -2441,6 +3831,17 @@ function registerServerCommands(program) {
2441
3831
  }
2442
3832
  });
2443
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
+ }
2444
3845
  function hasServerTargetOptions(options) {
2445
3846
  return typeof options.url === "string" || typeof options.command === "string";
2446
3847
  }
@@ -2489,7 +3890,7 @@ function parseDiffFailOn(value) {
2489
3890
  async function readSnapshotFile(filePath) {
2490
3891
  let contents;
2491
3892
  try {
2492
- contents = await promises.readFile(filePath, "utf8");
3893
+ contents = await readFile(filePath, "utf8");
2493
3894
  } catch (error) {
2494
3895
  throw operationalError(`Failed to read snapshot file "${filePath}".`, {
2495
3896
  source: error instanceof Error ? error.message : String(error)
@@ -2512,34 +3913,14 @@ function toOptionalString(value) {
2512
3913
  }
2513
3914
  function createServerDiffResult(left, right, failOn) {
2514
3915
  try {
2515
- return sdk.diffServerSnapshots(left, right, { failOn });
3916
+ return diffServerSnapshots(left, right, { failOn });
2516
3917
  } catch (error) {
2517
- if (error instanceof sdk.ServerSnapshotFormatError) {
3918
+ if (error instanceof ServerSnapshotFormatError) {
2518
3919
  throw usageError(error.message);
2519
3920
  }
2520
3921
  throw error;
2521
3922
  }
2522
3923
  }
2523
- async function listToolsWithMetadata(manager, params) {
2524
- const result = await manager.listTools(
2525
- params.serverId,
2526
- params.cursor ? { cursor: params.cursor } : void 0
2527
- );
2528
- const tools = result.tools ?? [];
2529
- const toolsMetadata = manager.getAllToolsMetadata(params.serverId);
2530
- const tokenCount = params.modelId ? estimateTokensFromChars(JSON.stringify(tools)) : void 0;
2531
- return {
2532
- tools,
2533
- nextCursor: result.nextCursor,
2534
- toolsMetadata,
2535
- ...tokenCount === void 0 ? {} : { tokenCount }
2536
- };
2537
- }
2538
- function estimateTokensFromChars(text) {
2539
- return Math.ceil(text.length / 4);
2540
- }
2541
-
2542
- // src/commands/tools.ts
2543
3924
  function registerToolsCommands(program) {
2544
3925
  const tools = program.command("tools").description("List and invoke MCP server tools");
2545
3926
  addRetryOptions(
@@ -2574,7 +3955,10 @@ function registerToolsCommands(program) {
2574
3955
  );
2575
3956
  });
2576
3957
  addSharedServerOptions(
2577
- tools.command("call").description("Call an MCP tool").option("--tool-name <tool>", "Tool name").option("--name <tool>", "Alias for --tool-name").option("--tool-args <json>", "Tool parameter object as JSON").option("--params <json>", "Alias for --tool-args").option(
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(
2578
3962
  "--validate-response",
2579
3963
  "Validate the MCP tool-call envelope returned by the server"
2580
3964
  ).option(
@@ -2643,6 +4027,7 @@ function registerToolsCommands(program) {
2643
4027
  await writeCommandDebugArtifact({
2644
4028
  outputPath: options.debugOut,
2645
4029
  format: globalOptions.format,
4030
+ quiet: globalOptions.quiet,
2646
4031
  commandName: "tools call",
2647
4032
  commandInput: {
2648
4033
  toolName,
@@ -2669,14 +4054,14 @@ function registerToolsCommands(program) {
2669
4054
  if (commandError) {
2670
4055
  throw commandError;
2671
4056
  }
2672
- const validationResult = shouldValidateResponse || shouldExpectSuccess ? sdk.validateToolCallResult(result, {
4057
+ const validationResult = shouldValidateResponse || shouldExpectSuccess ? validateToolCallResult(result, {
2673
4058
  envelope: shouldValidateResponse,
2674
4059
  outcome: shouldExpectSuccess ? { failOnIsError: true } : void 0
2675
4060
  }) : void 0;
2676
4061
  if (reporter) {
2677
4062
  writeReporterResult(
2678
4063
  reporter,
2679
- sdk.buildToolCallValidationReport(validationResult, {
4064
+ buildToolCallValidationReport(validationResult, {
2680
4065
  durationMs: Date.now() - startedAt,
2681
4066
  rawResult: result,
2682
4067
  metadata: {
@@ -2693,16 +4078,301 @@ function registerToolsCommands(program) {
2693
4078
  if (validationResult && !validationResult.passed) {
2694
4079
  setProcessExitCode(1);
2695
4080
  }
2696
- if (sdk.isCallToolResultError(result)) {
4081
+ if (isCallToolResultError(result)) {
2697
4082
  setProcessExitCode(1);
2698
4083
  }
2699
4084
  });
2700
4085
  }
2701
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
+ });
4111
+ writeResult(
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
+ },
4156
+ globalOptions.format
4157
+ );
4158
+ });
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
+ }
4370
+
2702
4371
  // src/index.ts
4372
+ var pkgVersion = package_default.version;
2703
4373
  async function main(argv = process.argv) {
2704
4374
  const program = addGlobalOptions(
2705
- 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(
2706
4376
  "Test, debug, and validate MCP servers. Health checks, OAuth conformance, tool-surface diffing, and structured triage from the terminal or CI."
2707
4377
  ).allowExcessArguments(false).exitOverride().configureOutput({
2708
4378
  writeOut: (value) => process.stdout.write(value),
@@ -2717,33 +4387,77 @@ async function main(argv = process.argv) {
2717
4387
  registerAppsCommands(program);
2718
4388
  registerOAuthCommands(program);
2719
4389
  registerProtocolCommands(program);
4390
+ registerInspectorCommands(program);
2720
4391
  if (argv.length <= 2) {
2721
4392
  program.outputHelp();
2722
- return 0;
4393
+ return {
4394
+ exitCode: 0,
4395
+ shouldCheckForUpdates: false
4396
+ };
2723
4397
  }
2724
4398
  try {
2725
4399
  await program.parseAsync(argv);
2726
4400
  const exitCode = process.exitCode;
2727
4401
  if (typeof exitCode === "number") {
2728
- return exitCode;
4402
+ return {
4403
+ exitCode,
4404
+ shouldCheckForUpdates: true
4405
+ };
2729
4406
  }
2730
- return Number(exitCode ?? 0) || 0;
4407
+ return {
4408
+ exitCode: Number(exitCode ?? 0) || 0,
4409
+ shouldCheckForUpdates: true
4410
+ };
2731
4411
  } catch (error) {
2732
4412
  const format = detectOutputFormatFromArgv(argv);
2733
- if (error instanceof commander.CommanderError) {
4413
+ if (error instanceof CommanderError) {
2734
4414
  if (error.code === "commander.helpDisplayed" || error.code === "commander.version") {
2735
- return 0;
4415
+ return {
4416
+ exitCode: 0,
4417
+ shouldCheckForUpdates: false
4418
+ };
2736
4419
  }
2737
4420
  writeError(usageError(error.message), format);
2738
- return 2;
4421
+ return {
4422
+ exitCode: 2,
4423
+ shouldCheckForUpdates: false
4424
+ };
2739
4425
  }
2740
4426
  const normalizedError = normalizeCliError(error);
2741
4427
  writeError(normalizedError, format);
2742
- return normalizedError.exitCode;
4428
+ return {
4429
+ exitCode: normalizedError.exitCode,
4430
+ shouldCheckForUpdates: false
4431
+ };
2743
4432
  }
2744
4433
  }
2745
- void main().then((exitCode) => {
2746
- process.exitCode = exitCode;
2747
- });
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 };
2748
4462
  //# sourceMappingURL=index.js.map
2749
4463
  //# sourceMappingURL=index.js.map