@mcpjam/cli 3.4.0 → 3.6.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
@@ -2,17 +2,22 @@
2
2
  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
- import { probeMcpServer, redactSensitiveValue, runServerDoctor, collectServerSnapshot, serializeStableServerSnapshot, serializeServerSnapshot, buildServerDiffReport, validateToolCallResult, isCallToolResultError, buildToolCallValidationReport, listResources, readResource, listPrompts, getPrompt, MCPAppsConformanceTest, MCPAppsConformanceSuite, runOAuthLogin, OAuthConformanceTest, OAuthConformanceSuite, MCPConformanceTest, MCPConformanceSuite, 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';
5
+ import { probeMcpServer, redactSensitiveValue, runServerDoctor, collectServerSnapshot, serializeStableServerSnapshot, serializeServerSnapshot, buildServerDiffReport, validateToolCallResult, isCallToolResultError, buildToolCallValidationReport, listResources, readResource, listPrompts, getPrompt, MCPAppsConformanceTest, MCPAppsConformanceSuite, runOAuthLogin, OAuthConformanceTest, OAuthConformanceSuite, MCPConformanceTest, MCPConformanceSuite, withEphemeralClient, diffServerSnapshots, ServerSnapshotFormatError, renderStructuredRunJUnitXml, renderStructuredRunJson, toConformanceReport, renderConformanceReportJUnitXml, renderConformanceReportJson, formatOAuthConformanceHuman, formatOAuthConformanceSuiteHuman, fetchOAuthMetadata, executeOAuthProxy, executeDebugOAuthProxy, generateRandomString, generateCodeChallenge, createInteractiveAuthorizationSession, openUrlInBrowser, MCPClientManager, MCP_APPS_CHECK_CATEGORIES, MCP_APPS_CHECK_IDS, OAuthProxyError, MCP_CHECK_CATEGORIES, MCP_CHECK_IDS } from '@mcpjam/sdk';
6
6
  import { mkdir, writeFile, readFile, chmod, rename, rm } from 'fs/promises';
7
- import path2, { join, dirname } from 'path';
7
+ import path2, { join, dirname, basename } from 'path';
8
8
  import { randomUUID } from 'crypto';
9
+ import os, { homedir } from 'os';
10
+ import { createTunnelOperation, DEFAULT_PLATFORM_API_BASE_URL, PlatformApiClient, isPlatformApiError, PlatformApiError, listProjectsOperation, listProjectServersOperation, showServersOperation } from '@mcpjam/sdk/platform';
9
11
  import { PostHog } from 'posthog-node';
10
12
  import { spawn } from 'child_process';
11
- import os, { homedir } from 'os';
13
+ import http from 'http';
14
+ import https from 'https';
15
+ import { once } from 'events';
16
+ import { WebSocket } from 'ws';
12
17
 
13
18
  // package.json
14
19
  var package_default = {
15
- version: "3.4.0"};
20
+ version: "3.6.0"};
16
21
 
17
22
  // src/lib/output.ts
18
23
  var DEFAULT_OUTPUT_FORMAT = "json";
@@ -1243,6 +1248,638 @@ function buildAppsConformanceConfig(options) {
1243
1248
  ...resolvedCheckIds && resolvedCheckIds.length > 0 ? { checkIds: resolvedCheckIds } : {}
1244
1249
  };
1245
1250
  }
