@mcpjam/cli 3.3.0 → 3.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -12,7 +12,7 @@ import os, { homedir } from 'os';
12
12
 
13
13
  // package.json
14
14
  var package_default = {
15
- version: "3.3.0"};
15
+ version: "3.3.2"};
16
16
 
17
17
  // src/lib/output.ts
18
18
  var DEFAULT_OUTPUT_FORMAT = "json";
@@ -582,7 +582,8 @@ function assertNoCredentialsFileAuthConflicts(options) {
582
582
  }
583
583
  function redactCredentialsFromResult(result, credentialsFilePath) {
584
584
  const redacted = redactSensitiveValue(result);
585
- const credentials = result.credentials;
585
+ const credentials = result.credentials ?? {};
586
+ const hasCredentials = Object.keys(credentials).length > 0;
586
587
  const secretMarker = credentialsFilePath ? "[SAVED_TO_FILE]" : "[REDACTED]";
587
588
  const redactedCredentials = {
588
589
  ...redacted.credentials ?? {},
@@ -595,26 +596,29 @@ function redactCredentialsFromResult(result, credentialsFilePath) {
595
596
  };
596
597
  return {
597
598
  ...redacted,
598
- credentials: redactedCredentials,
599
+ ...hasCredentials ? { credentials: redactedCredentials } : {},
599
600
  ...credentialsFilePath ? { credentialsFile: credentialsFilePath } : {}
600
601
  };
601
602
  }
602
603
  function hasCredentialsToSave(result) {
603
- return Boolean(result.credentials.accessToken || result.credentials.refreshToken);
604
+ return Boolean(
605
+ result.credentials?.accessToken || result.credentials?.refreshToken
606
+ );
604
607
  }
605
608
  function buildCredentialsFileContents(result, now) {
606
609
  if (!hasCredentialsToSave(result)) {
607
- throw usageError("OAuth login did not return usable credentials to save.");
610
+ throw usageError("OAuth flow did not return usable credentials to save.");
608
611
  }
609
- const expiresAt = typeof result.credentials.expiresIn === "number" && Number.isFinite(result.credentials.expiresIn) ? new Date(now.getTime() + result.credentials.expiresIn * 1e3).toISOString() : void 0;
612
+ const credentials = result.credentials ?? {};
613
+ const expiresAt = typeof credentials.expiresIn === "number" && Number.isFinite(credentials.expiresIn) ? new Date(now.getTime() + credentials.expiresIn * 1e3).toISOString() : void 0;
610
614
  return {
611
615
  version: CREDENTIALS_FILE_VERSION,
612
616
  serverUrl: result.serverUrl,
613
- ...result.credentials.accessToken ? { accessToken: result.credentials.accessToken } : {},
614
- ...result.credentials.refreshToken ? { refreshToken: result.credentials.refreshToken } : {},
615
- ...result.credentials.clientId ? { clientId: result.credentials.clientId } : {},
616
- ...result.credentials.clientSecret ? { clientSecret: result.credentials.clientSecret } : {},
617
- ...result.credentials.tokenType ? { tokenType: result.credentials.tokenType } : {},
617
+ ...credentials.accessToken ? { accessToken: credentials.accessToken } : {},
618
+ ...credentials.refreshToken ? { refreshToken: credentials.refreshToken } : {},
619
+ ...credentials.clientId ? { clientId: credentials.clientId } : {},
620
+ ...credentials.clientSecret ? { clientSecret: credentials.clientSecret } : {},
621
+ ...credentials.tokenType ? { tokenType: credentials.tokenType } : {},
618
622
  ...expiresAt ? { expiresAt } : {},
619
623
  ...result.protocolVersion ? { protocolVersion: result.protocolVersion } : {}
620
624
  };
@@ -788,7 +792,7 @@ function addSharedServerOptions(command) {
788
792
  "OAuth client secret used with --refresh-token"
789
793
  ).option(
790
794
  "--credentials-file <path>",
791
- "Load OAuth credentials from a file created by oauth login --credentials-out"
795
+ "Load OAuth credentials from a file created by oauth login or oauth conformance --credentials-out"
792
796
  ).option(
793
797
  "--header <header>",
794
798
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
@@ -1243,7 +1247,7 @@ function registerProtocolCommands(program) {
1243
1247
  const protocol = program.command("protocol").description("MCP protocol inspection and conformance checks");
1244
1248
  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(
1245
1249
  "--credentials-file <path>",
1246
- "Load OAuth access token from a file created by oauth login --credentials-out"
1250
+ "Load OAuth access token from a file created by oauth login or oauth conformance --credentials-out"
1247
1251
  ).option(
1248
1252
  "--header <header>",
1249
1253
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
@@ -1359,21 +1363,49 @@ function parseOAuthOutputFormat(value) {
1359
1363
  function resolveOAuthOutputFormat(value, isTTY) {
1360
1364
  return parseOAuthOutputFormat(value ?? (isTTY ? "human" : "json"));
1361
1365
  }
1362
- function renderOAuthConformanceResult(result, format) {
1366
+ function renderOAuthConformanceResult(result, format, options = {}) {
1367
+ const redactedResult = redactOAuthConformanceResult(result, options);
1363
1368
  switch (format) {
1364
1369
  case "human":
1365
- return formatOAuthConformanceHuman(result);
1370
+ return formatOAuthConformanceHuman(redactedResult);
1366
1371
  case "json":
1367
- return JSON.stringify(result);
1372
+ return JSON.stringify(redactedResult);
1368
1373
  }
1369
1374
  }
1370
- function renderOAuthConformanceSuiteResult(result, format) {
1375
+ function renderOAuthConformanceSuiteResult(result, format, options = {}) {
1376
+ const redactedResult = redactOAuthConformanceSuiteResult(result, options);
1371
1377
  switch (format) {
1372
1378
  case "human":
1373
- return formatOAuthConformanceSuiteHuman(result);
1379
+ return formatOAuthConformanceSuiteHuman(redactedResult);
1374
1380
  case "json":
1375
- return JSON.stringify(result);
1381
+ return JSON.stringify(redactedResult);
1382
+ }
1383
+ }
1384
+ function redactOAuthConformanceResult(result, options) {
1385
+ if (options.credentialsFilePath && result.credentials) {
1386
+ return redactCredentialsFromResult(
1387
+ result,
1388
+ options.credentialsFilePath
1389
+ );
1390
+ }
1391
+ return redactSensitiveValue(result);
1392
+ }
1393
+ function redactOAuthConformanceSuiteResult(result, options) {
1394
+ const redacted = redactSensitiveValue(result);
1395
+ if (options.credentialsFilePath) {
1396
+ redacted.credentialsFile = options.credentialsFilePath;
1397
+ }
1398
+ const resultIndex = options.credentialsResultIndex;
1399
+ if (options.credentialsFilePath && resultIndex !== void 0 && result.results[resultIndex]?.credentials && redacted.results[resultIndex]) {
1400
+ redacted.results[resultIndex] = {
1401
+ ...redacted.results[resultIndex],
1402
+ ...redactCredentialsFromResult(
1403
+ result.results[resultIndex],
1404
+ options.credentialsFilePath
1405
+ )
1406
+ };
1376
1407
  }
1408
+ return redacted;
1377
1409
  }
1378
1410
  async function writeCommandDebugArtifact(options, dependencies = {}) {
1379
1411
  if (!options.outputPath) {
@@ -1774,6 +1806,9 @@ function registerOAuthCommands(program) {
1774
1806
  ).option(
1775
1807
  "--conformance-checks",
1776
1808
  "Run additional OAuth negative checks (invalid client, invalid redirect, token format) after the main flow"
1809
+ ).option(
1810
+ "--credentials-out <path>",
1811
+ "Write OAuth credentials to <path> (mode 0600); stdout output has secret fields redacted to [SAVED_TO_FILE]"
1777
1812
  ).option(
1778
1813
  "--print-url",
1779
1814
  "In interactive mode, print the consent URL to stderr instead of launching a browser"
@@ -1785,9 +1820,26 @@ function registerOAuthCommands(program) {
1785
1820
  const format = getOAuthConformanceFormat(command, reporter);
1786
1821
  const config = buildOAuthConformanceConfig(options);
1787
1822
  const result = await new OAuthConformanceTest(config).run();
1823
+ let credentialsFilePath;
1824
+ let credentialsFileError;
1825
+ if (options.credentialsOut && hasCredentialsToSave(result)) {
1826
+ try {
1827
+ credentialsFilePath = await writeCredentialsFile(
1828
+ options.credentialsOut,
1829
+ result
1830
+ );
1831
+ } catch (error) {
1832
+ credentialsFileError = error;
1833
+ }
1834
+ }
1788
1835
  writeOAuthOutput(
1789
- reporter ? renderConformanceReporterResult(result, reporter) : renderOAuthConformanceResult(result, format)
1836
+ reporter ? renderConformanceReporterResult(result, reporter) : renderOAuthConformanceResult(result, format, {
1837
+ credentialsFilePath
1838
+ })
1790
1839
  );
1840
+ if (credentialsFileError) {
1841
+ throw credentialsFileError;
1842
+ }
1791
1843
  if (!result.passed) {
1792
1844
  setProcessExitCode(1);
1793
1845
  }
@@ -1800,6 +1852,9 @@ function registerOAuthCommands(program) {
1800
1852
  ).option(
1801
1853
  "--verify-call-tool <name>",
1802
1854
  "Also call the named tool after listing"
1855
+ ).option(
1856
+ "--credentials-out <path>",
1857
+ "Write OAuth credentials from the first flow that returns credentials to <path> (mode 0600)"
1803
1858
  ).option(
1804
1859
  "--reporter <reporter>",
1805
1860
  "Structured reporter output: json-summary or junit-xml"
@@ -1822,9 +1877,28 @@ function registerOAuthCommands(program) {
1822
1877
  }
1823
1878
  const suite = new OAuthConformanceSuite(config);
1824
1879
  const result = await suite.run();
1880
+ const credentialsResultIndex = findCredentialsResultIndex(result);
1881
+ let credentialsFilePath;
1882
+ let credentialsFileError;
1883
+ if (options.credentialsOut && credentialsResultIndex !== void 0) {
1884
+ try {
1885
+ credentialsFilePath = await writeCredentialsFile(
1886
+ options.credentialsOut,
1887
+ result.results[credentialsResultIndex]
1888
+ );
1889
+ } catch (error) {
1890
+ credentialsFileError = error;
1891
+ }
1892
+ }
1825
1893
  writeOAuthOutput(
1826
- reporter ? renderConformanceReporterResult(result, reporter) : renderOAuthConformanceSuiteResult(result, format)
1894
+ reporter ? renderConformanceReporterResult(result, reporter) : renderOAuthConformanceSuiteResult(result, format, {
1895
+ credentialsFilePath,
1896
+ credentialsResultIndex
1897
+ })
1827
1898
  );
1899
+ if (credentialsFileError) {
1900
+ throw credentialsFileError;
1901
+ }
1828
1902
  if (!result.passed) {
1829
1903
  setProcessExitCode(1);
1830
1904
  }
@@ -1944,6 +2018,10 @@ function buildOAuthConformanceConfig(options, defaults) {
1944
2018
  oauthConformanceChecks: options.conformanceChecks ?? false
1945
2019
  };
1946
2020
  }
2021
+ function findCredentialsResultIndex(result) {
2022
+ const index = result.results.findIndex(hasCredentialsToSave);
2023
+ return index >= 0 ? index : void 0;
2024
+ }
1947
2025
  function buildOAuthLoginConfig(options, defaults) {
1948
2026
  const serverUrl = options.url.trim();
1949
2027
  assertValidUrl2(serverUrl, "server URL");
@@ -2397,7 +2475,7 @@ function registerServerCommands(program) {
2397
2475
  "OAuth bearer access token for HTTP servers"
2398
2476
  ).option(
2399
2477
  "--credentials-file <path>",
2400
- "Load OAuth access token from a file created by oauth login --credentials-out"
2478
+ "Load OAuth access token from a file created by oauth login or oauth conformance --credentials-out"
2401
2479
  ).option(
2402
2480
  "--header <header>",
2403
2481
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
@@ -3557,9 +3635,13 @@ var DEFAULT_COMMAND_TIMEOUT_MS = 3e4;
3557
3635
  var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
3558
3636
  var COMMAND_FETCH_TIMEOUT_BUFFER_MS = 2e3;
3559
3637
  var HEALTH_FETCH_TIMEOUT_MS = 2e3;
3638
+ var FRONTEND_PROBE_TIMEOUT_MS = 750;
3639
+ var ORIGIN_PROBE_TIMEOUT_MS = 750;
3560
3640
  var SESSION_TOKEN_TIMEOUT_MS = 3e3;
3561
3641
  var STOP_FETCH_TIMEOUT_MS = 3e3;
3562
3642
  var STARTUP_LOG_MAX_BYTES = 1024 * 1024;
3643
+ var FRONTEND_PORT_SCAN_WINDOW = 10;
3644
+ var WELL_KNOWN_FRONTEND_PORTS = [5173, 5174, 5175, 8080];
3563
3645
  var TOKEN_TTL_MS = 5 * 6e4;
3564
3646
  var tokenCache = /* @__PURE__ */ new Map();
3565
3647
  var tokenRequests = /* @__PURE__ */ new Map();
@@ -3596,23 +3678,167 @@ function normalizeInspectorFrontendUrl(frontendUrl) {
3596
3678
  return void 0;
3597
3679
  }
3598
3680
  }
3599
- function buildInspectorBrowserUrl(baseUrl, frontendUrl, tab) {
3600
- return buildInspectorUrl(
3601
- normalizeInspectorFrontendUrl(frontendUrl) ?? baseUrl,
3602
- tab
3681
+ function normalizeExplicitInspectorFrontendUrl(frontendUrl) {
3682
+ const normalized = normalizeInspectorFrontendUrl(frontendUrl);
3683
+ if (!normalized) {
3684
+ throw operationalError(`Invalid Inspector frontend URL "${frontendUrl}".`);
3685
+ }
3686
+ return normalized;
3687
+ }
3688
+ function canonicalizeInspectorFrontendUrl(baseUrl, frontendUrl) {
3689
+ if (!frontendUrl) {
3690
+ return void 0;
3691
+ }
3692
+ try {
3693
+ const base = new URL(baseUrl);
3694
+ const frontend = new URL(frontendUrl);
3695
+ if (isLoopbackHostname(base.hostname) && isLoopbackHostname(frontend.hostname) && base.protocol === frontend.protocol && getEffectiveUrlPort(base) === getEffectiveUrlPort(frontend)) {
3696
+ return baseUrl;
3697
+ }
3698
+ } catch {
3699
+ return frontendUrl;
3700
+ }
3701
+ return frontendUrl;
3702
+ }
3703
+ function getEffectiveUrlPort(url) {
3704
+ if (url.port) {
3705
+ return url.port;
3706
+ }
3707
+ return url.protocol === "https:" ? "443" : "80";
3708
+ }
3709
+ async function resolveInspectorBrowserBaseUrl(baseUrl, frontendUrl, options = {}) {
3710
+ const fastResolution = await resolveInspectorBrowserBaseUrlFast(
3711
+ baseUrl,
3712
+ frontendUrl
3713
+ );
3714
+ if (fastResolution.browserBaseUrl) {
3715
+ return fastResolution.browserBaseUrl;
3716
+ }
3717
+ if (options.skipDiscovery) {
3718
+ assertFastFrontendMismatch(fastResolution.candidates);
3719
+ return fastResolution.normalizedFrontendUrl ?? baseUrl;
3720
+ }
3721
+ const discoveredCandidates = await discoverLocalInspectorFrontendCandidates(
3722
+ baseUrl,
3723
+ fastResolution.normalizedFrontendUrl
3724
+ );
3725
+ const usableDiscoveredCandidate = discoveredCandidates.find(
3726
+ isUsableInspectorFrontendCandidate
3727
+ );
3728
+ if (usableDiscoveredCandidate) {
3729
+ return usableDiscoveredCandidate.url;
3730
+ }
3731
+ const candidates = [...fastResolution.candidates, ...discoveredCandidates];
3732
+ assertFullFrontendMismatch(candidates);
3733
+ return fastResolution.normalizedFrontendUrl ?? baseUrl;
3734
+ }
3735
+ async function resolveInspectorBrowserBaseUrlFast(baseUrl, frontendUrl) {
3736
+ const normalizedFrontendUrl = canonicalizeInspectorFrontendUrl(
3737
+ baseUrl,
3738
+ normalizeInspectorFrontendUrl(frontendUrl)
3739
+ );
3740
+ const targets = [];
3741
+ if (normalizedFrontendUrl) {
3742
+ targets.push({ source: "advertised", url: normalizedFrontendUrl });
3743
+ }
3744
+ if (!targets.some((target) => target.url === baseUrl)) {
3745
+ targets.push({ source: "base", url: baseUrl });
3746
+ }
3747
+ const candidates = await inspectInspectorFrontendCandidates(
3748
+ baseUrl,
3749
+ targets
3750
+ );
3751
+ const usableCandidate = candidates.find(isUsableInspectorFrontendCandidate);
3752
+ return {
3753
+ ...usableCandidate ? { browserBaseUrl: usableCandidate.url } : {},
3754
+ candidates,
3755
+ ...normalizedFrontendUrl ? { normalizedFrontendUrl } : {}
3756
+ };
3757
+ }
3758
+ async function inspectInspectorFrontendCandidates(apiBaseUrl, targets) {
3759
+ const settled = await Promise.allSettled(
3760
+ targets.map(
3761
+ (target) => inspectInspectorFrontendCandidate(apiBaseUrl, target.url, target.source)
3762
+ )
3603
3763
  );
3764
+ return settled.map((result, index) => {
3765
+ if (result.status === "fulfilled") {
3766
+ return result.value;
3767
+ }
3768
+ const target = targets[index];
3769
+ return {
3770
+ isFrontend: false,
3771
+ originStatus: "unknown",
3772
+ source: target.source,
3773
+ url: target.url
3774
+ };
3775
+ });
3776
+ }
3777
+ function assertFastFrontendMismatch(candidates) {
3778
+ const advertisedCandidate = candidates.find(
3779
+ (candidate) => candidate.source === "advertised"
3780
+ );
3781
+ const rejectedLiveCandidate = candidates.find(
3782
+ (candidate) => candidate.isFrontend && candidate.originStatus === "rejected"
3783
+ );
3784
+ if (!rejectedLiveCandidate) {
3785
+ return;
3786
+ }
3787
+ if (advertisedCandidate === rejectedLiveCandidate) {
3788
+ throw frontendMismatchError(void 0, rejectedLiveCandidate);
3789
+ }
3790
+ throw frontendMismatchError(advertisedCandidate, rejectedLiveCandidate);
3791
+ }
3792
+ function assertFullFrontendMismatch(candidates) {
3793
+ const advertisedCandidate = candidates.find(
3794
+ (candidate) => candidate.source === "advertised"
3795
+ );
3796
+ const rejectedLiveCandidate = candidates.find(
3797
+ (candidate) => candidate !== advertisedCandidate && candidate.isFrontend && candidate.originStatus === "rejected"
3798
+ );
3799
+ if (advertisedCandidate?.isFrontend && advertisedCandidate.originStatus === "rejected") {
3800
+ throw frontendMismatchError(void 0, advertisedCandidate);
3801
+ }
3802
+ if (advertisedCandidate && !advertisedCandidate.isFrontend && advertisedCandidate.originStatus === "accepted") {
3803
+ throw frontendMismatchError(advertisedCandidate, rejectedLiveCandidate);
3804
+ }
3805
+ if (rejectedLiveCandidate) {
3806
+ throw frontendMismatchError(advertisedCandidate, rejectedLiveCandidate);
3807
+ }
3808
+ }
3809
+ async function resolveInspectorBrowserBaseUrlForHealth(baseUrl, frontendUrl, options) {
3810
+ try {
3811
+ return await resolveInspectorBrowserBaseUrl(baseUrl, frontendUrl, {
3812
+ skipDiscovery: options.skipDiscovery
3813
+ });
3814
+ } catch (error) {
3815
+ if (options.hasActiveClient && !options.openBrowser) {
3816
+ return canonicalizeInspectorFrontendUrl(
3817
+ baseUrl,
3818
+ normalizeInspectorFrontendUrl(frontendUrl)
3819
+ ) ?? baseUrl;
3820
+ }
3821
+ throw error;
3822
+ }
3604
3823
  }
3605
3824
  async function ensureInspector(options = {}) {
3606
3825
  const baseUrl = normalizeInspectorBaseUrl(options.baseUrl);
3826
+ const explicitFrontendUrl = options.frontendUrl !== void 0 ? normalizeExplicitInspectorFrontendUrl(options.frontendUrl) : void 0;
3607
3827
  const health = await getInspectorHealth(baseUrl);
3608
3828
  if (health.healthy) {
3609
- const url2 = buildInspectorBrowserUrl(baseUrl, health.frontendUrl, options.tab);
3829
+ const browserBaseUrl2 = explicitFrontendUrl ?? await resolveInspectorBrowserBaseUrlForHealth(baseUrl, health.frontendUrl, {
3830
+ hasActiveClient: health.hasActiveClient,
3831
+ openBrowser: options.openBrowser === true,
3832
+ skipDiscovery: options.skipDiscovery
3833
+ });
3834
+ const url2 = buildInspectorUrl(browserBaseUrl2, options.tab);
3610
3835
  if (options.openBrowser && !health.hasActiveClient) {
3611
3836
  openUrl(url2);
3612
3837
  }
3613
3838
  return {
3614
3839
  baseUrl,
3615
- ...health.frontendUrl ? { frontendUrl: health.frontendUrl } : {},
3840
+ ...browserBaseUrl2 !== baseUrl ? { frontendUrl: browserBaseUrl2 } : {},
3841
+ hasActiveClient: health.hasActiveClient,
3616
3842
  url: url2,
3617
3843
  started: false
3618
3844
  };
@@ -3625,17 +3851,23 @@ async function ensureInspector(options = {}) {
3625
3851
  await startInspector(baseUrl, options.timeoutMs ?? DEFAULT_START_TIMEOUT_MS);
3626
3852
  clearInspectorSessionTokenCache(baseUrl);
3627
3853
  const startedHealth = await getInspectorHealth(baseUrl);
3628
- const url = buildInspectorBrowserUrl(
3854
+ const browserBaseUrl = explicitFrontendUrl ?? await resolveInspectorBrowserBaseUrlForHealth(
3629
3855
  baseUrl,
3630
3856
  startedHealth.frontendUrl,
3631
- options.tab
3857
+ {
3858
+ hasActiveClient: startedHealth.hasActiveClient,
3859
+ openBrowser: options.openBrowser === true,
3860
+ skipDiscovery: options.skipDiscovery
3861
+ }
3632
3862
  );
3863
+ const url = buildInspectorUrl(browserBaseUrl, options.tab);
3633
3864
  if (options.openBrowser) {
3634
3865
  openUrl(url);
3635
3866
  }
3636
3867
  return {
3637
3868
  baseUrl,
3638
- ...startedHealth.frontendUrl ? { frontendUrl: startedHealth.frontendUrl } : {},
3869
+ ...browserBaseUrl !== baseUrl ? { frontendUrl: browserBaseUrl } : {},
3870
+ hasActiveClient: startedHealth.hasActiveClient,
3639
3871
  url,
3640
3872
  started: true
3641
3873
  };
@@ -3881,6 +4113,177 @@ async function getInspectorHealth(baseUrl, timeoutMs = HEALTH_FETCH_TIMEOUT_MS)
3881
4113
  return { healthy: false, hasActiveClient: false };
3882
4114
  }
3883
4115
  }
4116
+ async function isInspectorFrontendUrl(baseUrl) {
4117
+ try {
4118
+ const response = await fetch(`${baseUrl}/`, {
4119
+ signal: AbortSignal.timeout(FRONTEND_PROBE_TIMEOUT_MS)
4120
+ });
4121
+ if (!response.ok) {
4122
+ return false;
4123
+ }
4124
+ const contentType = response.headers.get("content-type") ?? "";
4125
+ if (!contentType.toLowerCase().includes("text/html")) {
4126
+ return false;
4127
+ }
4128
+ const body = await response.text();
4129
+ return hasInspectorFrontendMarker(body) || /<title>\s*MCPJam Inspector\s*<\/title>/i.test(body) || body.includes("/mcp_jam.svg") || body.includes("__MCP_SESSION_TOKEN__");
4130
+ } catch {
4131
+ return false;
4132
+ }
4133
+ }
4134
+ function hasInspectorFrontendMarker(body) {
4135
+ return /<meta\b(?=[^>]*\bname=["']mcpjam-inspector["'])[^>]*>/i.test(body);
4136
+ }
4137
+ async function inspectInspectorFrontendCandidate(apiBaseUrl, frontendBaseUrl, source) {
4138
+ const [isFrontend, originStatus] = await Promise.all([
4139
+ isInspectorFrontendUrl(frontendBaseUrl),
4140
+ getInspectorApiOriginStatus(apiBaseUrl, frontendBaseUrl)
4141
+ ]);
4142
+ return {
4143
+ isFrontend,
4144
+ originStatus,
4145
+ source,
4146
+ url: frontendBaseUrl
4147
+ };
4148
+ }
4149
+ function isUsableInspectorFrontendCandidate(candidate) {
4150
+ return candidate.isFrontend && candidate.originStatus !== "rejected";
4151
+ }
4152
+ async function getInspectorApiOriginStatus(apiBaseUrl, frontendBaseUrl) {
4153
+ try {
4154
+ const origin = new URL(frontendBaseUrl).origin;
4155
+ const response = await fetch(`${apiBaseUrl}/api/session-token`, {
4156
+ headers: { Origin: origin },
4157
+ signal: AbortSignal.timeout(ORIGIN_PROBE_TIMEOUT_MS)
4158
+ });
4159
+ return response.status === 403 ? "rejected" : "accepted";
4160
+ } catch {
4161
+ return "unknown";
4162
+ }
4163
+ }
4164
+ function frontendMismatchError(advertisedCandidate, rejectedLiveCandidate) {
4165
+ const details = {
4166
+ ...advertisedCandidate ? {
4167
+ advertisedFrontendUrl: advertisedCandidate.url,
4168
+ advertisedFrontendReachable: advertisedCandidate.isFrontend,
4169
+ advertisedOriginStatus: advertisedCandidate.originStatus
4170
+ } : {},
4171
+ ...rejectedLiveCandidate ? {
4172
+ rejectedFrontendUrl: rejectedLiveCandidate.url,
4173
+ rejectedOriginStatus: rejectedLiveCandidate.originStatus
4174
+ } : {}
4175
+ };
4176
+ if (advertisedCandidate && rejectedLiveCandidate) {
4177
+ return operationalError(
4178
+ `Inspector backend advertises ${advertisedCandidate.url}, but no Inspector frontend responded there. A frontend was found at ${rejectedLiveCandidate.url}, but the Inspector backend rejects that origin. Start Inspector's frontend on the advertised URL or restart Inspector with matching frontend/backend ports.`,
4179
+ details
4180
+ );
4181
+ }
4182
+ if (advertisedCandidate) {
4183
+ return operationalError(
4184
+ `Inspector backend advertises ${advertisedCandidate.url}, but no Inspector frontend responded there. Start Inspector's frontend on the advertised URL or restart Inspector with matching frontend/backend ports.`,
4185
+ details
4186
+ );
4187
+ }
4188
+ return operationalError(
4189
+ `Inspector frontend ${rejectedLiveCandidate?.url ?? "URL"} is reachable, but the Inspector backend rejects that origin. Restart Inspector with matching frontend/backend ports.`,
4190
+ details
4191
+ );
4192
+ }
4193
+ async function discoverLocalInspectorFrontendCandidates(baseUrl, frontendUrl) {
4194
+ const hosts = getLocalInspectorCandidateHosts(baseUrl, frontendUrl);
4195
+ if (hosts.length === 0) {
4196
+ return [];
4197
+ }
4198
+ const protocol = getUrlProtocol(frontendUrl) ?? getUrlProtocol(baseUrl) ?? "http:";
4199
+ const targets = [];
4200
+ for (const port of getFrontendProbePorts(frontendUrl)) {
4201
+ for (const host of hosts) {
4202
+ const candidate = `${protocol}//${formatUrlHostname(host)}:${port}`;
4203
+ if (candidate === frontendUrl || candidate === baseUrl) {
4204
+ continue;
4205
+ }
4206
+ targets.push(candidate);
4207
+ }
4208
+ }
4209
+ const inspectedCandidates = await inspectInspectorFrontendCandidates(
4210
+ baseUrl,
4211
+ targets.map((candidate) => ({
4212
+ source: "discovered",
4213
+ url: candidate
4214
+ }))
4215
+ );
4216
+ return inspectedCandidates.filter((candidate) => candidate.isFrontend);
4217
+ }
4218
+ function getLocalInspectorCandidateHosts(baseUrl, frontendUrl) {
4219
+ const hosts = /* @__PURE__ */ new Set();
4220
+ for (const value of [frontendUrl, baseUrl]) {
4221
+ const hostname = getUrlHostname(value);
4222
+ if (!hostname || !isLoopbackHostname(hostname)) {
4223
+ continue;
4224
+ }
4225
+ hosts.add(hostname);
4226
+ if (hostname === "localhost") {
4227
+ hosts.add("127.0.0.1");
4228
+ }
4229
+ if (hostname === "127.0.0.1") {
4230
+ hosts.add("localhost");
4231
+ }
4232
+ }
4233
+ return [...hosts];
4234
+ }
4235
+ function getFrontendProbePorts(frontendUrl) {
4236
+ const ports = /* @__PURE__ */ new Set();
4237
+ const hintedPort = getUrlPort(frontendUrl);
4238
+ if (hintedPort) {
4239
+ ports.add(hintedPort);
4240
+ for (let offset = 1; offset <= FRONTEND_PORT_SCAN_WINDOW; offset += 1) {
4241
+ ports.add(hintedPort + offset);
4242
+ }
4243
+ }
4244
+ for (const port of WELL_KNOWN_FRONTEND_PORTS) {
4245
+ ports.add(port);
4246
+ }
4247
+ return [...ports].filter((port) => port > 0 && port < 65536);
4248
+ }
4249
+ function getUrlHostname(value) {
4250
+ if (!value) {
4251
+ return void 0;
4252
+ }
4253
+ try {
4254
+ return new URL(value).hostname.toLowerCase();
4255
+ } catch {
4256
+ return void 0;
4257
+ }
4258
+ }
4259
+ function getUrlProtocol(value) {
4260
+ if (!value) {
4261
+ return void 0;
4262
+ }
4263
+ try {
4264
+ return new URL(value).protocol;
4265
+ } catch {
4266
+ return void 0;
4267
+ }
4268
+ }
4269
+ function getUrlPort(value) {
4270
+ if (!value) {
4271
+ return void 0;
4272
+ }
4273
+ try {
4274
+ const parsed = new URL(value);
4275
+ const port = Number(parsed.port);
4276
+ return Number.isInteger(port) && port > 0 ? port : void 0;
4277
+ } catch {
4278
+ return void 0;
4279
+ }
4280
+ }
4281
+ function isLoopbackHostname(hostname) {
4282
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]";
4283
+ }
4284
+ function formatUrlHostname(hostname) {
4285
+ return hostname.includes(":") && !hostname.startsWith("[") ? `[${hostname}]` : hostname;
4286
+ }
3884
4287
  async function isInspectorHealthy(baseUrl) {
3885
4288
  const status = await getInspectorHealth(baseUrl);
3886
4289
  return status.healthy;
@@ -4004,12 +4407,25 @@ function isInspectorCommandResponse(value) {
4004
4407
  // src/lib/inspector-render.ts
4005
4408
  async function runUiRender(options) {
4006
4409
  const client = new InspectorApiClient({ baseUrl: options.baseUrl });
4410
+ const openBrowser = options.openBrowser === true;
4007
4411
  const ensureResult = await client.ensure({
4008
- openBrowser: true,
4009
- startIfNeeded: true,
4412
+ frontendUrl: options.frontendUrl,
4413
+ openBrowser,
4414
+ skipDiscovery: options.skipDiscovery,
4415
+ startIfNeeded: options.startIfNeeded ?? true,
4010
4416
  tab: "app-builder",
4011
4417
  timeoutMs: options.timeoutMs
4012
4418
  });
4419
+ if (!ensureResult.hasActiveClient && !openBrowser) {
4420
+ const startedNote = ensureResult.started ? " Inspector was just started by the CLI and is still running." : "";
4421
+ throw operationalError(
4422
+ `Inspector has no active browser client.${startedNote} Open the Inspector App Builder URL in your browser, then rerun \`tools call --ui\`; or pass \`--open\` to let the CLI open a system browser.`,
4423
+ {
4424
+ inspectorBrowserUrl: ensureResult.url,
4425
+ inspectorStarted: ensureResult.started
4426
+ }
4427
+ );
4428
+ }
4013
4429
  await client.connectServer(options.serverName, options.config, {
4014
4430
  timeoutMs: options.timeoutMs
4015
4431
  });
@@ -4024,6 +4440,10 @@ async function runUiRender(options) {
4024
4440
  });
4025
4441
  return {
4026
4442
  baseUrl: ensureResult.baseUrl,
4443
+ browserUrl: ensureResult.url,
4444
+ ...ensureResult.frontendUrl ? { frontendUrl: ensureResult.frontendUrl } : {},
4445
+ browserOpenRequested: openBrowser,
4446
+ hasActiveClient: ensureResult.hasActiveClient,
4027
4447
  inspectorStarted: ensureResult.started,
4028
4448
  ...renderResult
4029
4449
  };
@@ -4234,7 +4654,16 @@ function registerToolsCommands(program) {
4234
4654
  ).option(
4235
4655
  "--debug-out <path>",
4236
4656
  "Write a structured debug artifact to a file"
4237
- ).option("--ui", "Open Inspector and render the tool result").option("--inspector-url <url>", "Local Inspector base URL (with --ui)").option(
4657
+ ).option("--ui", "Render the tool result in Inspector App Builder").option("--open", "Open Inspector in the system browser before rendering").option(
4658
+ "--no-open",
4659
+ "Start/use Inspector without opening a system browser"
4660
+ ).option(
4661
+ "--attach-only",
4662
+ "Require an already-running Inspector browser client; do not start or open Inspector"
4663
+ ).option("--inspector-url <url>", "Local Inspector base URL (with --ui)").option(
4664
+ "--frontend-url <url>",
4665
+ "Inspector frontend URL (with --ui; overrides health-advertised frontend and skips discovery)"
4666
+ ).option(
4238
4667
  "--server-name <name>",
4239
4668
  "Server name inside Inspector (with --ui)"
4240
4669
  ).option(
@@ -4278,6 +4707,9 @@ function registerToolsCommands(program) {
4278
4707
  if (options.ui && reporter) {
4279
4708
  throw usageError("--ui cannot be used together with --reporter.");
4280
4709
  }
4710
+ if (options.attachOnly && options.open === true) {
4711
+ throw usageError("--attach-only cannot be used together with --open.");
4712
+ }
4281
4713
  if (reporter && !shouldValidateResponse && !shouldExpectSuccess) {
4282
4714
  throw usageError(
4283
4715
  "--reporter requires --validate-response and/or --expect-success."
@@ -4290,6 +4722,7 @@ function registerToolsCommands(program) {
4290
4722
  locale: trimOptional(options.locale),
4291
4723
  timeZone: trimOptional(options.timeZone)
4292
4724
  } : void 0;
4725
+ const frontendUrl = options.ui ? parseInspectorFrontendUrl(options.frontendUrl) : void 0;
4293
4726
  let result;
4294
4727
  let commandError;
4295
4728
  const startedAt = Date.now();
@@ -4341,40 +4774,62 @@ function registerToolsCommands(program) {
4341
4774
  );
4342
4775
  const toolResultError = isCallToolResultError(result);
4343
4776
  let outputPayload = result;
4777
+ let debugOutputPayload = outputPayload;
4344
4778
  let inspectorRenderError;
4345
4779
  if (options.ui) {
4346
4780
  const serverName = typeof options.serverName === "string" && options.serverName.trim() ? options.serverName.trim() : buildInspectorServerName(options);
4781
+ const openBrowser = resolveInspectorOpenBrowser(options, globalOptions);
4782
+ const skipDiscovery = resolveInspectorSkipDiscovery(
4783
+ options,
4784
+ globalOptions
4785
+ );
4347
4786
  let uiResult;
4348
4787
  try {
4349
4788
  uiResult = await runUiRender({
4350
4789
  baseUrl: options.inspectorUrl,
4351
4790
  config,
4791
+ frontendUrl,
4792
+ openBrowser,
4352
4793
  params,
4353
4794
  renderContext,
4795
+ skipDiscovery,
4354
4796
  serverName,
4797
+ startIfNeeded: resolveInspectorStartIfNeeded(options),
4355
4798
  timeoutMs: globalOptions.timeout,
4356
4799
  toolName,
4357
4800
  toolResult: result
4358
4801
  });
4359
4802
  inspectorRenderError = findInspectorRenderError(uiResult);
4360
4803
  } catch (error) {
4361
- inspectorRenderError = toStructuredError(normalizeCliError(error)).error;
4804
+ inspectorRenderError = toStructuredError(
4805
+ normalizeCliError(error)
4806
+ ).error;
4362
4807
  uiResult = {
4363
4808
  status: "error",
4364
- error: inspectorRenderError
4809
+ error: inspectorRenderError,
4810
+ ...extractInspectorRenderErrorUrls(inspectorRenderError)
4365
4811
  };
4366
4812
  }
4367
- outputPayload = {
4813
+ const compactInspectorRender = buildCompactInspectorRender(uiResult);
4814
+ const compactOutputPayload = {
4368
4815
  success: !inspectorRenderError && !validationFailed && !toolResultError,
4369
4816
  command: "tools call",
4370
4817
  inspectorUi: true,
4818
+ ...typeof compactInspectorRender.browserUrl === "string" ? { inspectorBrowserUrl: compactInspectorRender.browserUrl } : {},
4819
+ ...typeof compactInspectorRender.frontendUrl === "string" ? { inspectorFrontendUrl: compactInspectorRender.frontendUrl } : {},
4371
4820
  target,
4372
4821
  toolName,
4373
- params,
4822
+ parameterKeys: Object.keys(params),
4374
4823
  result,
4375
- inspectorRender: uiResult,
4824
+ inspectorRender: compactInspectorRender,
4376
4825
  ...inspectorRenderError ? { error: inspectorRenderError } : {}
4377
4826
  };
4827
+ outputPayload = compactOutputPayload;
4828
+ debugOutputPayload = {
4829
+ ...compactOutputPayload,
4830
+ params,
4831
+ inspectorRender: uiResult
4832
+ };
4378
4833
  }
4379
4834
  await writeCommandDebugArtifact({
4380
4835
  outputPath: options.debugOut,
@@ -4389,10 +4844,10 @@ function registerToolsCommands(program) {
4389
4844
  outcome: inspectorRenderError ? {
4390
4845
  status: "error",
4391
4846
  error: inspectorRenderError,
4392
- result: outputPayload
4847
+ result: debugOutputPayload
4393
4848
  } : {
4394
4849
  status: "success",
4395
- result: outputPayload
4850
+ result: debugOutputPayload
4396
4851
  },
4397
4852
  snapshot: options.debugOut ? {
4398
4853
  input: {
@@ -4432,6 +4887,98 @@ function registerToolsCommands(program) {
4432
4887
  }
4433
4888
  });
4434
4889
  }
4890
+ function resolveInspectorOpenBrowser(options, globalOptions) {
4891
+ if (options.attachOnly) {
4892
+ return false;
4893
+ }
4894
+ if (options.open !== void 0) {
4895
+ return options.open;
4896
+ }
4897
+ return globalOptions.format === "human" && !globalOptions.quiet;
4898
+ }
4899
+ function parseInspectorFrontendUrl(value) {
4900
+ if (value === void 0) {
4901
+ return void 0;
4902
+ }
4903
+ const frontendUrl = normalizeInspectorFrontendUrl(value);
4904
+ if (!frontendUrl) {
4905
+ throw usageError(`Invalid --frontend-url "${value}".`);
4906
+ }
4907
+ return frontendUrl;
4908
+ }
4909
+ function resolveInspectorSkipDiscovery(options, globalOptions) {
4910
+ if (typeof options.frontendUrl === "string" && options.frontendUrl.trim()) {
4911
+ return true;
4912
+ }
4913
+ if (options.attachOnly) {
4914
+ return true;
4915
+ }
4916
+ if ((globalOptions.format === "json" || globalOptions.quiet) && options.open !== true) {
4917
+ return true;
4918
+ }
4919
+ if (options.open === true) {
4920
+ return false;
4921
+ }
4922
+ return false;
4923
+ }
4924
+ function resolveInspectorStartIfNeeded(options) {
4925
+ return options.attachOnly !== true;
4926
+ }
4927
+ function extractInspectorRenderErrorUrls(error) {
4928
+ if (!error.details || typeof error.details !== "object") {
4929
+ return {};
4930
+ }
4931
+ const details = error.details;
4932
+ return {
4933
+ ...typeof details.inspectorBrowserUrl === "string" ? { browserUrl: details.inspectorBrowserUrl } : {},
4934
+ ...typeof details.inspectorFrontendUrl === "string" ? { frontendUrl: details.inspectorFrontendUrl } : {}
4935
+ };
4936
+ }
4937
+ function buildCompactInspectorRender(uiResult) {
4938
+ const commands = {};
4939
+ let hasCommandError = false;
4940
+ for (const [commandName, commandValue] of Object.entries(uiResult)) {
4941
+ const response = compactInspectorCommandResponse(commandValue);
4942
+ if (!response) {
4943
+ continue;
4944
+ }
4945
+ commands[commandName] = response;
4946
+ if (response.status === "error") {
4947
+ hasCommandError = true;
4948
+ }
4949
+ }
4950
+ const topLevelError = uiResult.status === "error" && isRecord(uiResult.error) ? { error: uiResult.error } : {};
4951
+ return {
4952
+ status: hasCommandError || uiResult.status === "error" ? "error" : "rendered",
4953
+ // Contract metadata: renders target the active client and fresh tabs do not
4954
+ // hydrate this injected state.
4955
+ mode: "active-client",
4956
+ urlHydratesRender: false,
4957
+ ...typeof uiResult.baseUrl === "string" ? { baseUrl: uiResult.baseUrl } : {},
4958
+ ...typeof uiResult.browserUrl === "string" ? { browserUrl: uiResult.browserUrl } : {},
4959
+ ...typeof uiResult.frontendUrl === "string" ? { frontendUrl: uiResult.frontendUrl } : {},
4960
+ ...typeof uiResult.inspectorStarted === "boolean" ? { inspectorStarted: uiResult.inspectorStarted } : {},
4961
+ ...typeof uiResult.browserOpenRequested === "boolean" ? { browserOpenRequested: uiResult.browserOpenRequested } : {},
4962
+ ...typeof uiResult.hasActiveClient === "boolean" ? { hasActiveClient: uiResult.hasActiveClient } : {},
4963
+ ...Object.keys(commands).length > 0 ? { commands } : {},
4964
+ ...topLevelError
4965
+ };
4966
+ }
4967
+ function compactInspectorCommandResponse(value) {
4968
+ if (!isRecord(value) || !isCompactInspectorCommandStatus(value.status)) {
4969
+ return void 0;
4970
+ }
4971
+ return {
4972
+ status: value.status,
4973
+ ...value.status === "error" && isRecord(value.error) ? { error: value.error } : {}
4974
+ };
4975
+ }
4976
+ function isCompactInspectorCommandStatus(value) {
4977
+ return value === "success" || value === "error";
4978
+ }
4979
+ function isRecord(value) {
4980
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
4981
+ }
4435
4982
 
4436
4983
  // src/commands/inspector.ts
4437
4984
  function addInspectorUrlOption(command) {