@mcpjam/cli 3.3.0 → 3.3.1

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
@@ -3,7 +3,7 @@ import { Command, CommanderError } from 'commander';
3
3
  import { realpathSync, readFileSync, existsSync, closeSync, mkdirSync, writeFileSync, renameSync, statSync, openSync } from 'fs';
4
4
  import { pathToFileURL, fileURLToPath } from 'url';
5
5
  import { probeMcpServer, runServerDoctor, collectServerSnapshot, serializeStableServerSnapshot, serializeServerSnapshot, buildServerDiffReport, validateToolCallResult, isCallToolResultError, buildToolCallValidationReport, listResources, readResource, listPrompts, getPrompt, MCPAppsConformanceTest, MCPAppsConformanceSuite, runOAuthLogin, OAuthConformanceTest, OAuthConformanceSuite, MCPConformanceTest, MCPConformanceSuite, redactSensitiveValue, withEphemeralClient, diffServerSnapshots, ServerSnapshotFormatError, renderStructuredRunJUnitXml, renderStructuredRunJson, 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';
6
+ import { mkdir, writeFile, chmod, readFile, rename, rm } from 'fs/promises';
7
7
  import path2, { join, dirname } from 'path';
8
8
  import { randomUUID } from 'crypto';
9
9
  import { PostHog } from 'posthog-node';
@@ -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.2.1"};
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
+ );
1376
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
+ };
1407
+ }
1408
+ return redacted;
1377
1409
  }