1251
+ var AUTH_STORE_VERSION = 1;
1252
+ function getAuthFilePath(options = {}) {
1253
+ const env = options.env ?? process.env;
1254
+ const platform = options.platform ?? process.platform;
1255
+ const homeDirectory = options.homeDirectory ?? homedir();
1256
+ if (env.MCPJAM_AUTH_FILE) {
1257
+ return env.MCPJAM_AUTH_FILE;
1258
+ }
1259
+ if (platform === "win32") {
1260
+ return join(
1261
+ env.APPDATA || join(homeDirectory, "AppData", "Roaming"),
1262
+ "mcpjam",
1263
+ "auth.json"
1264
+ );
1265
+ }
1266
+ return join(
1267
+ env.XDG_CONFIG_HOME || join(homeDirectory, ".config"),
1268
+ "mcpjam",
1269
+ "auth.json"
1270
+ );
1271
+ }
1272
+ function readStoredAuth(filePath) {
1273
+ let raw;
1274
+ try {
1275
+ raw = readFileSync(filePath, "utf8");
1276
+ } catch {
1277
+ return null;
1278
+ }
1279
+ let parsed;
1280
+ try {
1281
+ parsed = JSON.parse(raw);
1282
+ } catch {
1283
+ return null;
1284
+ }
1285
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1286
+ return null;
1287
+ }
1288
+ const record = parsed;
1289
+ if (record.version !== AUTH_STORE_VERSION || typeof record.issuer !== "string" || typeof record.clientId !== "string" || typeof record.tokenEndpoint !== "string" || typeof record.accessToken !== "string") {
1290
+ return null;
1291
+ }
1292
+ return {
1293
+ version: AUTH_STORE_VERSION,
1294
+ issuer: record.issuer,
1295
+ clientId: record.clientId,
1296
+ tokenEndpoint: record.tokenEndpoint,
1297
+ accessToken: record.accessToken,
1298
+ // Hand-edited files may hold a non-URL; dropping it here means readers
1299
+ // fall back to the default base URL instead of producing broken requests.
1300
+ ...typeof record.apiUrl === "string" && URL.canParse(record.apiUrl) ? { apiUrl: record.apiUrl } : {},
1301
+ ...typeof record.refreshToken === "string" ? { refreshToken: record.refreshToken } : {},
1302
+ ...typeof record.expiresAt === "number" ? { expiresAt: record.expiresAt } : {}
1303
+ };
1304
+ }
1305
+ async function writeStoredAuth(contents, filePath) {
1306
+ const directory = dirname(filePath);
1307
+ const temporaryPath = join(
1308
+ directory,
1309
+ `.${basename(filePath)}.${randomUUID()}.tmp`
1310
+ );
1311
+ try {
1312
+ await mkdir(directory, { recursive: true });
1313
+ await writeFile(temporaryPath, `${JSON.stringify(contents, null, 2)}
1314
+ `, {
1315
+ encoding: "utf8",
1316
+ mode: 384
1317
+ });
1318
+ await chmod(temporaryPath, 384);
1319
+ await rename(temporaryPath, filePath);
1320
+ } catch (error) {
1321
+ await rm(temporaryPath, { force: true }).catch(() => void 0);
1322
+ throw operationalError(`Failed to write credentials to "${filePath}".`, {
1323
+ source: error instanceof Error ? error.message : String(error)
1324
+ });
1325
+ }
1326
+ return filePath;
1327
+ }
1328
+ async function clearStoredAuth(filePath) {
1329
+ const existed = readStoredAuth(filePath) !== null;
1330
+ await rm(filePath, { force: true });
1331
+ return existed;
1332
+ }
1333
+
1334
+ // src/lib/platform-auth.ts
1335
+ var LEGACY_API_KEY_PREFIX = "mcpjam_";
1336
+ var TOKEN_REFRESH_SKEW_MS = 6e4;
1337
+ var DEFAULT_LOGIN_TIMEOUT_MS = 5 * 6e4;
1338
+ var LEGACY_KEY_REMEDY = "Legacy mcpjam_ API keys are not supported by platform commands. Create an sk_ key at https://app.mcpjam.com/settings/api-keys or run `mcpjam login`.";
1339
+ function resolvePlatformCredential(options, deps = {}) {
1340
+ const env = deps.env ?? process.env;
1341
+ const warn = deps.warn ?? ((message) => process.stderr.write(`${message}
1342
+ `));
1343
+ const flagKey = options.apiKey?.trim();
1344
+ if (flagKey) {
1345
+ if (flagKey.startsWith(LEGACY_API_KEY_PREFIX)) {
1346
+ throw usageError(LEGACY_KEY_REMEDY);
1347
+ }
1348
+ return { kind: "api-key", getAuth: async () => flagKey };
1349
+ }
1350
+ const envKey = env.MCPJAM_API_KEY?.trim();
1351
+ if (envKey) {
1352
+ if (!envKey.startsWith(LEGACY_API_KEY_PREFIX)) {
1353
+ return { kind: "api-key", getAuth: async () => envKey };
1354
+ }
1355
+ warn(
1356
+ `Ignoring legacy mcpjam_ key in MCPJAM_API_KEY for this command. ${LEGACY_KEY_REMEDY}`
1357
+ );
1358
+ }
1359
+ const authFilePath = deps.authFilePath ?? getAuthFilePath({ env });
1360
+ return {
1361
+ kind: "oauth",
1362
+ getAuth: () => getOAuthAccessToken({
1363
+ authFilePath,
1364
+ fetchFn: deps.fetchFn,
1365
+ now: deps.now
1366
+ })
1367
+ };
1368
+ }
1369
+ async function getOAuthAccessToken(deps) {
1370
+ const stored = readStoredAuth(deps.authFilePath);
1371
+ if (!stored) {
1372
+ throw operationalError(
1373
+ "Not logged in. Run `mcpjam login`, or pass an sk_ API key via --api-key / MCPJAM_API_KEY."
1374
+ );
1375
+ }
1376
+ const now = deps.now ?? Date.now;
1377
+ const expiresSoon = stored.expiresAt !== void 0 && stored.expiresAt - now() <= TOKEN_REFRESH_SKEW_MS;
1378
+ if (!expiresSoon) {
1379
+ return stored.accessToken;
1380
+ }
1381
+ if (!stored.refreshToken) {
1382
+ throw operationalError("Login expired. Run `mcpjam login` again.");
1383
+ }
1384
+ const refreshed = await refreshStoredAuth(stored, deps);
1385
+ return refreshed.accessToken;
1386
+ }
1387
+ async function refreshStoredAuth(stored, deps) {
1388
+ const tokens = await exchangeToken(
1389
+ stored.tokenEndpoint,
1390
+ {
1391
+ grant_type: "refresh_token",
1392
+ client_id: stored.clientId,
1393
+ refresh_token: stored.refreshToken
1394
+ },
1395
+ deps.fetchFn ?? fetch,
1396
+ "Token refresh failed. Run `mcpjam login` again.",
1397
+ deps.now
1398
+ );
1399
+ const refreshed = {
1400
+ ...stored,
1401
+ accessToken: tokens.accessToken,
1402
+ // AuthKit rotates refresh tokens; keep the old one only if none returned.
1403
+ ...tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {},
1404
+ ...tokens.expiresAt !== void 0 ? { expiresAt: tokens.expiresAt } : {}
1405
+ };
1406
+ await writeStoredAuth(refreshed, deps.authFilePath);
1407
+ return refreshed;
1408
+ }
1409
+ async function runPlatformLogin(target, deps = {}) {
1410
+ const fetchFn = deps.fetchFn ?? fetch;
1411
+ const config = await fetchCliAuthConfig(target.origin, fetchFn);
1412
+ const codeVerifier = generateRandomString(64);
1413
+ const state = generateRandomString(32);
1414
+ const codeChallenge = await generateCodeChallenge(codeVerifier);
1415
+ const session = await (deps.createSession ?? createInteractiveAuthorizationSession)();
1416
+ let code;
1417
+ try {
1418
+ const authorizationUrl = new URL(config.authStartUrl);
1419
+ authorizationUrl.searchParams.set("redirect_uri", session.redirectUrl);
1420
+ authorizationUrl.searchParams.set("state", state);
1421
+ authorizationUrl.searchParams.set("code_challenge", codeChallenge);
1422
+ authorizationUrl.searchParams.set("code_challenge_method", "S256");
1423
+ ({ code } = await session.authorize({
1424
+ authorizationUrl: authorizationUrl.toString(),
1425
+ expectedState: state,
1426
+ timeoutMs: deps.timeoutMs ?? DEFAULT_LOGIN_TIMEOUT_MS,
1427
+ openUrl: deps.openUrl ?? openUrlInBrowser
1428
+ }));
1429
+ } finally {
1430
+ await session.stop().catch(() => void 0);
1431
+ }
1432
+ const tokens = await exchangeToken(
1433
+ config.tokenEndpoint,
1434
+ {
1435
+ grant_type: "authorization_code",
1436
+ client_id: config.clientId,
1437
+ code,
1438
+ redirect_uri: config.redirectUri,
1439
+ code_verifier: codeVerifier
1440
+ },
1441
+ fetchFn,
1442
+ "Login failed during the token exchange.",
1443
+ deps.now
1444
+ );
1445
+ if (!tokens.refreshToken) {
1446
+ throw operationalError(
1447
+ "AuthKit did not return a refresh token, so this login could not be saved. Ensure the CLI OAuth client allows the offline_access scope, or use an sk_ API key instead."
1448
+ );
1449
+ }
1450
+ const authFilePath = deps.authFilePath ?? getAuthFilePath();
1451
+ await writeStoredAuth(
1452
+ {
1453
+ version: 1,
1454
+ issuer: config.issuer,
1455
+ clientId: config.clientId,
1456
+ tokenEndpoint: config.tokenEndpoint,
1457
+ apiUrl: target.apiUrl,
1458
+ accessToken: tokens.accessToken,
1459
+ refreshToken: tokens.refreshToken,
1460
+ ...tokens.expiresAt !== void 0 ? { expiresAt: tokens.expiresAt } : {}
1461
+ },
1462
+ authFilePath
1463
+ );
1464
+ return {
1465
+ authFilePath,
1466
+ issuer: config.issuer,
1467
+ ...tokens.expiresAt !== void 0 ? { expiresAt: tokens.expiresAt } : {}
1468
+ };
1469
+ }
1470
+ async function runPlatformLogout(authFilePath = getAuthFilePath()) {
1471
+ const loggedOut = await clearStoredAuth(authFilePath);
1472
+ return { loggedOut, authFilePath };
1473
+ }
1474
+ async function fetchCliAuthConfig(platformOrigin, fetchFn) {
1475
+ const configUrl = `${platformOrigin.replace(/\/+$/, "")}/api/cli/auth/config`;
1476
+ let response;
1477
+ try {
1478
+ response = await fetchFn(configUrl);
1479
+ } catch (error) {
1480
+ throw operationalError(
1481
+ `Could not reach ${configUrl}: ${error instanceof Error ? error.message : String(error)}`
1482
+ );
1483
+ }
1484
+ if (response.status === 501) {
1485
+ throw operationalError(
1486
+ `CLI login is not enabled on ${platformOrigin}. Use an sk_ API key via --api-key / MCPJAM_API_KEY instead.`
1487
+ );
1488
+ }
1489
+ if (!response.ok) {
1490
+ throw operationalError(
1491
+ `Fetching the login configuration from ${configUrl} failed (${response.status}).`
1492
+ );
1493
+ }
1494
+ const body = await response.json().catch(() => null);
1495
+ for (const field of [
1496
+ "issuer",
1497
+ "clientId",
1498
+ "authStartUrl",
1499
+ "tokenEndpoint",
1500
+ "redirectUri"
1501
+ ]) {
1502
+ if (typeof body?.[field] !== "string" || !body[field]) {
1503
+ throw operationalError(
1504
+ `The login configuration from ${configUrl} is missing "${field}".`
1505
+ );
1506
+ }
1507
+ }
1508
+ return {
1509
+ issuer: body.issuer,
1510
+ clientId: body.clientId,
1511
+ authStartUrl: body.authStartUrl,
1512
+ tokenEndpoint: body.tokenEndpoint,
1513
+ redirectUri: body.redirectUri
1514
+ };
1515
+ }
1516
+ async function exchangeToken(tokenEndpoint, params, fetchFn, failureMessage, now = Date.now) {
1517
+ let response;
1518
+ try {
1519
+ response = await fetchFn(tokenEndpoint, {
1520
+ method: "POST",
1521
+ headers: { "content-type": "application/x-www-form-urlencoded" },
1522
+ body: new URLSearchParams(params).toString()
1523
+ });
1524
+ } catch (error) {
1525
+ throw operationalError(
1526
+ `${failureMessage} Could not reach ${tokenEndpoint}: ${error instanceof Error ? error.message : String(error)}`
1527
+ );
1528
+ }
1529
+ const body = await response.json().catch(() => null);
1530
+ if (!response.ok || typeof body?.access_token !== "string") {
1531
+ const detail = typeof body?.error_description === "string" ? body.error_description : typeof body?.error === "string" ? body.error : `HTTP ${response.status}`;
1532
+ throw operationalError(`${failureMessage} (${detail})`);
1533
+ }
1534
+ return {
1535
+ accessToken: body.access_token,
1536
+ ...typeof body.refresh_token === "string" ? { refreshToken: body.refresh_token } : {},
1537
+ ...typeof body.expires_in === "number" && Number.isFinite(body.expires_in) ? { expiresAt: now() + body.expires_in * 1e3 } : {}
1538
+ };
1539
+ }
1540
+ function validateApiUrl(value, source) {
1541
+ let parsed;
1542
+ try {
1543
+ parsed = new URL(value);
1544
+ } catch {
1545
+ throw usageError(
1546
+ `Invalid ${source} value "${value}". Expected a full URL like ${DEFAULT_PLATFORM_API_BASE_URL}.`
1547
+ );
1548
+ }
1549
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
1550
+ throw usageError(
1551
+ `Invalid ${source} value "${value}". Expected an http(s) URL like ${DEFAULT_PLATFORM_API_BASE_URL}.`
1552
+ );
1553
+ }
1554
+ return value;
1555
+ }
1556
+ function resolveExplicitApiUrl(options, env) {
1557
+ const flagUrl = options.apiUrl?.trim();
1558
+ if (flagUrl) {
1559
+ return validateApiUrl(flagUrl, "--api-url");
1560
+ }
1561
+ const envUrl = env.MCPJAM_API_URL?.trim();
1562
+ if (envUrl) {
1563
+ return validateApiUrl(envUrl, "MCPJAM_API_URL");
1564
+ }
1565
+ return void 0;
1566
+ }
1567
+ function resolvePlatformBaseUrl(options, env = process.env) {
1568
+ return resolveExplicitApiUrl(options, env) ?? DEFAULT_PLATFORM_API_BASE_URL;
1569
+ }
1570
+ function resolvePlatformOrigin(options, env = process.env) {
1571
+ return new URL(resolvePlatformBaseUrl(options, env)).origin;
1572
+ }
1573
+ function buildPlatformClient(options, deps = {}) {
1574
+ const env = deps.env ?? process.env;
1575
+ const credential = resolvePlatformCredential(options, deps);
1576
+ let baseUrl = resolveExplicitApiUrl(options, env);
1577
+ if (!baseUrl && credential.kind === "oauth") {
1578
+ const stored = readStoredAuth(deps.authFilePath ?? getAuthFilePath({ env }));
1579
+ baseUrl = stored?.apiUrl;
1580
+ }
1581
+ const client = new PlatformApiClient({
1582
+ baseUrl: baseUrl ?? DEFAULT_PLATFORM_API_BASE_URL,
1583
+ getAuth: credential.getAuth,
1584
+ ...deps.fetchFn ? { fetch: deps.fetchFn } : {},
1585
+ ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
1586
+ userAgent: `mcpjam-cli/${package_default.version}`
1587
+ });
1588
+ return { client, credentialKind: credential.kind };
1589
+ }
1590
+ function toCliError(error) {
1591
+ if (error instanceof CliError) {
1592
+ return error;
1593
+ }
1594
+ if (isPlatformApiError(error)) {
1595
+ const message = error.code === "UNAUTHORIZED" ? `${error.message} Run \`mcpjam login\` or pass a valid sk_ API key.` : error.message;
1596
+ return cliError(error.code, message, 1, error.details);
1597
+ }
1598
+ return cliError(
1599
+ "INTERNAL_ERROR",
1600
+ error instanceof Error ? error.message : String(error)
1601
+ );
1602
+ }
1603
+
1604
+ // src/commands/auth.ts
1605
+ function registerAuthCommands(program) {
1606
+ program.command("login").description(
1607
+ "Log in to MCPJam. Opens your browser for OAuth and stores the session locally."
1608
+ ).option(
1609
+ "--api-url <url>",
1610
+ "MCPJam API base URL (defaults to https://app.mcpjam.com/api/v1)"
1611
+ ).option(
1612
+ "--no-browser",
1613
+ "Print the login URL instead of opening a browser"
1614
+ ).action(async (options, command) => {
1615
+ const globalOptions = getGlobalOptions(command);
1616
+ const apiUrl = resolvePlatformBaseUrl(options);
1617
+ const origin = resolvePlatformOrigin(options);
1618
+ const result = await runPlatformLogin({ origin, apiUrl }, {
1619
+ ...options.browser === false ? {
1620
+ openUrl: async (url) => {
1621
+ process.stderr.write(
1622
+ `Open this URL in your browser to continue:
1623
+
1624
+ ${url}
1625
+
1626
+ `
1627
+ );
1628
+ }
1629
+ } : {}
1630
+ });
1631
+ writeResult(
1632
+ {
1633
+ status: "logged_in",
1634
+ issuer: result.issuer,
1635
+ authFile: result.authFilePath,
1636
+ ...result.expiresAt !== void 0 ? { expiresAt: new Date(result.expiresAt).toISOString() } : {}
1637
+ },
1638
+ globalOptions.format
1639
+ );
1640
+ });
1641
+ program.command("logout").description("Remove the stored MCPJam login.").action(async (_options, command) => {
1642
+ const globalOptions = getGlobalOptions(command);
1643
+ const result = await runPlatformLogout();
1644
+ writeResult(
1645
+ {
1646
+ status: result.loggedOut ? "logged_out" : "not_logged_in",
1647
+ authFile: result.authFilePath
1648
+ },
1649
+ globalOptions.format
1650
+ );
1651
+ });
1652
+ program.command("whoami").description("Show the MCPJam account behind the current credentials.").option("--api-key <key>", "MCPJam sk_ API key (overrides MCPJAM_API_KEY)").option(
1653
+ "--api-url <url>",
1654
+ "MCPJam API base URL (defaults to https://app.mcpjam.com/api/v1)"
1655
+ ).action(async (options, command) => {
1656
+ const globalOptions = getGlobalOptions(command);
1657
+ try {
1658
+ const { client, credentialKind } = buildPlatformClient(options);
1659
+ const me = await client.getMe();
1660
+ writeResult(
1661
+ {
1662
+ id: me.id,
1663
+ email: me.email,
1664
+ name: me.name,
1665
+ ...me.plan ? { plan: me.plan } : {},
1666
+ credential: credentialKind
1667
+ },
1668
+ globalOptions.format
1669
+ );
1670
+ } catch (error) {
1671
+ throw toCliError(error);
1672
+ }
1673
+ });
1674
+ }
1675
+
1676
+ // src/lib/projects-render.ts
1677
+ function formatTimestamp(value) {
1678
+ return typeof value === "number" ? new Date(value).toISOString() : "-";
1679
+ }
1680
+ function table(rows) {
1681
+ if (rows.length === 0) {
1682
+ return [];
1683
+ }
1684
+ const widths = rows[0].map(
1685
+ (_cell, column) => Math.max(...rows.map((row) => row[column]?.length ?? 0))
1686
+ );
1687
+ return rows.map(
1688
+ (row) => row.map(
1689
+ (cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])
1690
+ ).join(" ").trimEnd()
1691
+ );
1692
+ }
1693
+ function formatProjectsHuman(projects) {
1694
+ if (projects.length === 0) {
1695
+ return "No accessible projects.";
1696
+ }
1697
+ const lines = table([
1698
+ ["ID", "NAME", "UPDATED"],
1699
+ ...projects.map((project) => [
1700
+ project.id,
1701
+ project.name,
1702
+ formatTimestamp(project.updatedAt)
1703
+ ])
1704
+ ]);
1705
+ lines.push("", `${projects.length} project(s).`);
1706
+ return lines.join("\n");
1707
+ }
1708
+ function formatProjectServersHuman(result) {
1709
+ const lines = [`Project: ${result.project.name} (${result.project.id})`, ""];
1710
+ if (result.items.length === 0) {
1711
+ lines.push("No servers in this project.");
1712
+ } else {
1713
+ lines.push(
1714
+ ...table([
1715
+ ["ID", "NAME", "TRANSPORT", "URL", "ENABLED"],
1716
+ ...result.items.map((server) => [
1717
+ server.id,
1718
+ server.name,
1719
+ server.transportType,
1720
+ server.url ?? "-",
1721
+ server.enabled ? "yes" : "no"
1722
+ ])
1723
+ ])
1724
+ );
1725
+ }
1726
+ appendOtherProjects(lines, result.otherProjects);
1727
+ return lines.join("\n");
1728
+ }
1729
+ function formatShowServersHuman(payload) {
1730
+ const lines = [
1731
+ `Project: ${payload.project.name} (${payload.project.id})`,
1732
+ ""
1733
+ ];
1734
+ if (payload.servers.length === 0) {
1735
+ lines.push("No servers in this project.");
1736
+ } else {
1737
+ for (const server of payload.servers) {
1738
+ const headline = `${statusGlyph(server.status)} ${server.name} [${server.status}]`;
1739
+ lines.push(server.url ? `${headline} ${server.url}` : headline);
1740
+ if (server.statusDetail) {
1741
+ lines.push(` ${server.statusDetail}`);
1742
+ }
1743
+ if (server.serverInfo?.name || server.serverInfo?.version) {
1744
+ lines.push(
1745
+ ` Server: ${server.serverInfo.name ?? "unknown"}${server.serverInfo.version ? ` v${server.serverInfo.version}` : ""}`
1746
+ );
1747
+ }
1748
+ if (server.primitives) {
1749
+ lines.push(
1750
+ ` Primitives: tools ${server.primitives.tools.items.length}, resources ${server.primitives.resources.items.length}, prompts ${server.primitives.prompts.items.length}`
1751
+ );
1752
+ }
1753
+ }
1754
+ }
1755
+ const summary = payload.summary;
1756
+ lines.push(
1757
+ "",
1758
+ `Summary: ${summary.reachable} reachable, ${summary.unreachable} unreachable, ${summary.skipped} skipped, ${summary.error} error(s).`
1759
+ );
1760
+ appendOtherProjects(lines, payload.otherProjects);
1761
+ lines.push(`Generated at ${payload.generatedAt}.`);
1762
+ return lines.join("\n");
1763
+ }
1764
+ function appendOtherProjects(lines, otherProjects) {
1765
+ if (otherProjects.length > 0) {
1766
+ lines.push(
1767
+ "",
1768
+ `Other projects: ${otherProjects.map((project) => project.name).join(", ")} (switch with --project)`
1769
+ );
1770
+ }
1771
+ }
1772
+ function statusGlyph(status) {
1773
+ switch (status) {
1774
+ case "reachable":
1775
+ return "\u2713";
1776
+ case "unreachable":
1777
+ return "\u2717";
1778
+ case "skipped":
1779
+ return "-";
1780
+ case "error":
1781
+ return "!";
1782
+ }
1783
+ }
1784
+
1785
+ // src/commands/projects.ts
1786
+ function addPlatformOptions(command) {
1787
+ return command.option("--api-key <key>", "MCPJam sk_ API key (overrides MCPJAM_API_KEY)").option(
1788
+ "--api-url <url>",
1789
+ "MCPJam API base URL (defaults to https://app.mcpjam.com/api/v1)"
1790
+ );
1791
+ }
1792
+ async function runPlatformCommand(options, timeoutMs, execute) {
1793
+ const controller = new AbortController();
1794
+ const timeoutHandle = setTimeout(() => {
1795
+ controller.abort(
1796
+ new PlatformApiError(
1797
+ `Request timed out after ${timeoutMs}ms`,
1798
+ "TIMEOUT",
1799
+ {
1800
+ status: 0
1801
+ }
1802
+ )
1803
+ );
1804
+ }, timeoutMs);
1805
+ timeoutHandle.unref?.();
1806
+ try {
1807
+ const { client } = buildPlatformClient({ ...options, timeoutMs });
1808
+ return await execute({ client, signal: controller.signal });
1809
+ } catch (error) {
1810
+ if (controller.signal.aborted && controller.signal.reason instanceof PlatformApiError) {
1811
+ throw toCliError(controller.signal.reason);
1812
+ }
1813
+ throw toCliError(error);
1814
+ } finally {
1815
+ clearTimeout(timeoutHandle);
1816
+ }
1817
+ }
1818
+ function registerProjectsCommands(program) {
1819
+ const projects = program.command("projects").description("Operate the MCP servers saved in your hosted MCPJam projects");
1820
+ addPlatformOptions(
1821
+ projects.command("list").description("List the projects you can access")
1822
+ ).action(async (options, command) => {
1823
+ const globalOptions = getGlobalOptions(command);
1824
+ const result = await runPlatformCommand(
1825
+ options,
1826
+ globalOptions.timeout,
1827
+ ({ client, signal }) => listProjectsOperation.execute({}, { client, signal })
1828
+ );
1829
+ if (globalOptions.format === "human") {
1830
+ process.stdout.write(`${formatProjectsHuman(result.items)}
1831
+ `);
1832
+ } else {
1833
+ writeResult(result, globalOptions.format);
1834
+ }
1835
+ });
1836
+ addPlatformOptions(
1837
+ projects.command("servers").description("List the servers saved in a project").option(
1838
+ "--project <id-or-name>",
1839
+ "Project name or ID (defaults to the most recently updated project)"
1840
+ )
1841
+ ).action(async (options, command) => {
1842
+ const globalOptions = getGlobalOptions(command);
1843
+ const result = await runPlatformCommand(
1844
+ options,
1845
+ globalOptions.timeout,
1846
+ ({ client, signal }) => listProjectServersOperation.execute(
1847
+ { project: options.project },
1848
+ { client, signal }
1849
+ )
1850
+ );
1851
+ if (globalOptions.format === "human") {
1852
+ process.stdout.write(`${formatProjectServersHuman(result)}
1853
+ `);
1854
+ } else {
1855
+ writeResult(result, globalOptions.format);
1856
+ }
1857
+ });
1858
+ addPlatformOptions(
1859
+ projects.command("status").description(
1860
+ "Health-check every server in a project (hosted doctor per server)"
1861
+ ).option(
1862
+ "--project <id-or-name>",
1863
+ "Project name or ID (defaults to the most recently updated project)"
1864
+ )
1865
+ ).action(async (options, command) => {
1866
+ const globalOptions = getGlobalOptions(command);
1867
+ const payload = await runPlatformCommand(
1868
+ options,
1869
+ globalOptions.timeout,
1870
+ ({ client, signal }) => showServersOperation.execute(
1871
+ { project: options.project },
1872
+ { client, signal }
1873
+ )
1874
+ );
1875
+ if (globalOptions.format === "human") {
1876
+ process.stdout.write(`${formatShowServersHuman(payload)}
1877
+ `);
1878
+ } else {
1879
+ writeResult(payload, globalOptions.format);
1880
+ }
1881
+ });
1882
+ }
1246
1883
  function registerProtocolCommands(program) {
1247
1884
  const protocol = program.command("protocol").description("MCP protocol inspection and conformance checks");
1248
1885
  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(
@@ -5203,6 +5840,1033 @@ function isCompactInspectorCommandStatus(value) {
5203
5840
  function isRecord(value) {
5204
5841
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
5205
5842
  }
5843
+ function tunnelPathPrefix(serverId) {
5844
+ return `/api/mcp/adapter-http/${encodeURIComponent(serverId)}`;
5845
+ }
5846
+ var NON_FORWARDED_REQUEST_HEADERS = /* @__PURE__ */ new Set([
5847
+ "host",
5848
+ "connection",
5849
+ "keep-alive",
5850
+ "proxy-authenticate",
5851
+ "proxy-authorization",
5852
+ "proxy-connection",
5853
+ "te",
5854
+ "trailer",
5855
+ "transfer-encoding",
5856
+ "upgrade"
5857
+ ]);
5858
+ var NON_FORWARDED_RESPONSE_HEADERS = /* @__PURE__ */ new Set([
5859
+ "connection",
5860
+ "keep-alive",
5861
+ "transfer-encoding"
5862
+ ]);
5863
+ function writeJson(res, status, payload) {
5864
+ const body = JSON.stringify(payload);
5865
+ res.writeHead(status, {
5866
+ "content-type": "application/json",
5867
+ "content-length": Buffer.byteLength(body)
5868
+ });
5869
+ res.end(body);
5870
+ }
5871
+ function matchTunnelPath(serverId, pathname) {
5872
+ const prefix = tunnelPathPrefix(serverId);
5873
+ if (pathname === prefix) return "";
5874
+ if (pathname.startsWith(`${prefix}/`)) return pathname.slice(prefix.length);
5875
+ return null;
5876
+ }
5877
+ function stripTunnelSecret(search) {
5878
+ const params = new URLSearchParams(search);
5879
+ params.delete("k");
5880
+ return params;
5881
+ }
5882
+ function buildUpstreamUrl(targetUrl, remainderPath, callerParams) {
5883
+ const upstream = new URL(targetUrl.toString());
5884
+ const basePath = upstream.pathname.replace(/\/+$/, "");
5885
+ upstream.pathname = remainderPath ? `${basePath}${remainderPath}` : upstream.pathname;
5886
+ for (const [name, value] of callerParams) {
5887
+ upstream.searchParams.append(name, value);
5888
+ }
5889
+ return upstream;
5890
+ }
5891
+ function proxyHttpRequest(req, res, upstreamUrl) {
5892
+ const requestFn = upstreamUrl.protocol === "https:" ? https.request : http.request;
5893
+ const headers = {};
5894
+ for (const [name, value] of Object.entries(req.headers)) {
5895
+ if (value === void 0 || NON_FORWARDED_REQUEST_HEADERS.has(name)) continue;
5896
+ headers[name] = value;
5897
+ }
5898
+ const upstream = requestFn(
5899
+ upstreamUrl,
5900
+ { method: req.method, headers },
5901
+ (upstreamRes) => {
5902
+ const responseHeaders = {};
5903
+ for (const [name, value] of Object.entries(upstreamRes.headers)) {
5904
+ if (value === void 0 || NON_FORWARDED_RESPONSE_HEADERS.has(name)) {
5905
+ continue;
5906
+ }
5907
+ responseHeaders[name] = value;
5908
+ }
5909
+ res.writeHead(upstreamRes.statusCode ?? 502, responseHeaders);
5910
+ upstreamRes.pipe(res);
5911
+ upstreamRes.on("error", () => res.destroy());
5912
+ }
5913
+ );
5914
+ upstream.on("error", (error) => {
5915
+ if (res.headersSent) {
5916
+ res.destroy();
5917
+ return;
5918
+ }
5919
+ writeJson(res, 502, {
5920
+ error: `Local target unreachable: ${error.message}`
5921
+ });
5922
+ });
5923
+ res.on("close", () => upstream.destroy());
5924
+ req.pipe(upstream);
5925
+ }
5926
+ async function handleFacadeJsonRpc(serverId, body, manager) {
5927
+ const id = body?.id ?? null;
5928
+ const method = body?.method;
5929
+ const params = body?.params ?? {};
5930
+ const respond = (payload) => ({
5931
+ jsonrpc: "2.0",
5932
+ id,
5933
+ ...payload
5934
+ });
5935
+ if (typeof method !== "string" || method.length === 0) {
5936
+ return respond({
5937
+ error: { code: -32600, message: "Invalid Request" }
5938
+ });
5939
+ }
5940
+ if (method.startsWith("notifications/")) {
5941
+ return null;
5942
+ }
5943
+ const respondError = (error) => respond({
5944
+ error: {
5945
+ code: typeof error?.code === "number" ? error.code : -32e3,
5946
+ message: error instanceof Error ? error.message : String(error)
5947
+ }
5948
+ });
5949
+ try {
5950
+ if (method === "ping") {
5951
+ return respond({ result: {} });
5952
+ }
5953
+ if (method === "initialize") {
5954
+ const info = manager.getInitializationInfo(serverId);
5955
+ const requested = typeof params?.protocolVersion === "string" ? params.protocolVersion : "2025-06-18";
5956
+ const result2 = {
5957
+ protocolVersion: info?.protocolVersion ?? requested,
5958
+ capabilities: info?.serverCapabilities ?? {},
5959
+ serverInfo: info?.serverVersion ?? {
5960
+ name: serverId,
5961
+ version: "mcpjam-tunnel"
5962
+ }
5963
+ };
5964
+ if (info?.instructions !== void 0) {
5965
+ result2.instructions = info.instructions;
5966
+ }
5967
+ return respond({ result: result2 });
5968
+ }
5969
+ const managed = manager.getManagedClient(serverId);
5970
+ if (!managed) {
5971
+ return respond({
5972
+ error: {
5973
+ code: -32e3,
5974
+ message: "Local MCP server is not connected (did the process exit?)"
5975
+ }
5976
+ });
5977
+ }
5978
+ const result = await managed.request({ method, params });
5979
+ return respond({ result: result ?? {} });
5980
+ } catch (error) {
5981
+ return respondError(error);
5982
+ }
5983
+ }
5984
+ async function readRequestBody(req) {
5985
+ const chunks = [];
5986
+ for await (const chunk of req) {
5987
+ chunks.push(chunk);
5988
+ }
5989
+ return Buffer.concat(chunks);
5990
+ }
5991
+ function handleStdioRequest(serverId, manager, req, res) {
5992
+ if (req.method !== "POST") {
5993
+ res.writeHead(405, { allow: "POST" });
5994
+ res.end();
5995
+ return;
5996
+ }
5997
+ void (async () => {
5998
+ let body;
5999
+ try {
6000
+ const raw = await readRequestBody(req);
6001
+ body = raw.byteLength > 0 ? JSON.parse(raw.toString("utf8")) : {};
6002
+ } catch {
6003
+ writeJson(res, 400, {
6004
+ jsonrpc: "2.0",
6005
+ id: null,
6006
+ error: { code: -32700, message: "Parse error" }
6007
+ });
6008
+ return;
6009
+ }
6010
+ if (Array.isArray(body)) {
6011
+ writeJson(res, 400, {
6012
+ jsonrpc: "2.0",
6013
+ id: null,
6014
+ error: { code: -32600, message: "Batch requests are not supported" }
6015
+ });
6016
+ return;
6017
+ }
6018
+ const response = await handleFacadeJsonRpc(
6019
+ serverId,
6020
+ body,
6021
+ manager
6022
+ );
6023
+ if (!response) {
6024
+ res.writeHead(202);
6025
+ res.end("Accepted");
6026
+ return;
6027
+ }
6028
+ writeJson(res, 200, response);
6029
+ })().catch(() => {
6030
+ if (!res.headersSent) {
6031
+ writeJson(res, 500, { error: "Bridge failure" });
6032
+ } else {
6033
+ res.destroy();
6034
+ }
6035
+ });
6036
+ }
6037
+ async function startLocalBridge(options) {
6038
+ const { serverId, target } = options;
6039
+ let manager = null;
6040
+ if (target.kind === "stdio") {
6041
+ if (options.connectStdio) {
6042
+ manager = await options.connectStdio(serverId, target.config);
6043
+ } else {
6044
+ manager = new MCPClientManager(
6045
+ {},
6046
+ {
6047
+ defaultTimeout: options.timeoutMs ?? 3e4,
6048
+ defaultClientName: "mcpjam-tunnel",
6049
+ lazyConnect: true
6050
+ }
6051
+ );
6052
+ try {
6053
+ await manager.connectToServer(serverId, target.config);
6054
+ } catch (error) {
6055
+ await manager.disconnectAllServers().catch(() => {
6056
+ });
6057
+ throw error;
6058
+ }
6059
+ }
6060
+ }
6061
+ const server = http.createServer((req, res) => {
6062
+ let url;
6063
+ try {
6064
+ url = new URL(req.url ?? "/", "http://bridge.invalid");
6065
+ } catch {
6066
+ writeJson(res, 400, { error: "Bad request" });
6067
+ return;
6068
+ }
6069
+ const remainder = matchTunnelPath(serverId, url.pathname);
6070
+ if (remainder === null) {
6071
+ writeJson(res, 404, { error: "Not found" });
6072
+ return;
6073
+ }
6074
+ const callerParams = stripTunnelSecret(url.searchParams);
6075
+ if (target.kind === "http") {
6076
+ const upstreamUrl = buildUpstreamUrl(
6077
+ new URL(target.url),
6078
+ remainder,
6079
+ callerParams
6080
+ );
6081
+ proxyHttpRequest(req, res, upstreamUrl);
6082
+ return;
6083
+ }
6084
+ handleStdioRequest(serverId, manager, req, res);
6085
+ });
6086
+ try {
6087
+ server.listen(0, "127.0.0.1");
6088
+ await once(server, "listening");
6089
+ } catch (error) {
6090
+ await manager?.disconnectAllServers().catch(() => {
6091
+ });
6092
+ throw error;
6093
+ }
6094
+ const address = server.address();
6095
+ if (!address || typeof address === "string") {
6096
+ server.close();
6097
+ await manager?.disconnectAllServers().catch(() => {
6098
+ });
6099
+ throw new Error("Failed to bind the local bridge address");
6100
+ }
6101
+ return {
6102
+ localAddr: `http://127.0.0.1:${address.port}`,
6103
+ async close() {
6104
+ await new Promise((resolve) => {
6105
+ server.close(() => resolve());
6106
+ server.closeAllConnections?.();
6107
+ });
6108
+ if (manager) {
6109
+ await manager.disconnectAllServers().catch(() => {
6110
+ });
6111
+ }
6112
+ }
6113
+ };
6114
+ }
6115
+ var RELAY_SUBPROTOCOL = "mcpjam-tunnel.v1";
6116
+ var CHUNK_BYTES = 64 * 1024;
6117
+ var HEARTBEAT_INTERVAL_MS = 25e3;
6118
+ var HEARTBEAT_MISSED_LIMIT = 2;
6119
+ var WS_BACKPRESSURE_HIGH_WATER_BYTES = 1024 * 1024;
6120
+ var RECONNECT_MIN_MS = 1e3;
6121
+ var RECONNECT_MAX_MS = 3e4;
6122
+ var CONNECT_TIMEOUT_MS = 15e3;
6123
+ var CLOSE_BAD_TOKEN = 4e3;
6124
+ var CLOSE_REPLACED = 4001;
6125
+ var CLOSE_CONTROL_PLANE = 4002;
6126
+ var CLOSE_EDGE_RESTART = 1012;
6127
+ var BIN_REQ_CHUNK = 1;
6128
+ var BIN_RES_CHUNK = 2;
6129
+ function encodeBinaryFrame(kind, id, payload) {
6130
+ const buf = Buffer.allocUnsafe(5 + payload.byteLength);
6131
+ buf.writeUInt8(kind, 0);
6132
+ buf.writeUInt32BE(id >>> 0, 1);
6133
+ Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength).copy(
6134
+ buf,
6135
+ 5
6136
+ );
6137
+ return buf;
6138
+ }
6139
+ function decodeBinaryFrame(data) {
6140
+ if (data.byteLength < 5) return null;
6141
+ return {
6142
+ kind: data.readUInt8(0),
6143
+ id: data.readUInt32BE(1),
6144
+ payload: data.subarray(5)
6145
+ };
6146
+ }
6147
+ var NOOP_LOGGER = { info: () => {
6148
+ }, warn: () => {
6149
+ } };
6150
+ var RelayConnection = class {
6151
+ constructor(options) {
6152
+ this.options = options;
6153
+ this.logger = options.logger ?? NOOP_LOGGER;
6154
+ }
6155
+ ws = null;
6156
+ local = /* @__PURE__ */ new Map();
6157
+ heartbeatTimer = null;
6158
+ missedPongs = 0;
6159
+ reconnectDelayMs = RECONNECT_MIN_MS;
6160
+ reconnectTimer = null;
6161
+ closedByUs = false;
6162
+ permanent = null;
6163
+ logger;
6164
+ /** Resolves on the first successful hello; rejects on permanent failure. */
6165
+ connect() {
6166
+ return new Promise((resolve, reject) => {
6167
+ let settled = false;
6168
+ const timeout = setTimeout(() => {
6169
+ if (!settled) {
6170
+ settled = true;
6171
+ this.close();
6172
+ reject(new Error("Timed out connecting to the tunnel relay"));
6173
+ }
6174
+ }, CONNECT_TIMEOUT_MS);
6175
+ this.dial(
6176
+ () => {
6177
+ if (!settled) {
6178
+ settled = true;
6179
+ clearTimeout(timeout);
6180
+ resolve();
6181
+ }
6182
+ },
6183
+ (reason) => {
6184
+ if (!settled) {
6185
+ settled = true;
6186
+ clearTimeout(timeout);
6187
+ reject(new Error(reason));
6188
+ }
6189
+ }
6190
+ );
6191
+ });
6192
+ }
6193
+ get isConnected() {
6194
+ return this.ws?.readyState === WebSocket.OPEN;
6195
+ }
6196
+ get permanentFailure() {
6197
+ return this.permanent;
6198
+ }
6199
+ dial(onHello, onPermanent) {
6200
+ if (this.closedByUs || this.permanent) return;
6201
+ const ws = new WebSocket(this.options.relayWsUrl, RELAY_SUBPROTOCOL, {
6202
+ headers: { Authorization: `Bearer ${this.options.connectToken}` }
6203
+ });
6204
+ this.ws = ws;
6205
+ ws.on("message", (data, isBinary) => {
6206
+ if (isBinary) {
6207
+ this.handleBinary(data);
6208
+ return;
6209
+ }
6210
+ let frame = null;
6211
+ try {
6212
+ frame = JSON.parse(String(data));
6213
+ } catch {
6214
+ return;
6215
+ }
6216
+ if (frame.t === "hello") {
6217
+ this.reconnectDelayMs = RECONNECT_MIN_MS;
6218
+ this.logger.info(
6219
+ `Tunnel relay connected (${this.options.serverId}): ${this.options.publicHost}`
6220
+ );
6221
+ onHello?.();
6222
+ return;
6223
+ }
6224
+ this.handleControl(frame);
6225
+ });
6226
+ ws.on("pong", () => {
6227
+ this.missedPongs = 0;
6228
+ });
6229
+ ws.on("error", () => {
6230
+ });
6231
+ ws.on("open", () => this.startHeartbeat());
6232
+ ws.on("close", (code, reasonBuf) => {
6233
+ this.stopHeartbeat();
6234
+ this.abortAllLocal();
6235
+ if (this.closedByUs) return;
6236
+ const reason = reasonBuf.toString() || `relay closed (${code})`;
6237
+ if (code === CLOSE_BAD_TOKEN || code === CLOSE_REPLACED || code === CLOSE_CONTROL_PLANE) {
6238
+ const why = code === CLOSE_REPLACED ? "Tunnel taken over by another session \u2014 re-run `mcpjam tunnel` to take it back" : code === CLOSE_CONTROL_PLANE ? "Tunnel was closed or its secret rotated elsewhere \u2014 re-run `mcpjam tunnel` to recreate it" : "Tunnel session expired \u2014 recreate the tunnel";
6239
+ this.permanent = why;
6240
+ this.logger.warn(`Tunnel relay closed permanently (${code}): ${reason}`);
6241
+ onPermanent?.(why);
6242
+ this.options.onPermanentFailure?.(why, code);
6243
+ return;
6244
+ }
6245
+ const delay2 = code === CLOSE_EDGE_RESTART ? 0 : Math.floor(this.reconnectDelayMs * (0.5 + Math.random() * 0.5));
6246
+ this.reconnectDelayMs = Math.min(
6247
+ this.reconnectDelayMs * 2,
6248
+ RECONNECT_MAX_MS
6249
+ );
6250
+ this.logger.warn(
6251
+ `Tunnel relay disconnected (${code}); reconnecting in ${delay2}ms`
6252
+ );
6253
+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
6254
+ this.reconnectTimer = setTimeout(
6255
+ () => this.dial(onHello, onPermanent),
6256
+ delay2
6257
+ );
6258
+ });
6259
+ }
6260
+ close() {
6261
+ this.closedByUs = true;
6262
+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
6263
+ this.stopHeartbeat();
6264
+ this.abortAllLocal();
6265
+ try {
6266
+ this.ws?.close();
6267
+ } catch {
6268
+ this.ws?.terminate();
6269
+ }
6270
+ this.ws = null;
6271
+ }
6272
+ // ── Edge frames → local bridge ─────────────────────────────────────────────
6273
+ handleControl(frame) {
6274
+ if (frame.t === "req") {
6275
+ this.startLocalRequest(frame);
6276
+ } else if (frame.t === "req_end") {
6277
+ this.local.get(frame.id)?.req.end();
6278
+ } else if (frame.t === "abort") {
6279
+ const entry = this.local.get(frame.id);
6280
+ if (entry) {
6281
+ entry.req.destroy();
6282
+ this.cleanupLocal(frame.id);
6283
+ }
6284
+ }
6285
+ }
6286
+ handleBinary(data) {
6287
+ const frame = decodeBinaryFrame(data);
6288
+ if (!frame || frame.kind !== BIN_REQ_CHUNK) return;
6289
+ this.local.get(frame.id)?.req.write(frame.payload);
6290
+ }
6291
+ startLocalRequest(frame) {
6292
+ const base = new URL(this.options.localAddr);
6293
+ const headers = {};
6294
+ for (const [name, value] of frame.headers) {
6295
+ const existing = headers[name];
6296
+ if (existing === void 0) headers[name] = value;
6297
+ else if (Array.isArray(existing)) existing.push(value);
6298
+ else headers[name] = [existing, value];
6299
+ }
6300
+ const req = http.request({
6301
+ host: base.hostname,
6302
+ port: base.port || 80,
6303
+ method: frame.method,
6304
+ // Forwarded verbatim by the edge (?k= included): the bridge owns
6305
+ // stripping the bearer secret before it reaches the local target.
6306
+ path: frame.url,
6307
+ headers
6308
+ });
6309
+ this.local.set(frame.id, { req, resumePoll: null });
6310
+ req.on("response", (res) => {
6311
+ const responseHeaders = [];
6312
+ for (let i = 0; i + 1 < res.rawHeaders.length; i += 2) {
6313
+ responseHeaders.push([
6314
+ res.rawHeaders[i],
6315
+ res.rawHeaders[i + 1]
6316
+ ]);
6317
+ }
6318
+ this.sendControl({
6319
+ t: "res",
6320
+ id: frame.id,
6321
+ status: res.statusCode ?? 502,
6322
+ headers: responseHeaders
6323
+ });
6324
+ res.on("data", (chunk) => {
6325
+ const ws = this.ws;
6326
+ if (!ws || ws.readyState !== WebSocket.OPEN) {
6327
+ res.destroy();
6328
+ return;
6329
+ }
6330
+ for (let off = 0; off < chunk.byteLength; off += CHUNK_BYTES) {
6331
+ ws.send(
6332
+ encodeBinaryFrame(
6333
+ BIN_RES_CHUNK,
6334
+ frame.id,
6335
+ chunk.subarray(off, off + CHUNK_BYTES)
6336
+ )
6337
+ );
6338
+ }
6339
+ if (ws.bufferedAmount > WS_BACKPRESSURE_HIGH_WATER_BYTES) {
6340
+ res.pause();
6341
+ const entry = this.local.get(frame.id);
6342
+ if (entry && !entry.resumePoll) {
6343
+ entry.resumePoll = setInterval(() => {
6344
+ if (ws.bufferedAmount < WS_BACKPRESSURE_HIGH_WATER_BYTES / 2) {
6345
+ if (entry.resumePoll) clearInterval(entry.resumePoll);
6346
+ entry.resumePoll = null;
6347
+ res.resume();
6348
+ }
6349
+ }, 25);
6350
+ }
6351
+ }
6352
+ });
6353
+ res.on("end", () => {
6354
+ this.sendControl({ t: "res_end", id: frame.id });
6355
+ this.cleanupLocal(frame.id);
6356
+ });
6357
+ res.on("error", () => {
6358
+ this.sendControl({
6359
+ t: "abort",
6360
+ id: frame.id,
6361
+ code: "upstream_error"
6362
+ });
6363
+ this.cleanupLocal(frame.id);
6364
+ });
6365
+ });
6366
+ req.on("error", () => {
6367
+ this.sendControl({ t: "abort", id: frame.id, code: "upstream_error" });
6368
+ this.cleanupLocal(frame.id);
6369
+ });
6370
+ if (!frame.hasBody) req.end();
6371
+ }
6372
+ cleanupLocal(id) {
6373
+ const entry = this.local.get(id);
6374
+ if (entry?.resumePoll) clearInterval(entry.resumePoll);
6375
+ this.local.delete(id);
6376
+ }
6377
+ abortAllLocal() {
6378
+ for (const [id, entry] of [...this.local]) {
6379
+ entry.req.destroy();
6380
+ this.cleanupLocal(id);
6381
+ }
6382
+ }
6383
+ sendControl(frame) {
6384
+ try {
6385
+ this.ws?.send(JSON.stringify(frame));
6386
+ } catch {
6387
+ }
6388
+ }
6389
+ startHeartbeat() {
6390
+ this.stopHeartbeat();
6391
+ this.missedPongs = 0;
6392
+ this.heartbeatTimer = setInterval(() => {
6393
+ const ws = this.ws;
6394
+ if (!ws || ws.readyState !== WebSocket.OPEN) return;
6395
+ if (this.missedPongs >= HEARTBEAT_MISSED_LIMIT) {
6396
+ ws.terminate();
6397
+ return;
6398
+ }
6399
+ this.missedPongs++;
6400
+ try {
6401
+ ws.ping();
6402
+ } catch {
6403
+ }
6404
+ }, HEARTBEAT_INTERVAL_MS);
6405
+ }
6406
+ stopHeartbeat() {
6407
+ if (this.heartbeatTimer) {
6408
+ clearInterval(this.heartbeatTimer);
6409
+ this.heartbeatTimer = null;
6410
+ }
6411
+ }
6412
+ };
6413
+
6414
+ // src/lib/tunnel/tunnel-session.ts
6415
+ var MAX_REMINT_ATTEMPTS = 3;
6416
+ var REMINT_RESET_WINDOW_MS = 6e4;
6417
+ var CLOSE_GRANT_TIMEOUT_MS = 5e3;
6418
+ function permanentCloseMessage(reason, closeCode) {
6419
+ if (closeCode === CLOSE_REPLACED) {
6420
+ return "Tunnel taken over: another session registered a tunnel for this server. Re-run `mcpjam tunnel` here to take it back.";
6421
+ }
6422
+ if (closeCode === CLOSE_CONTROL_PLANE) {
6423
+ return "Tunnel closed or re-created elsewhere (another `mcpjam tunnel` session for this server, or closed from the platform). Re-run `mcpjam tunnel` to recreate it.";
6424
+ }
6425
+ return reason;
6426
+ }
6427
+ async function withTimeout2(promise, ms) {
6428
+ let timer;
6429
+ try {
6430
+ return await Promise.race([
6431
+ promise,
6432
+ new Promise((_, reject) => {
6433
+ timer = setTimeout(
6434
+ () => reject(new Error(`Timed out after ${ms}ms`)),
6435
+ ms
6436
+ );
6437
+ })
6438
+ ]);
6439
+ } finally {
6440
+ if (timer) clearTimeout(timer);
6441
+ }
6442
+ }
6443
+ var TunnelSession = class {
6444
+ constructor(deps) {
6445
+ this.deps = deps;
6446
+ this.closed = new Promise((resolve) => {
6447
+ this.settle = (result) => {
6448
+ if (this.settled) return;
6449
+ this.settled = true;
6450
+ resolve(result);
6451
+ };
6452
+ });
6453
+ }
6454
+ grantResult = null;
6455
+ bridge = null;
6456
+ connection = null;
6457
+ remintAttempts = 0;
6458
+ lastRemintAt = null;
6459
+ started = false;
6460
+ stopped = false;
6461
+ /** True while start()/remint own a connect() — its error path drives. */
6462
+ dialing = false;
6463
+ /** True while a remint is rotating; a second 4000 must not start another. */
6464
+ reminting = false;
6465
+ /**
6466
+ * Permanent close that arrived while we couldn't act on it (mid-dial or
6467
+ * pre-start). Consumed by dial()'s post-handshake check or flushed once
6468
+ * the session is live, so no event is ever silently dropped.
6469
+ */
6470
+ pendingPermanent = null;
6471
+ /** Aborts an in-flight grant mint when stop() lands during one. */
6472
+ mintAborter = null;
6473
+ settled = false;
6474
+ settle;
6475
+ closed;
6476
+ /**
6477
+ * Create the grant, start the bridge, and connect the relay. Resolves
6478
+ * with the grant once the relay handshake succeeded; throws on startup
6479
+ * failure (after cleaning up whatever was started).
6480
+ */
6481
+ async start() {
6482
+ try {
6483
+ const result = await this.mintGrant();
6484
+ this.grantResult = result;
6485
+ this.assertNotStopped();
6486
+ this.bridge = await this.deps.startBridge(result.grant.serverId);
6487
+ this.assertNotStopped();
6488
+ await this.dial(result);
6489
+ this.assertNotStopped();
6490
+ this.started = true;
6491
+ this.deps.onGrant?.(result, false);
6492
+ this.flushPendingPermanent();
6493
+ return result;
6494
+ } catch (error) {
6495
+ await this.cleanup();
6496
+ await this.revokeGrantBestEffort();
6497
+ throw error;
6498
+ }
6499
+ }
6500
+ async mintGrant() {
6501
+ const aborter = new AbortController();
6502
+ this.mintAborter = aborter;
6503
+ try {
6504
+ return await this.deps.createGrant(aborter.signal);
6505
+ } finally {
6506
+ if (this.mintAborter === aborter) {
6507
+ this.mintAborter = null;
6508
+ }
6509
+ }
6510
+ }
6511
+ /**
6512
+ * A stop() that lands mid-startup owns the session: abandon the bring-up
6513
+ * here so start()'s catch tears down and revokes whatever exists by now —
6514
+ * including a grant whose mint resolved after stop() already ran its own
6515
+ * (then-empty) revocation.
6516
+ */
6517
+ assertNotStopped() {
6518
+ if (this.stopped || this.settled) {
6519
+ throw new Error("Tunnel startup interrupted");
6520
+ }
6521
+ }
6522
+ async revokeGrantBestEffort() {
6523
+ if (!this.grantResult) return;
6524
+ const aborter = new AbortController();
6525
+ try {
6526
+ await withTimeout2(
6527
+ this.deps.closeGrant(this.grantResult, aborter.signal),
6528
+ this.deps.closeGrantTimeoutMs ?? CLOSE_GRANT_TIMEOUT_MS
6529
+ );
6530
+ } catch {
6531
+ aborter.abort();
6532
+ }
6533
+ }
6534
+ waitUntilClosed() {
6535
+ return this.closed;
6536
+ }
6537
+ /** Ctrl-C path: close everything, best-effort revoke, exit 0. */
6538
+ async stop() {
6539
+ if (this.stopped) return;
6540
+ this.stopped = true;
6541
+ this.mintAborter?.abort();
6542
+ await this.cleanup();
6543
+ if (this.grantResult) {
6544
+ const aborter = new AbortController();
6545
+ try {
6546
+ await withTimeout2(
6547
+ this.deps.closeGrant(this.grantResult, aborter.signal),
6548
+ this.deps.closeGrantTimeoutMs ?? CLOSE_GRANT_TIMEOUT_MS
6549
+ );
6550
+ this.deps.log("Tunnel grant revoked.");
6551
+ } catch (error) {
6552
+ aborter.abort();
6553
+ this.deps.log(
6554
+ `Could not revoke the tunnel grant (${error instanceof Error ? error.message : String(error)}); it dies with the next create or its own expiry.`
6555
+ );
6556
+ }
6557
+ }
6558
+ this.settle({ exitCode: 0 });
6559
+ }
6560
+ async dial(result) {
6561
+ this.dialing = true;
6562
+ this.pendingPermanent = null;
6563
+ try {
6564
+ const connection = this.deps.connectRelay({
6565
+ grant: result.grant,
6566
+ localAddr: this.bridge.localAddr,
6567
+ onPermanentFailure: (reason, closeCode) => this.handlePermanentFailure(reason, closeCode)
6568
+ });
6569
+ this.connection = connection;
6570
+ await connection.connect();
6571
+ const pending = this.pendingPermanent;
6572
+ if (connection.permanentFailure || pending) {
6573
+ this.pendingPermanent = null;
6574
+ connection.close();
6575
+ throw new Error(connection.permanentFailure ?? pending.reason);
6576
+ }
6577
+ } finally {
6578
+ this.dialing = false;
6579
+ }
6580
+ }
6581
+ handlePermanentFailure(reason, closeCode) {
6582
+ if (this.stopped || this.settled) return;
6583
+ if (this.dialing || !this.started) {
6584
+ this.pendingPermanent = { reason, closeCode };
6585
+ return;
6586
+ }
6587
+ this.dispatchPermanentFailure(reason, closeCode);
6588
+ }
6589
+ flushPendingPermanent() {
6590
+ const pending = this.pendingPermanent;
6591
+ if (!pending || this.stopped || this.settled) return;
6592
+ this.pendingPermanent = null;
6593
+ this.dispatchPermanentFailure(pending.reason, pending.closeCode);
6594
+ }
6595
+ dispatchPermanentFailure(reason, closeCode) {
6596
+ if (closeCode === CLOSE_BAD_TOKEN) {
6597
+ if (!this.reminting) {
6598
+ void this.remint();
6599
+ }
6600
+ return;
6601
+ }
6602
+ void this.fail(permanentCloseMessage(reason, closeCode));
6603
+ }
6604
+ async remint() {
6605
+ if (this.reminting) return;
6606
+ this.reminting = true;
6607
+ try {
6608
+ const now = this.deps.now?.() ?? Date.now();
6609
+ if (this.lastRemintAt !== null && now - this.lastRemintAt > REMINT_RESET_WINDOW_MS) {
6610
+ this.remintAttempts = 0;
6611
+ }
6612
+ this.lastRemintAt = now;
6613
+ this.remintAttempts += 1;
6614
+ if (this.remintAttempts > MAX_REMINT_ATTEMPTS) {
6615
+ await this.fail(
6616
+ `Tunnel session expired and could not be renewed after ${MAX_REMINT_ATTEMPTS} rapid attempts.`
6617
+ );
6618
+ return;
6619
+ }
6620
+ this.deps.log(
6621
+ `Tunnel session expired; renewing the grant (attempt ${this.remintAttempts}/${MAX_REMINT_ATTEMPTS})...`
6622
+ );
6623
+ try {
6624
+ this.connection?.close();
6625
+ const result = await this.mintGrant();
6626
+ this.grantResult = result;
6627
+ if (this.stopped || this.settled) {
6628
+ await this.revokeGrantBestEffort();
6629
+ return;
6630
+ }
6631
+ await this.dial(result);
6632
+ this.deps.onGrant?.(result, true);
6633
+ } catch (error) {
6634
+ await this.revokeGrantBestEffort();
6635
+ if (this.stopped || this.settled) return;
6636
+ await this.fail(
6637
+ `Failed to renew the tunnel: ${error instanceof Error ? error.message : String(error)}`
6638
+ );
6639
+ }
6640
+ } finally {
6641
+ this.reminting = false;
6642
+ this.flushPendingPermanent();
6643
+ }
6644
+ }
6645
+ async fail(reason) {
6646
+ await this.cleanup();
6647
+ this.settle({ exitCode: 1, reason });
6648
+ }
6649
+ async cleanup() {
6650
+ this.connection?.close();
6651
+ this.connection = null;
6652
+ if (this.bridge) {
6653
+ const bridge = this.bridge;
6654
+ this.bridge = null;
6655
+ await bridge.close().catch(() => {
6656
+ });
6657
+ }
6658
+ }
6659
+ };
6660
+
6661
+ // src/commands/tunnel.ts
6662
+ function parseTunnelTarget(tokens) {
6663
+ const isUrl = (token) => /^https?:\/\//i.test(token);
6664
+ if (tokens.length === 0) {
6665
+ throw usageError(
6666
+ "Specify a target: a local server URL (mcpjam tunnel http://localhost:9090/mcp --id my-server) or a stdio command (mcpjam tunnel --id my-server -- npx -y @modelcontextprotocol/server-everything)."
6667
+ );
6668
+ }
6669
+ if (isUrl(tokens[0])) {
6670
+ if (tokens.length > 1) {
6671
+ throw usageError(
6672
+ "Pass either a URL or a stdio command (after --), not both."
6673
+ );
6674
+ }
6675
+ try {
6676
+ new URL(tokens[0]);
6677
+ } catch {
6678
+ throw usageError(`Invalid URL: ${tokens[0]}`);
6679
+ }
6680
+ return { kind: "http", url: tokens[0] };
6681
+ }
6682
+ return { kind: "stdio", command: tokens[0], args: tokens.slice(1) };
6683
+ }
6684
+ function overwriteWarning(result) {
6685
+ const grant = result.grant;
6686
+ if (!grant.existed) return void 0;
6687
+ if (grant.previousTransportType === "stdio") {
6688
+ return `WARNING: server "${grant.name ?? grant.serverId}" already existed as a stdio server \u2014 its config was converted to an HTTP server pointing at this tunnel.`;
6689
+ }
6690
+ if (grant.previousUrl) {
6691
+ return `WARNING: server "${grant.name ?? grant.serverId}" already existed \u2014 its URL was overwritten (was: ${grant.previousUrl}).`;
6692
+ }
6693
+ return void 0;
6694
+ }
6695
+ function publicHost(url) {
6696
+ try {
6697
+ return new URL(url).host || url;
6698
+ } catch {
6699
+ return url;
6700
+ }
6701
+ }
6702
+ function registerTunnelCommands(program) {
6703
+ program.command("tunnel").description(
6704
+ "Expose a local MCP server through an MCPJam tunnel and register it as a server in your project"
6705
+ ).argument(
6706
+ "[target...]",
6707
+ "Local http(s) MCP server URL, or a stdio command after `--`"
6708
+ ).requiredOption(
6709
+ "--id <name>",
6710
+ "Server name to register in the project (an existing server with this name is pointed at the tunnel)"
6711
+ ).option(
6712
+ "--project <id-or-name>",
6713
+ "Project name or ID (defaults to the most recently updated project)"
6714
+ ).option("--api-key <key>", "MCPJam sk_ API key (overrides MCPJAM_API_KEY)").option(
6715
+ "--api-url <url>",
6716
+ "MCPJam API base URL (defaults to https://app.mcpjam.com/api/v1)"
6717
+ ).option(
6718
+ "-e, --env <env...>",
6719
+ 'Stdio environment assignment in "KEY=VALUE" format. Pass multiple values or repeat the flag.'
6720
+ ).option("--cwd <path>", "Working directory for the stdio MCP server process").action(
6721
+ async (target, options, command) => {
6722
+ const globalOptions = getGlobalOptions(command);
6723
+ const parsedTarget = parseTunnelTarget(target);
6724
+ if (parsedTarget.kind === "http" && ((options.env?.length ?? 0) > 0 || options.cwd)) {
6725
+ throw usageError(
6726
+ "--env and --cwd can only be used with a stdio command target."
6727
+ );
6728
+ }
6729
+ const status = (message) => {
6730
+ process.stderr.write(`${message}
6731
+ `);
6732
+ };
6733
+ const bridgeTarget = parsedTarget.kind === "http" ? { kind: "http", url: parsedTarget.url } : {
6734
+ kind: "stdio",
6735
+ config: parseServerConfig({
6736
+ transport: "stdio",
6737
+ command: parsedTarget.command,
6738
+ args: parsedTarget.args,
6739
+ env: options.env,
6740
+ cwd: options.cwd,
6741
+ timeout: globalOptions.timeout
6742
+ })
6743
+ };
6744
+ let client;
6745
+ try {
6746
+ ({ client } = buildPlatformClient({
6747
+ apiKey: options.apiKey,
6748
+ apiUrl: options.apiUrl,
6749
+ timeoutMs: globalOptions.timeout
6750
+ }));
6751
+ } catch (error) {
6752
+ throw toCliError(error);
6753
+ }
6754
+ const printStartup = (result) => {
6755
+ const warning = overwriteWarning(result);
6756
+ if (warning) status(warning);
6757
+ if (globalOptions.format === "human") {
6758
+ process.stdout.write(
6759
+ `Tunnel live: ${result.grant.url}
6760
+ Registered server "${result.grant.name ?? options.id}" in project "${result.project.name}" (${result.grant.serverId})
6761
+ `
6762
+ );
6763
+ status("Press Ctrl-C to stop the tunnel.");
6764
+ } else {
6765
+ writeResult(
6766
+ {
6767
+ url: result.grant.url,
6768
+ serverId: result.grant.serverId,
6769
+ name: result.grant.name ?? options.id,
6770
+ slug: result.grant.slug,
6771
+ project: result.project,
6772
+ existed: result.grant.existed ?? false,
6773
+ ...result.grant.previousUrl ? { previousUrl: result.grant.previousUrl } : {},
6774
+ ...result.grant.previousTransportType ? { previousTransportType: result.grant.previousTransportType } : {},
6775
+ ...result.grant.secretVersion !== void 0 ? { secretVersion: result.grant.secretVersion } : {},
6776
+ target: parsedTarget.kind === "http" ? { kind: "http", url: parsedTarget.url } : {
6777
+ kind: "stdio",
6778
+ command: parsedTarget.command,
6779
+ args: parsedTarget.args
6780
+ }
6781
+ },
6782
+ globalOptions.format
6783
+ );
6784
+ }
6785
+ };
6786
+ const session = new TunnelSession({
6787
+ createGrant: (signal) => createTunnelOperation.execute(
6788
+ { project: options.project, name: options.id },
6789
+ { client, signal }
6790
+ ),
6791
+ closeGrant: async (result, signal) => {
6792
+ await client.closeTunnel(
6793
+ {
6794
+ projectId: result.project.id,
6795
+ serverId: result.grant.serverId
6796
+ },
6797
+ { signal }
6798
+ );
6799
+ },
6800
+ startBridge: (serverId) => startLocalBridge({
6801
+ serverId,
6802
+ target: bridgeTarget,
6803
+ timeoutMs: globalOptions.timeout,
6804
+ log: status
6805
+ }),
6806
+ connectRelay: ({ grant, localAddr, onPermanentFailure }) => new RelayConnection({
6807
+ serverId: grant.serverId,
6808
+ slug: grant.slug,
6809
+ relayWsUrl: grant.relayWsUrl,
6810
+ connectToken: grant.connectToken,
6811
+ localAddr,
6812
+ publicHost: publicHost(grant.url),
6813
+ logger: { info: status, warn: status },
6814
+ onPermanentFailure
6815
+ }),
6816
+ log: status,
6817
+ onGrant: (result, rotated) => {
6818
+ if (rotated) {
6819
+ status(`Tunnel secret rotated; new URL: ${result.grant.url}`);
6820
+ return;
6821
+ }
6822
+ printStartup(result);
6823
+ }
6824
+ });
6825
+ if (parsedTarget.kind === "stdio") {
6826
+ status(
6827
+ `Starting stdio server: ${parsedTarget.command}${parsedTarget.args.length ? ` ${parsedTarget.args.join(" ")}` : ""}`
6828
+ );
6829
+ }
6830
+ let sigints = 0;
6831
+ const onSignal = () => {
6832
+ sigints += 1;
6833
+ if (sigints === 1) {
6834
+ status("Shutting down tunnel... (Ctrl-C again to force quit)");
6835
+ void session.stop();
6836
+ return;
6837
+ }
6838
+ process.exit(130);
6839
+ };
6840
+ process.on("SIGINT", onSignal);
6841
+ process.on("SIGTERM", onSignal);
6842
+ try {
6843
+ const startPromise = session.start();
6844
+ try {
6845
+ await Promise.race([startPromise, session.waitUntilClosed()]);
6846
+ } catch (error) {
6847
+ if (sigints === 0) {
6848
+ throw toCliError(error);
6849
+ }
6850
+ }
6851
+ if (sigints > 0) {
6852
+ startPromise.catch(() => {
6853
+ });
6854
+ }
6855
+ const result = await session.waitUntilClosed();
6856
+ if (result.exitCode !== 0) {
6857
+ throw cliError(
6858
+ "TUNNEL_CLOSED",
6859
+ result.reason ?? "Tunnel closed",
6860
+ result.exitCode
6861
+ );
6862
+ }
6863
+ } finally {
6864
+ process.removeListener("SIGINT", onSignal);
6865
+ process.removeListener("SIGTERM", onSignal);
6866
+ }
6867
+ }
6868
+ );
6869
+ }
5206
6870
 
5207
6871
  // src/commands/inspector.ts
5208
6872
  function addInspectorUrlOption(command) {
@@ -5299,6 +6963,9 @@ async function main(argv = process.argv, dependencies = {}) {
5299
6963
  registerAppsCommands(program);
5300
6964
  registerOAuthCommands(program);
5301
6965
  registerProtocolCommands(program);
6966
+ registerAuthCommands(program);
6967
+ registerProjectsCommands(program);
6968
+ registerTunnelCommands(program);
5302
6969
  registerInspectorCommands(program);
5303
6970
  registerTelemetryCommands(program, dependencies.telemetry);
5304
6971
  if (argv.length <= 2) {