1378
1410
  async function writeCommandDebugArtifact(options, dependencies = {}) {
1379
1411
  if (!options.outputPath) {
@@ -1387,10 +1419,7 @@ async function writeCommandDebugArtifact(options, dependencies = {}) {
1387
1419
  outcome: options.outcome,
1388
1420
  snapshot: snapshotResult.snapshot,
1389
1421
  snapshotError: snapshotResult.snapshotError,
1390
- collectors: [
1391
- ...options.collectors ?? [],
1392
- options.snapshot?.collector
1393
- ]
1422
+ collectors: [...options.collectors ?? [], options.snapshot?.collector]
1394
1423
  });
1395
1424
  const artifactPath = await writeDebugArtifact(options.outputPath, payload);
1396
1425
  if (options.format === "human" && !options.quiet) {
@@ -1436,8 +1465,12 @@ async function writeDebugArtifact(outputPath, payload) {
1436
1465
  resolvedPath,
1437
1466
  `${JSON.stringify(redactedPayload, null, 2)}
1438
1467
  `,
1439
- "utf8"
1468
+ {
1469
+ encoding: "utf8",
1470
+ mode: 384
1471
+ }
1440
1472
  );
1473
+ await chmod(resolvedPath, 384);
1441
1474
  } catch (error) {
1442
1475
  throw operationalError(
1443
1476
  `Failed to write debug artifact to "${resolvedPath}".`,
@@ -1572,6 +1605,7 @@ function extractHeaders(headers) {
1572
1605
  // src/commands/oauth.ts
1573
1606
  var DYNAMIC_CLIENT_ID_PLACEHOLDER = "__dynamic_registration_client__";
1574
1607
  var DYNAMIC_CLIENT_SECRET_PLACEHOLDER = "__dynamic_registration_secret__";
1608
+ var DEFAULT_OAUTH_STEP_TIMEOUT_MS = 12e4;
1575
1609
  function getOAuthFormat(command) {
1576
1610
  const opts = command.optsWithGlobals();
1577
1611
  return resolveOAuthOutputFormat(opts.format, process.stdout.isTTY);
@@ -1588,6 +1622,28 @@ function writeOAuthOutput(output) {
1588
1622
  process.stdout.write(output.endsWith("\n") ? output : `${output}
1589
1623
  `);
1590
1624
  }
1625
+ function createOAuthProgressReporter(quiet) {
1626
+ let wroteInlineProgress = false;
1627
+ return {
1628
+ onProgress(message) {
1629
+ if (quiet) {
1630
+ return;
1631
+ }
1632
+ if (process.stderr.isTTY) {
1633
+ wroteInlineProgress = true;
1634
+ process.stderr.write(`\r\x1B[K${message}`);
1635
+ return;
1636
+ }
1637
+ process.stderr.write(`${message}
1638
+ `);
1639
+ },
1640
+ clear() {
1641
+ if (!quiet && process.stderr.isTTY && wroteInlineProgress) {
1642
+ process.stderr.write("\r\x1B[K");
1643
+ }
1644
+ }
1645
+ };
1646
+ }
1591
1647
  function buildOAuthLoginDebugOutcome(options) {
1592
1648
  if (options.commandError !== void 0) {
1593
1649
  return {
@@ -1641,35 +1697,28 @@ function registerOAuthCommands(program) {
1641
1697
  "--step-timeout <ms>",
1642
1698
  "Per-step timeout in milliseconds",
1643
1699
  (value) => parsePositiveInteger(value, "Step timeout"),
1644
- 3e4
1700
+ DEFAULT_OAUTH_STEP_TIMEOUT_MS
1645
1701
  ).option(
1646
1702
  "--verify-tools",
1647
1703
  "After OAuth succeeds, verify the token by listing MCP tools"
1648
1704
  ).option(
1649
1705
  "--verify-call-tool <name>",
1650
1706
  "After listing tools, also call the named tool"
1651
- ).option(
1652
- "--debug-out <path>",
1653
- "Write a structured debug artifact to a file"
1654
- ).option(
1707
+ ).option("--debug-out <path>", "Write a structured debug artifact to a file").option(
1655
1708
  "--credentials-out <path>",
1656
1709
  "Write OAuth credentials to <path> (mode 0600); stdout output has secret fields redacted to [SAVED_TO_FILE]"
1710
+ ).option(
1711
+ "--print-url",
1712
+ "In interactive mode, print the consent URL to stderr instead of launching a browser"
1657
1713
  ).action(async (options, command) => {
1658
1714
  const globalOptions = getGlobalOptions(command);
1659
1715
  const format = getOAuthFormat(command);
1660
- const config = buildOAuthLoginConfig(
1661
- options,
1662
- {
1663
- defaultAuthMode: "interactive"
1664
- }
1665
- );
1716
+ const config = buildOAuthLoginConfig(options, {
1717
+ defaultAuthMode: "interactive"
1718
+ });
1666
1719
  const snapshotCollector = options.debugOut ? createCliRpcLogCollector({ __cli__: config.serverUrl }) : void 0;
1667
- const isTTY = process.stderr.isTTY && !globalOptions.quiet;
1668
- if (isTTY) {
1669
- config.onProgress = (message) => {
1670
- process.stderr.write(`\r\x1B[K${message}`);
1671
- };
1672
- }
1720
+ const progress = createOAuthProgressReporter(globalOptions.quiet);
1721
+ config.onProgress = progress.onProgress;
1673
1722
  let result;
1674
1723
  let commandError;
1675
1724
  try {
@@ -1677,9 +1726,7 @@ function registerOAuthCommands(program) {
1677
1726
  } catch (error) {
1678
1727
  commandError = error;
1679
1728
  } finally {
1680
- if (isTTY) {
1681
- process.stderr.write("\r\x1B[K");
1682
- }
1729
+ progress.clear();
1683
1730
  }
1684
1731
  const snapshotConfig = buildOAuthLoginSnapshotConfig(config, result);
1685
1732
  const target = summarizeServerDoctorTarget(
@@ -1690,14 +1737,20 @@ function registerOAuthCommands(program) {
1690
1737
  let credentialsFileError;
1691
1738
  if (commandError === void 0 && result && options.credentialsOut && hasCredentialsToSave(result)) {
1692
1739
  try {
1740
+ progress.onProgress("Saving OAuth credentials...");
1693
1741
  credentialsFilePath = await writeCredentialsFile(
1694
1742
  options.credentialsOut,
1695
1743
  result
1696
1744
  );
1745
+ progress.onProgress(
1746
+ `OAuth credentials saved to ${credentialsFilePath}.`
1747
+ );
1697
1748
  } catch (error) {
1698
1749
  credentialsFileError = error;
1750
+ progress.onProgress("Failed to save OAuth credentials.");
1699
1751
  }
1700
1752
  }
1753
+ progress.clear();
1701
1754
  await writeCommandDebugArtifact({
1702
1755
  outputPath: options.debugOut,
1703
1756
  format,
@@ -1716,7 +1769,7 @@ function registerOAuthCommands(program) {
1716
1769
  input: {
1717
1770
  config: snapshotConfig,
1718
1771
  target,
1719
- timeout: config.stepTimeout ?? 3e4
1772
+ timeout: config.stepTimeout ?? DEFAULT_OAUTH_STEP_TIMEOUT_MS
1720
1773
  },
1721
1774
  collector: snapshotCollector
1722
1775
  } : void 0
@@ -1725,7 +1778,10 @@ function registerOAuthCommands(program) {
1725
1778
  throw commandError;
1726
1779
  }
1727
1780
  if (!result) {
1728
- throw cliError("INTERNAL_ERROR", "OAuth login did not return a result.");
1781
+ throw cliError(
1782
+ "INTERNAL_ERROR",
1783
+ "OAuth login did not return a result."
1784
+ );
1729
1785
  }
1730
1786
  if (options.credentialsOut) {
1731
1787
  writeResult(
@@ -1764,7 +1820,7 @@ function registerOAuthCommands(program) {
1764
1820
  "--step-timeout <ms>",
1765
1821
  "Per-step timeout in milliseconds",
1766
1822
  (value) => parsePositiveInteger(value, "Step timeout"),
1767
- 3e4
1823
+ DEFAULT_OAUTH_STEP_TIMEOUT_MS
1768
1824
  ).option(
1769
1825
  "--verify-tools",
1770
1826
  "After OAuth succeeds, verify the token by listing MCP tools"
@@ -1774,6 +1830,9 @@ function registerOAuthCommands(program) {
1774
1830
  ).option(
1775
1831
  "--conformance-checks",
1776
1832
  "Run additional OAuth negative checks (invalid client, invalid redirect, token format) after the main flow"
1833
+ ).option(
1834
+ "--credentials-out <path>",
1835
+ "Write OAuth credentials to <path> (mode 0600); stdout output has secret fields redacted to [SAVED_TO_FILE]"
1777
1836
  ).option(
1778
1837
  "--print-url",
1779
1838
  "In interactive mode, print the consent URL to stderr instead of launching a browser"
@@ -1781,13 +1840,34 @@ function registerOAuthCommands(program) {
1781
1840
  "--reporter <reporter>",
1782
1841
  "Structured reporter output: json-summary or junit-xml"
1783
1842
  ).action(async (options, command) => {
1784
- const reporter = parseReporterFormat(options.reporter);
1843
+ const reporter = parseReporterFormat(
1844
+ options.reporter
1845
+ );
1785
1846
  const format = getOAuthConformanceFormat(command, reporter);
1786
- const config = buildOAuthConformanceConfig(options);
1847
+ const config = buildOAuthConformanceConfig(
1848
+ options
1849
+ );
1787
1850
  const result = await new OAuthConformanceTest(config).run();
1851
+ let credentialsFilePath;
1852
+ let credentialsFileError;
1853
+ if (options.credentialsOut && hasCredentialsToSave(result)) {
1854
+ try {
1855
+ credentialsFilePath = await writeCredentialsFile(
1856
+ options.credentialsOut,
1857
+ result
1858
+ );
1859
+ } catch (error) {
1860
+ credentialsFileError = error;
1861
+ }
1862
+ }
1788
1863
  writeOAuthOutput(
1789
- reporter ? renderConformanceReporterResult(result, reporter) : renderOAuthConformanceResult(result, format)
1864
+ reporter ? renderConformanceReporterResult(result, reporter) : renderOAuthConformanceResult(result, format, {
1865
+ credentialsFilePath
1866
+ })
1790
1867
  );
1868
+ if (credentialsFileError) {
1869
+ throw credentialsFileError;
1870
+ }
1791
1871
  if (!result.passed) {
1792
1872
  setProcessExitCode(1);
1793
1873
  }
@@ -1800,11 +1880,16 @@ function registerOAuthCommands(program) {
1800
1880
  ).option(
1801
1881
  "--verify-call-tool <name>",
1802
1882
  "Also call the named tool after listing"
1883
+ ).option(
1884
+ "--credentials-out <path>",
1885
+ "Write OAuth credentials from the first flow that returns credentials to <path> (mode 0600)"
1803
1886
  ).option(
1804
1887
  "--reporter <reporter>",
1805
1888
  "Structured reporter output: json-summary or junit-xml"
1806
1889
  ).action(async (options, command) => {
1807
- const reporter = parseReporterFormat(options.reporter);
1890
+ const reporter = parseReporterFormat(
1891
+ options.reporter
1892
+ );
1808
1893
  const format = getOAuthConformanceFormat(command, reporter);
1809
1894
  const config = loadOAuthSuiteConfig(options.config);
1810
1895
  if (options.verifyTools || options.verifyCallTool) {
@@ -1817,14 +1902,36 @@ function registerOAuthCommands(program) {
1817
1902
  }
1818
1903
  config.defaults = {
1819
1904
  ...config.defaults,
1820
- verification: { ...config.defaults?.verification, ...cliVerification }
1905
+ verification: {
1906
+ ...config.defaults?.verification,
1907
+ ...cliVerification
1908
+ }
1821
1909
  };
1822
1910
  }
1823
1911
  const suite = new OAuthConformanceSuite(config);
1824
1912
  const result = await suite.run();
1913
+ const credentialsResultIndex = findCredentialsResultIndex(result);
1914
+ let credentialsFilePath;
1915
+ let credentialsFileError;
1916
+ if (options.credentialsOut && credentialsResultIndex !== void 0) {
1917
+ try {
1918
+ credentialsFilePath = await writeCredentialsFile(
1919
+ options.credentialsOut,
1920
+ result.results[credentialsResultIndex]
1921
+ );
1922
+ } catch (error) {
1923
+ credentialsFileError = error;
1924
+ }
1925
+ }
1825
1926
  writeOAuthOutput(
1826
- reporter ? renderConformanceReporterResult(result, reporter) : renderOAuthConformanceSuiteResult(result, format)
1927
+ reporter ? renderConformanceReporterResult(result, reporter) : renderOAuthConformanceSuiteResult(result, format, {
1928
+ credentialsFilePath,
1929
+ credentialsResultIndex
1930
+ })
1827
1931
  );
1932
+ if (credentialsFileError) {
1933
+ throw credentialsFileError;
1934
+ }
1828
1935
  if (!result.passed) {
1829
1936
  setProcessExitCode(1);
1830
1937
  }
@@ -1923,7 +2030,12 @@ function buildOAuthConformanceConfig(options, defaults) {
1923
2030
  listTools: options.verifyTools ?? !!options.verifyCallTool,
1924
2031
  ...options.verifyCallTool ? { callTool: { name: options.verifyCallTool } } : {}
1925
2032
  } : void 0;
1926
- const auth = buildAuthConfig(authMode, registrationStrategy, clientId, clientSecret);
2033
+ const auth = buildAuthConfig(
2034
+ authMode,
2035
+ registrationStrategy,
2036
+ clientId,
2037
+ clientSecret
2038
+ );
1927
2039
  if (options.printUrl && auth.mode === "interactive") {
1928
2040
  auth.openUrl = async (url) => {
1929
2041
  process.stderr.write(`OAUTH_CONSENT_URL: ${url}
@@ -1939,11 +2051,15 @@ function buildOAuthConformanceConfig(options, defaults) {
1939
2051
  scopes: options.scopes?.trim() || void 0,
1940
2052
  customHeaders,
1941
2053
  redirectUrl,
1942
- stepTimeout: options.stepTimeout ?? 3e4,
2054
+ stepTimeout: options.stepTimeout ?? DEFAULT_OAUTH_STEP_TIMEOUT_MS,
1943
2055
  verification,
1944
2056
  oauthConformanceChecks: options.conformanceChecks ?? false
1945
2057
  };
1946
2058
  }
2059
+ function findCredentialsResultIndex(result) {
2060
+ const index = result.results.findIndex(hasCredentialsToSave);
2061
+ return index >= 0 ? index : void 0;
2062
+ }
1947
2063
  function buildOAuthLoginConfig(options, defaults) {
1948
2064
  const serverUrl = options.url.trim();
1949
2065
  assertValidUrl2(serverUrl, "server URL");
@@ -2025,7 +2141,7 @@ function buildOAuthLoginConfig(options, defaults) {
2025
2141
  scopes: options.scopes?.trim() || void 0,
2026
2142
  customHeaders,
2027
2143
  redirectUrl,
2028
- stepTimeout: options.stepTimeout ?? 3e4,
2144
+ stepTimeout: options.stepTimeout ?? DEFAULT_OAUTH_STEP_TIMEOUT_MS,
2029
2145
  verification,
2030
2146
  oauthConformanceChecks: false
2031
2147
  };
@@ -2046,14 +2162,14 @@ function summarizeOAuthLoginCommandInput(options) {
2046
2162
  hasClientSecret: Boolean(options.clientSecret),
2047
2163
  verifyTools: options.verifyTools ?? false,
2048
2164
  verifyCallTool: options.verifyCallTool ?? void 0,
2049
- stepTimeout: options.stepTimeout ?? 3e4
2165
+ stepTimeout: options.stepTimeout ?? DEFAULT_OAUTH_STEP_TIMEOUT_MS
2050
2166
  };
2051
2167
  }
2052
2168
  function buildOAuthLoginSnapshotConfig(config, result) {
2053
2169
  const baseConfig = {
2054
2170
  url: config.serverUrl,
2055
2171
  ...config.customHeaders ? { requestInit: { headers: config.customHeaders } } : {},
2056
- timeout: config.stepTimeout ?? 3e4
2172
+ timeout: config.stepTimeout ?? DEFAULT_OAUTH_STEP_TIMEOUT_MS
2057
2173
  };
2058
2174
  if (!result) {
2059
2175
  return baseConfig;
@@ -2104,7 +2220,9 @@ function parseProtocolVersion(value) {
2104
2220
  return value;
2105
2221
  }
2106
2222
  throw usageError(
2107
- `Invalid protocol version "${value}". Use ${[...VALID_PROTOCOL_VERSIONS].join(", ")}.`
2223
+ `Invalid protocol version "${value}". Use ${[
2224
+ ...VALID_PROTOCOL_VERSIONS
2225
+ ].join(", ")}.`
2108
2226
  );
2109
2227
  }
2110
2228
  function parseRequiredProtocolVersion(value) {
@@ -2120,14 +2238,14 @@ function parseRegistrationStrategy(value) {
2120
2238
  return value;
2121
2239
  }
2122
2240
  throw usageError(
2123
- `Invalid registration strategy "${value}". Use ${[...VALID_REGISTRATION_STRATEGIES].join(", ")}.`
2241
+ `Invalid registration strategy "${value}". Use ${[
2242
+ ...VALID_REGISTRATION_STRATEGIES
2243
+ ].join(", ")}.`
2124
2244
  );
2125
2245
  }
2126
2246
  function parseRequiredRegistrationStrategy(value) {
2127
2247
  if (!value) {
2128
- throw usageError(
2129
- "--registration is required for oauth conformance flows."
2130
- );
2248
+ throw usageError("--registration is required for oauth conformance flows.");
2131
2249
  }
2132
2250
  return parseRegistrationStrategy(value);
2133
2251
  }
@@ -2397,7 +2515,7 @@ function registerServerCommands(program) {
2397
2515
  "OAuth bearer access token for HTTP servers"
2398
2516
  ).option(
2399
2517
  "--credentials-file <path>",
2400
- "Load OAuth access token from a file created by oauth login --credentials-out"
2518
+ "Load OAuth access token from a file created by oauth login or oauth conformance --credentials-out"
2401
2519
  ).option(
2402
2520
  "--header <header>",
2403
2521
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
@@ -3557,9 +3675,13 @@ var DEFAULT_COMMAND_TIMEOUT_MS = 3e4;
3557
3675
  var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
3558
3676
  var COMMAND_FETCH_TIMEOUT_BUFFER_MS = 2e3;
3559
3677
  var HEALTH_FETCH_TIMEOUT_MS = 2e3;
3678
+ var FRONTEND_PROBE_TIMEOUT_MS = 750;
3679
+ var ORIGIN_PROBE_TIMEOUT_MS = 750;
3560
3680
  var SESSION_TOKEN_TIMEOUT_MS = 3e3;
3561
3681
  var STOP_FETCH_TIMEOUT_MS = 3e3;
3562
3682
  var STARTUP_LOG_MAX_BYTES = 1024 * 1024;
3683
+ var FRONTEND_PORT_SCAN_WINDOW = 10;
3684
+ var WELL_KNOWN_FRONTEND_PORTS = [5173, 5174, 5175, 8080];
3563
3685
  var TOKEN_TTL_MS = 5 * 6e4;
3564
3686
  var tokenCache = /* @__PURE__ */ new Map();
3565
3687
  var tokenRequests = /* @__PURE__ */ new Map();
@@ -3596,23 +3718,167 @@ function normalizeInspectorFrontendUrl(frontendUrl) {
3596
3718
  return void 0;
3597
3719
  }
3598
3720
  }
3599
- function buildInspectorBrowserUrl(baseUrl, frontendUrl, tab) {
3600
- return buildInspectorUrl(
3601
- normalizeInspectorFrontendUrl(frontendUrl) ?? baseUrl,
3602
- tab
3721
+ function normalizeExplicitInspectorFrontendUrl(frontendUrl) {
3722
+ const normalized = normalizeInspectorFrontendUrl(frontendUrl);
3723
+ if (!normalized) {
3724
+ throw operationalError(`Invalid Inspector frontend URL "${frontendUrl}".`);
3725
+ }
3726
+ return normalized;
3727
+ }
3728
+ function canonicalizeInspectorFrontendUrl(baseUrl, frontendUrl) {
3729
+ if (!frontendUrl) {
3730
+ return void 0;
3731
+ }
3732
+ try {
3733
+ const base = new URL(baseUrl);
3734
+ const frontend = new URL(frontendUrl);
3735
+ if (isLoopbackHostname(base.hostname) && isLoopbackHostname(frontend.hostname) && base.protocol === frontend.protocol && getEffectiveUrlPort(base) === getEffectiveUrlPort(frontend)) {
3736
+ return baseUrl;
3737
+ }
3738
+ } catch {
3739
+ return frontendUrl;
3740
+ }
3741
+ return frontendUrl;
3742
+ }
3743
+ function getEffectiveUrlPort(url) {
3744
+ if (url.port) {
3745
+ return url.port;
3746
+ }
3747
+ return url.protocol === "https:" ? "443" : "80";
3748
+ }
3749
+ async function resolveInspectorBrowserBaseUrl(baseUrl, frontendUrl, options = {}) {
3750
+ const fastResolution = await resolveInspectorBrowserBaseUrlFast(
3751
+ baseUrl,
3752
+ frontendUrl
3753
+ );
3754
+ if (fastResolution.browserBaseUrl) {
3755
+ return fastResolution.browserBaseUrl;
3756
+ }
3757
+ if (options.skipDiscovery) {
3758
+ assertFastFrontendMismatch(fastResolution.candidates);
3759
+ return fastResolution.normalizedFrontendUrl ?? baseUrl;
3760
+ }
3761
+ const discoveredCandidates = await discoverLocalInspectorFrontendCandidates(
3762
+ baseUrl,
3763
+ fastResolution.normalizedFrontendUrl
3764
+ );
3765
+ const usableDiscoveredCandidate = discoveredCandidates.find(
3766
+ isUsableInspectorFrontendCandidate
3767
+ );
3768
+ if (usableDiscoveredCandidate) {
3769
+ return usableDiscoveredCandidate.url;
3770
+ }
3771
+ const candidates = [...fastResolution.candidates, ...discoveredCandidates];
3772
+ assertFullFrontendMismatch(candidates);
3773
+ return fastResolution.normalizedFrontendUrl ?? baseUrl;
3774
+ }
3775
+ async function resolveInspectorBrowserBaseUrlFast(baseUrl, frontendUrl) {
3776
+ const normalizedFrontendUrl = canonicalizeInspectorFrontendUrl(
3777
+ baseUrl,
3778
+ normalizeInspectorFrontendUrl(frontendUrl)
3779
+ );
3780
+ const targets = [];
3781
+ if (normalizedFrontendUrl) {
3782
+ targets.push({ source: "advertised", url: normalizedFrontendUrl });
3783
+ }
3784
+ if (!targets.some((target) => target.url === baseUrl)) {
3785
+ targets.push({ source: "base", url: baseUrl });
3786
+ }
3787
+ const candidates = await inspectInspectorFrontendCandidates(
3788
+ baseUrl,
3789
+ targets
3790
+ );
3791
+ const usableCandidate = candidates.find(isUsableInspectorFrontendCandidate);
3792
+ return {
3793
+ ...usableCandidate ? { browserBaseUrl: usableCandidate.url } : {},
3794
+ candidates,
3795
+ ...normalizedFrontendUrl ? { normalizedFrontendUrl } : {}
3796
+ };
3797
+ }
3798
+ async function inspectInspectorFrontendCandidates(apiBaseUrl, targets) {
3799
+ const settled = await Promise.allSettled(
3800
+ targets.map(
3801
+ (target) => inspectInspectorFrontendCandidate(apiBaseUrl, target.url, target.source)
3802
+ )
3803
+ );
3804
+ return settled.map((result, index) => {
3805
+ if (result.status === "fulfilled") {
3806
+ return result.value;
3807
+ }
3808
+ const target = targets[index];
3809
+ return {
3810
+ isFrontend: false,
3811
+ originStatus: "unknown",
3812
+ source: target.source,
3813
+ url: target.url
3814
+ };
3815
+ });
3816
+ }
3817
+ function assertFastFrontendMismatch(candidates) {
3818
+ const advertisedCandidate = candidates.find(
3819
+ (candidate) => candidate.source === "advertised"
3820
+ );
3821
+ const rejectedLiveCandidate = candidates.find(
3822
+ (candidate) => candidate.isFrontend && candidate.originStatus === "rejected"
3823
+ );
3824
+ if (!rejectedLiveCandidate) {
3825
+ return;
3826
+ }
3827
+ if (advertisedCandidate === rejectedLiveCandidate) {
3828
+ throw frontendMismatchError(void 0, rejectedLiveCandidate);
3829
+ }
3830
+ throw frontendMismatchError(advertisedCandidate, rejectedLiveCandidate);
3831
+ }
3832
+ function assertFullFrontendMismatch(candidates) {
3833
+ const advertisedCandidate = candidates.find(
3834
+ (candidate) => candidate.source === "advertised"
3603
3835
  );
3836
+ const rejectedLiveCandidate = candidates.find(
3837
+ (candidate) => candidate !== advertisedCandidate && candidate.isFrontend && candidate.originStatus === "rejected"
3838
+ );
3839
+ if (advertisedCandidate?.isFrontend && advertisedCandidate.originStatus === "rejected") {
3840
+ throw frontendMismatchError(void 0, advertisedCandidate);
3841
+ }
3842
+ if (advertisedCandidate && !advertisedCandidate.isFrontend && advertisedCandidate.originStatus === "accepted") {
3843
+ throw frontendMismatchError(advertisedCandidate, rejectedLiveCandidate);
3844
+ }
3845
+ if (rejectedLiveCandidate) {
3846
+ throw frontendMismatchError(advertisedCandidate, rejectedLiveCandidate);
3847
+ }
3848
+ }
3849
+ async function resolveInspectorBrowserBaseUrlForHealth(baseUrl, frontendUrl, options) {
3850
+ try {
3851
+ return await resolveInspectorBrowserBaseUrl(baseUrl, frontendUrl, {
3852
+ skipDiscovery: options.skipDiscovery
3853
+ });
3854
+ } catch (error) {
3855
+ if (options.hasActiveClient && !options.openBrowser) {
3856
+ return canonicalizeInspectorFrontendUrl(
3857
+ baseUrl,
3858
+ normalizeInspectorFrontendUrl(frontendUrl)
3859
+ ) ?? baseUrl;
3860
+ }
3861
+ throw error;
3862
+ }
3604
3863
  }
3605
3864
  async function ensureInspector(options = {}) {
3606
3865
  const baseUrl = normalizeInspectorBaseUrl(options.baseUrl);
3866
+ const explicitFrontendUrl = options.frontendUrl !== void 0 ? normalizeExplicitInspectorFrontendUrl(options.frontendUrl) : void 0;
3607
3867
  const health = await getInspectorHealth(baseUrl);
3608
3868
  if (health.healthy) {
3609
- const url2 = buildInspectorBrowserUrl(baseUrl, health.frontendUrl, options.tab);
3869
+ const browserBaseUrl2 = explicitFrontendUrl ?? await resolveInspectorBrowserBaseUrlForHealth(baseUrl, health.frontendUrl, {
3870
+ hasActiveClient: health.hasActiveClient,
3871
+ openBrowser: options.openBrowser === true,
3872
+ skipDiscovery: options.skipDiscovery
3873
+ });
3874
+ const url2 = buildInspectorUrl(browserBaseUrl2, options.tab);
3610
3875
  if (options.openBrowser && !health.hasActiveClient) {
3611
3876
  openUrl(url2);
3612
3877
  }
3613
3878
  return {
3614
3879
  baseUrl,
3615
- ...health.frontendUrl ? { frontendUrl: health.frontendUrl } : {},
3880
+ ...browserBaseUrl2 !== baseUrl ? { frontendUrl: browserBaseUrl2 } : {},
3881
+ hasActiveClient: health.hasActiveClient,
3616
3882
  url: url2,
3617
3883
  started: false
3618
3884
  };
@@ -3625,17 +3891,23 @@ async function ensureInspector(options = {}) {
3625
3891
  await startInspector(baseUrl, options.timeoutMs ?? DEFAULT_START_TIMEOUT_MS);
3626
3892
  clearInspectorSessionTokenCache(baseUrl);
3627
3893
  const startedHealth = await getInspectorHealth(baseUrl);
3628
- const url = buildInspectorBrowserUrl(
3894
+ const browserBaseUrl = explicitFrontendUrl ?? await resolveInspectorBrowserBaseUrlForHealth(
3629
3895
  baseUrl,
3630
3896
  startedHealth.frontendUrl,
3631
- options.tab
3897
+ {
3898
+ hasActiveClient: startedHealth.hasActiveClient,
3899
+ openBrowser: options.openBrowser === true,
3900
+ skipDiscovery: options.skipDiscovery
3901
+ }
3632
3902
  );
3903
+ const url = buildInspectorUrl(browserBaseUrl, options.tab);
3633
3904
  if (options.openBrowser) {
3634
3905
  openUrl(url);
3635
3906
  }
3636
3907
  return {
3637
3908
  baseUrl,
3638
- ...startedHealth.frontendUrl ? { frontendUrl: startedHealth.frontendUrl } : {},
3909
+ ...browserBaseUrl !== baseUrl ? { frontendUrl: browserBaseUrl } : {},
3910
+ hasActiveClient: startedHealth.hasActiveClient,
3639
3911
  url,
3640
3912
  started: true
3641
3913
  };
@@ -3881,6 +4153,177 @@ async function getInspectorHealth(baseUrl, timeoutMs = HEALTH_FETCH_TIMEOUT_MS)
3881
4153
  return { healthy: false, hasActiveClient: false };
3882
4154
  }
3883
4155
  }
4156
+ async function isInspectorFrontendUrl(baseUrl) {
4157
+ try {
4158
+ const response = await fetch(`${baseUrl}/`, {
4159
+ signal: AbortSignal.timeout(FRONTEND_PROBE_TIMEOUT_MS)
4160
+ });
4161
+ if (!response.ok) {
4162
+ return false;
4163
+ }
4164
+ const contentType = response.headers.get("content-type") ?? "";
4165
+ if (!contentType.toLowerCase().includes("text/html")) {
4166
+ return false;
4167
+ }
4168
+ const body = await response.text();
4169
+ return hasInspectorFrontendMarker(body) || /<title>\s*MCPJam Inspector\s*<\/title>/i.test(body) || body.includes("/mcp_jam.svg") || body.includes("__MCP_SESSION_TOKEN__");
4170
+ } catch {
4171
+ return false;
4172
+ }
4173
+ }
4174
+ function hasInspectorFrontendMarker(body) {
4175
+ return /<meta\b(?=[^>]*\bname=["']mcpjam-inspector["'])[^>]*>/i.test(body);
4176
+ }
4177
+ async function inspectInspectorFrontendCandidate(apiBaseUrl, frontendBaseUrl, source) {
4178
+ const [isFrontend, originStatus] = await Promise.all([
4179
+ isInspectorFrontendUrl(frontendBaseUrl),
4180
+ getInspectorApiOriginStatus(apiBaseUrl, frontendBaseUrl)
4181
+ ]);
4182
+ return {
4183
+ isFrontend,
4184
+ originStatus,
4185
+ source,
4186
+ url: frontendBaseUrl
4187
+ };
4188
+ }
4189
+ function isUsableInspectorFrontendCandidate(candidate) {
4190
+ return candidate.isFrontend && candidate.originStatus !== "rejected";
4191
+ }
4192
+ async function getInspectorApiOriginStatus(apiBaseUrl, frontendBaseUrl) {
4193
+ try {
4194
+ const origin = new URL(frontendBaseUrl).origin;
4195
+ const response = await fetch(`${apiBaseUrl}/api/session-token`, {
4196
+ headers: { Origin: origin },
4197
+ signal: AbortSignal.timeout(ORIGIN_PROBE_TIMEOUT_MS)
4198
+ });
4199
+ return response.status === 403 ? "rejected" : "accepted";
4200
+ } catch {
4201
+ return "unknown";
4202
+ }
4203
+ }
4204
+ function frontendMismatchError(advertisedCandidate, rejectedLiveCandidate) {
4205
+ const details = {
4206
+ ...advertisedCandidate ? {
4207
+ advertisedFrontendUrl: advertisedCandidate.url,
4208
+ advertisedFrontendReachable: advertisedCandidate.isFrontend,
4209
+ advertisedOriginStatus: advertisedCandidate.originStatus
4210
+ } : {},
4211
+ ...rejectedLiveCandidate ? {
4212
+ rejectedFrontendUrl: rejectedLiveCandidate.url,
4213
+ rejectedOriginStatus: rejectedLiveCandidate.originStatus
4214
+ } : {}
4215
+ };
4216
+ if (advertisedCandidate && rejectedLiveCandidate) {
4217
+ return operationalError(
4218
+ `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.`,
4219
+ details
4220
+ );
4221
+ }
4222
+ if (advertisedCandidate) {
4223
+ return operationalError(
4224
+ `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.`,
4225
+ details
4226
+ );
4227
+ }
4228
+ return operationalError(
4229
+ `Inspector frontend ${rejectedLiveCandidate?.url ?? "URL"} is reachable, but the Inspector backend rejects that origin. Restart Inspector with matching frontend/backend ports.`,
4230
+ details
4231
+ );
4232
+ }
4233
+ async function discoverLocalInspectorFrontendCandidates(baseUrl, frontendUrl) {
4234
+ const hosts = getLocalInspectorCandidateHosts(baseUrl, frontendUrl);
4235
+ if (hosts.length === 0) {
4236
+ return [];
4237
+ }
4238
+ const protocol = getUrlProtocol(frontendUrl) ?? getUrlProtocol(baseUrl) ?? "http:";
4239
+ const targets = [];
4240
+ for (const port of getFrontendProbePorts(frontendUrl)) {
4241
+ for (const host of hosts) {
4242
+ const candidate = `${protocol}//${formatUrlHostname(host)}:${port}`;
4243
+ if (candidate === frontendUrl || candidate === baseUrl) {
4244
+ continue;
4245
+ }
4246
+ targets.push(candidate);
4247
+ }
4248
+ }
4249
+ const inspectedCandidates = await inspectInspectorFrontendCandidates(
4250
+ baseUrl,
4251
+ targets.map((candidate) => ({
4252
+ source: "discovered",
4253
+ url: candidate
4254
+ }))
4255
+ );
4256
+ return inspectedCandidates.filter((candidate) => candidate.isFrontend);
4257
+ }
4258
+ function getLocalInspectorCandidateHosts(baseUrl, frontendUrl) {
4259
+ const hosts = /* @__PURE__ */ new Set();
4260
+ for (const value of [frontendUrl, baseUrl]) {
4261
+ const hostname = getUrlHostname(value);
4262
+ if (!hostname || !isLoopbackHostname(hostname)) {
4263
+ continue;
4264
+ }
4265
+ hosts.add(hostname);
4266
+ if (hostname === "localhost") {
4267
+ hosts.add("127.0.0.1");
4268
+ }
4269
+ if (hostname === "127.0.0.1") {
4270
+ hosts.add("localhost");
4271
+ }
4272
+ }
4273
+ return [...hosts];
4274
+ }
4275
+ function getFrontendProbePorts(frontendUrl) {
4276
+ const ports = /* @__PURE__ */ new Set();
4277
+ const hintedPort = getUrlPort(frontendUrl);
4278
+ if (hintedPort) {
4279
+ ports.add(hintedPort);
4280
+ for (let offset = 1; offset <= FRONTEND_PORT_SCAN_WINDOW; offset += 1) {
4281
+ ports.add(hintedPort + offset);
4282
+ }
4283
+ }
4284
+ for (const port of WELL_KNOWN_FRONTEND_PORTS) {
4285
+ ports.add(port);
4286
+ }
4287
+ return [...ports].filter((port) => port > 0 && port < 65536);
4288
+ }
4289
+ function getUrlHostname(value) {
4290
+ if (!value) {
4291
+ return void 0;
4292
+ }
4293
+ try {
4294
+ return new URL(value).hostname.toLowerCase();
4295
+ } catch {
4296
+ return void 0;
4297
+ }
4298
+ }
4299
+ function getUrlProtocol(value) {
4300
+ if (!value) {
4301
+ return void 0;
4302
+ }
4303
+ try {
4304
+ return new URL(value).protocol;
4305
+ } catch {
4306
+ return void 0;
4307
+ }
4308
+ }
4309
+ function getUrlPort(value) {
4310
+ if (!value) {
4311
+ return void 0;
4312
+ }
4313
+ try {
4314
+ const parsed = new URL(value);
4315
+ const port = Number(parsed.port);
4316
+ return Number.isInteger(port) && port > 0 ? port : void 0;
4317
+ } catch {
4318
+ return void 0;
4319
+ }
4320
+ }
4321
+ function isLoopbackHostname(hostname) {
4322
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]";
4323
+ }
4324
+ function formatUrlHostname(hostname) {
4325
+ return hostname.includes(":") && !hostname.startsWith("[") ? `[${hostname}]` : hostname;
4326
+ }
3884
4327
  async function isInspectorHealthy(baseUrl) {
3885
4328
  const status = await getInspectorHealth(baseUrl);
3886
4329
  return status.healthy;
@@ -4004,12 +4447,25 @@ function isInspectorCommandResponse(value) {
4004
4447
  // src/lib/inspector-render.ts
4005
4448
  async function runUiRender(options) {
4006
4449
  const client = new InspectorApiClient({ baseUrl: options.baseUrl });
4450
+ const openBrowser = options.openBrowser === true;
4007
4451
  const ensureResult = await client.ensure({
4008
- openBrowser: true,
4009
- startIfNeeded: true,
4452
+ frontendUrl: options.frontendUrl,
4453
+ openBrowser,
4454
+ skipDiscovery: options.skipDiscovery,
4455
+ startIfNeeded: options.startIfNeeded ?? true,
4010
4456
  tab: "app-builder",
4011
4457
  timeoutMs: options.timeoutMs
4012
4458
  });
4459
+ if (!ensureResult.hasActiveClient && !openBrowser) {
4460
+ const startedNote = ensureResult.started ? " Inspector was just started by the CLI and is still running." : "";
4461
+ throw operationalError(
4462
+ `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.`,
4463
+ {
4464
+ inspectorBrowserUrl: ensureResult.url,
4465
+ inspectorStarted: ensureResult.started
4466
+ }
4467
+ );
4468
+ }
4013
4469
  await client.connectServer(options.serverName, options.config, {
4014
4470
  timeoutMs: options.timeoutMs
4015
4471
  });
@@ -4024,6 +4480,10 @@ async function runUiRender(options) {
4024
4480
  });
4025
4481
  return {
4026
4482
  baseUrl: ensureResult.baseUrl,
4483
+ browserUrl: ensureResult.url,
4484
+ ...ensureResult.frontendUrl ? { frontendUrl: ensureResult.frontendUrl } : {},
4485
+ browserOpenRequested: openBrowser,
4486
+ hasActiveClient: ensureResult.hasActiveClient,
4027
4487
  inspectorStarted: ensureResult.started,
4028
4488
  ...renderResult
4029
4489
  };
@@ -4234,7 +4694,16 @@ function registerToolsCommands(program) {
4234
4694
  ).option(
4235
4695
  "--debug-out <path>",
4236
4696
  "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(
4697
+ ).option("--ui", "Render the tool result in Inspector App Builder").option("--open", "Open Inspector in the system browser before rendering").option(
4698
+ "--no-open",
4699
+ "Start/use Inspector without opening a system browser"
4700
+ ).option(
4701
+ "--attach-only",
4702
+ "Require an already-running Inspector browser client; do not start or open Inspector"
4703
+ ).option("--inspector-url <url>", "Local Inspector base URL (with --ui)").option(
4704
+ "--frontend-url <url>",
4705
+ "Inspector frontend URL (with --ui; overrides health-advertised frontend and skips discovery)"
4706
+ ).option(
4238
4707
  "--server-name <name>",
4239
4708
  "Server name inside Inspector (with --ui)"
4240
4709
  ).option(
@@ -4278,6 +4747,9 @@ function registerToolsCommands(program) {
4278
4747
  if (options.ui && reporter) {
4279
4748
  throw usageError("--ui cannot be used together with --reporter.");
4280
4749
  }
4750
+ if (options.attachOnly && options.open === true) {
4751
+ throw usageError("--attach-only cannot be used together with --open.");
4752
+ }
4281
4753
  if (reporter && !shouldValidateResponse && !shouldExpectSuccess) {
4282
4754
  throw usageError(
4283
4755
  "--reporter requires --validate-response and/or --expect-success."
@@ -4290,6 +4762,7 @@ function registerToolsCommands(program) {
4290
4762
  locale: trimOptional(options.locale),
4291
4763
  timeZone: trimOptional(options.timeZone)
4292
4764
  } : void 0;
4765
+ const frontendUrl = options.ui ? parseInspectorFrontendUrl(options.frontendUrl) : void 0;
4293
4766
  let result;
4294
4767
  let commandError;
4295
4768
  const startedAt = Date.now();
@@ -4341,40 +4814,62 @@ function registerToolsCommands(program) {
4341
4814
  );
4342
4815
  const toolResultError = isCallToolResultError(result);
4343
4816
  let outputPayload = result;
4817
+ let debugOutputPayload = outputPayload;
4344
4818
  let inspectorRenderError;
4345
4819
  if (options.ui) {
4346
4820
  const serverName = typeof options.serverName === "string" && options.serverName.trim() ? options.serverName.trim() : buildInspectorServerName(options);
4821
+ const openBrowser = resolveInspectorOpenBrowser(options, globalOptions);
4822
+ const skipDiscovery = resolveInspectorSkipDiscovery(
4823
+ options,
4824
+ globalOptions
4825
+ );
4347
4826
  let uiResult;
4348
4827
  try {
4349
4828
  uiResult = await runUiRender({
4350
4829
  baseUrl: options.inspectorUrl,
4351
4830
  config,
4831
+ frontendUrl,
4832
+ openBrowser,
4352
4833
  params,
4353
4834
  renderContext,
4835
+ skipDiscovery,
4354
4836
  serverName,
4837
+ startIfNeeded: resolveInspectorStartIfNeeded(options),
4355
4838
  timeoutMs: globalOptions.timeout,
4356
4839
  toolName,
4357
4840
  toolResult: result
4358
4841
  });
4359
4842
  inspectorRenderError = findInspectorRenderError(uiResult);
4360
4843
  } catch (error) {
4361
- inspectorRenderError = toStructuredError(normalizeCliError(error)).error;
4844
+ inspectorRenderError = toStructuredError(
4845
+ normalizeCliError(error)
4846
+ ).error;
4362
4847
  uiResult = {
4363
4848
  status: "error",
4364
- error: inspectorRenderError
4849
+ error: inspectorRenderError,
4850
+ ...extractInspectorRenderErrorUrls(inspectorRenderError)
4365
4851
  };
4366
4852
  }
4367
- outputPayload = {
4853
+ const compactInspectorRender = buildCompactInspectorRender(uiResult);
4854
+ const compactOutputPayload = {
4368
4855
  success: !inspectorRenderError && !validationFailed && !toolResultError,
4369
4856
  command: "tools call",
4370
4857
  inspectorUi: true,
4858
+ ...typeof compactInspectorRender.browserUrl === "string" ? { inspectorBrowserUrl: compactInspectorRender.browserUrl } : {},
4859
+ ...typeof compactInspectorRender.frontendUrl === "string" ? { inspectorFrontendUrl: compactInspectorRender.frontendUrl } : {},
4371
4860
  target,
4372
4861
  toolName,
4373
- params,
4862
+ parameterKeys: Object.keys(params),
4374
4863
  result,
4375
- inspectorRender: uiResult,
4864
+ inspectorRender: compactInspectorRender,
4376
4865
  ...inspectorRenderError ? { error: inspectorRenderError } : {}
4377
4866
  };
4867
+ outputPayload = compactOutputPayload;
4868
+ debugOutputPayload = {
4869
+ ...compactOutputPayload,
4870
+ params,
4871
+ inspectorRender: uiResult
4872
+ };
4378
4873
  }
4379
4874
  await writeCommandDebugArtifact({
4380
4875
  outputPath: options.debugOut,
@@ -4389,10 +4884,10 @@ function registerToolsCommands(program) {
4389
4884
  outcome: inspectorRenderError ? {
4390
4885
  status: "error",
4391
4886
  error: inspectorRenderError,
4392
- result: outputPayload
4887
+ result: debugOutputPayload
4393
4888
  } : {
4394
4889
  status: "success",
4395
- result: outputPayload
4890
+ result: debugOutputPayload
4396
4891
  },
4397
4892
  snapshot: options.debugOut ? {
4398
4893
  input: {
@@ -4432,6 +4927,98 @@ function registerToolsCommands(program) {
4432
4927
  }
4433
4928
  });
4434
4929
  }
4930
+ function resolveInspectorOpenBrowser(options, globalOptions) {
4931
+ if (options.attachOnly) {
4932
+ return false;
4933
+ }
4934
+ if (options.open !== void 0) {
4935
+ return options.open;
4936
+ }
4937
+ return globalOptions.format === "human" && !globalOptions.quiet;
4938
+ }
4939
+ function parseInspectorFrontendUrl(value) {
4940
+ if (value === void 0) {
4941
+ return void 0;
4942
+ }
4943
+ const frontendUrl = normalizeInspectorFrontendUrl(value);
4944
+ if (!frontendUrl) {
4945
+ throw usageError(`Invalid --frontend-url "${value}".`);
4946
+ }
4947
+ return frontendUrl;
4948
+ }
4949
+ function resolveInspectorSkipDiscovery(options, globalOptions) {
4950
+ if (typeof options.frontendUrl === "string" && options.frontendUrl.trim()) {
4951
+ return true;
4952
+ }
4953
+ if (options.attachOnly) {
4954
+ return true;
4955
+ }
4956
+ if ((globalOptions.format === "json" || globalOptions.quiet) && options.open !== true) {
4957
+ return true;
4958
+ }
4959
+ if (options.open === true) {
4960
+ return false;
4961
+ }
4962
+ return false;
4963
+ }
4964
+ function resolveInspectorStartIfNeeded(options) {
4965
+ return options.attachOnly !== true;
4966
+ }
4967
+ function extractInspectorRenderErrorUrls(error) {
4968
+ if (!error.details || typeof error.details !== "object") {
4969
+ return {};
4970
+ }
4971
+ const details = error.details;
4972
+ return {
4973
+ ...typeof details.inspectorBrowserUrl === "string" ? { browserUrl: details.inspectorBrowserUrl } : {},
4974
+ ...typeof details.inspectorFrontendUrl === "string" ? { frontendUrl: details.inspectorFrontendUrl } : {}
4975
+ };
4976
+ }
4977
+ function buildCompactInspectorRender(uiResult) {
4978
+ const commands = {};
4979
+ let hasCommandError = false;
4980
+ for (const [commandName, commandValue] of Object.entries(uiResult)) {
4981
+ const response = compactInspectorCommandResponse(commandValue);
4982
+ if (!response) {
4983
+ continue;
4984
+ }
4985
+ commands[commandName] = response;
4986
+ if (response.status === "error") {
4987
+ hasCommandError = true;
4988
+ }
4989
+ }
4990
+ const topLevelError = uiResult.status === "error" && isRecord(uiResult.error) ? { error: uiResult.error } : {};
4991
+ return {
4992
+ status: hasCommandError || uiResult.status === "error" ? "error" : "rendered",
4993
+ // Contract metadata: renders target the active client and fresh tabs do not
4994
+ // hydrate this injected state.
4995
+ mode: "active-client",
4996
+ urlHydratesRender: false,
4997
+ ...typeof uiResult.baseUrl === "string" ? { baseUrl: uiResult.baseUrl } : {},
4998
+ ...typeof uiResult.browserUrl === "string" ? { browserUrl: uiResult.browserUrl } : {},
4999
+ ...typeof uiResult.frontendUrl === "string" ? { frontendUrl: uiResult.frontendUrl } : {},
5000
+ ...typeof uiResult.inspectorStarted === "boolean" ? { inspectorStarted: uiResult.inspectorStarted } : {},
5001
+ ...typeof uiResult.browserOpenRequested === "boolean" ? { browserOpenRequested: uiResult.browserOpenRequested } : {},
5002
+ ...typeof uiResult.hasActiveClient === "boolean" ? { hasActiveClient: uiResult.hasActiveClient } : {},
5003
+ ...Object.keys(commands).length > 0 ? { commands } : {},
5004
+ ...topLevelError
5005
+ };
5006
+ }
5007
+ function compactInspectorCommandResponse(value) {
5008
+ if (!isRecord(value) || !isCompactInspectorCommandStatus(value.status)) {
5009
+ return void 0;
5010
+ }
5011
+ return {
5012
+ status: value.status,
5013
+ ...value.status === "error" && isRecord(value.error) ? { error: value.error } : {}
5014
+ };
5015
+ }
5016
+ function isCompactInspectorCommandStatus(value) {
5017
+ return value === "success" || value === "error";
5018
+ }
5019
+ function isRecord(value) {
5020
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
5021
+ }
4435
5022
 
4436
5023
  // src/commands/inspector.ts
4437
5024
  function addInspectorUrlOption(command) {