@mcpjam/cli 3.3.5 → 3.5.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,18 @@
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, 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 { 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';
12
13
 
13
14
  // package.json
14
15
  var package_default = {
15
- version: "3.3.5"};
16
+ version: "3.5.0"};
16
17
 
17
18
  // src/lib/output.ts
18
19
  var DEFAULT_OUTPUT_FORMAT = "json";
@@ -1243,6 +1244,638 @@ function buildAppsConformanceConfig(options) {
1243
1244
  ...resolvedCheckIds && resolvedCheckIds.length > 0 ? { checkIds: resolvedCheckIds } : {}
1244
1245
  };
1245
1246
  }
1247
+ var AUTH_STORE_VERSION = 1;
1248
+ function getAuthFilePath(options = {}) {
1249
+ const env = options.env ?? process.env;
1250
+ const platform = options.platform ?? process.platform;
1251
+ const homeDirectory = options.homeDirectory ?? homedir();
1252
+ if (env.MCPJAM_AUTH_FILE) {
1253
+ return env.MCPJAM_AUTH_FILE;
1254
+ }
1255
+ if (platform === "win32") {
1256
+ return join(
1257
+ env.APPDATA || join(homeDirectory, "AppData", "Roaming"),
1258
+ "mcpjam",
1259
+ "auth.json"
1260
+ );
1261
+ }
1262
+ return join(
1263
+ env.XDG_CONFIG_HOME || join(homeDirectory, ".config"),
1264
+ "mcpjam",
1265
+ "auth.json"
1266
+ );
1267
+ }
1268
+ function readStoredAuth(filePath) {
1269
+ let raw;
1270
+ try {
1271
+ raw = readFileSync(filePath, "utf8");
1272
+ } catch {
1273
+ return null;
1274
+ }
1275
+ let parsed;
1276
+ try {
1277
+ parsed = JSON.parse(raw);
1278
+ } catch {
1279
+ return null;
1280
+ }
1281
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1282
+ return null;
1283
+ }
1284
+ const record = parsed;
1285
+ if (record.version !== AUTH_STORE_VERSION || typeof record.issuer !== "string" || typeof record.clientId !== "string" || typeof record.tokenEndpoint !== "string" || typeof record.accessToken !== "string") {
1286
+ return null;
1287
+ }
1288
+ return {
1289
+ version: AUTH_STORE_VERSION,
1290
+ issuer: record.issuer,
1291
+ clientId: record.clientId,
1292
+ tokenEndpoint: record.tokenEndpoint,
1293
+ accessToken: record.accessToken,
1294
+ // Hand-edited files may hold a non-URL; dropping it here means readers
1295
+ // fall back to the default base URL instead of producing broken requests.
1296
+ ...typeof record.apiUrl === "string" && URL.canParse(record.apiUrl) ? { apiUrl: record.apiUrl } : {},
1297
+ ...typeof record.refreshToken === "string" ? { refreshToken: record.refreshToken } : {},
1298
+ ...typeof record.expiresAt === "number" ? { expiresAt: record.expiresAt } : {}
1299
+ };
1300
+ }
1301
+ async function writeStoredAuth(contents, filePath) {
1302
+ const directory = dirname(filePath);
1303
+ const temporaryPath = join(
1304
+ directory,
1305
+ `.${basename(filePath)}.${randomUUID()}.tmp`
1306
+ );
1307
+ try {
1308
+ await mkdir(directory, { recursive: true });
1309
+ await writeFile(temporaryPath, `${JSON.stringify(contents, null, 2)}
1310
+ `, {
1311
+ encoding: "utf8",
1312
+ mode: 384
1313
+ });
1314
+ await chmod(temporaryPath, 384);
1315
+ await rename(temporaryPath, filePath);
1316
+ } catch (error) {
1317
+ await rm(temporaryPath, { force: true }).catch(() => void 0);
1318
+ throw operationalError(`Failed to write credentials to "${filePath}".`, {
1319
+ source: error instanceof Error ? error.message : String(error)
1320
+ });
1321
+ }
1322
+ return filePath;
1323
+ }
1324
+ async function clearStoredAuth(filePath) {
1325
+ const existed = readStoredAuth(filePath) !== null;
1326
+ await rm(filePath, { force: true });
1327
+ return existed;
1328
+ }
1329
+
1330
+ // src/lib/platform-auth.ts
1331
+ var LEGACY_API_KEY_PREFIX = "mcpjam_";
1332
+ var TOKEN_REFRESH_SKEW_MS = 6e4;
1333
+ var DEFAULT_LOGIN_TIMEOUT_MS = 5 * 6e4;
1334
+ 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`.";
1335
+ function resolvePlatformCredential(options, deps = {}) {
1336
+ const env = deps.env ?? process.env;
1337
+ const warn = deps.warn ?? ((message) => process.stderr.write(`${message}
1338
+ `));
1339
+ const flagKey = options.apiKey?.trim();
1340
+ if (flagKey) {
1341
+ if (flagKey.startsWith(LEGACY_API_KEY_PREFIX)) {
1342
+ throw usageError(LEGACY_KEY_REMEDY);
1343
+ }
1344
+ return { kind: "api-key", getAuth: async () => flagKey };
1345
+ }
1346
+ const envKey = env.MCPJAM_API_KEY?.trim();
1347
+ if (envKey) {
1348
+ if (!envKey.startsWith(LEGACY_API_KEY_PREFIX)) {
1349
+ return { kind: "api-key", getAuth: async () => envKey };
1350
+ }
1351
+ warn(
1352
+ `Ignoring legacy mcpjam_ key in MCPJAM_API_KEY for this command. ${LEGACY_KEY_REMEDY}`
1353
+ );
1354
+ }
1355
+ const authFilePath = deps.authFilePath ?? getAuthFilePath({ env });
1356
+ return {
1357
+ kind: "oauth",
1358
+ getAuth: () => getOAuthAccessToken({
1359
+ authFilePath,
1360
+ fetchFn: deps.fetchFn,
1361
+ now: deps.now
1362
+ })
1363
+ };
1364
+ }
1365
+ async function getOAuthAccessToken(deps) {
1366
+ const stored = readStoredAuth(deps.authFilePath);
1367
+ if (!stored) {
1368
+ throw operationalError(
1369
+ "Not logged in. Run `mcpjam login`, or pass an sk_ API key via --api-key / MCPJAM_API_KEY."
1370
+ );
1371
+ }
1372
+ const now = deps.now ?? Date.now;
1373
+ const expiresSoon = stored.expiresAt !== void 0 && stored.expiresAt - now() <= TOKEN_REFRESH_SKEW_MS;
1374
+ if (!expiresSoon) {
1375
+ return stored.accessToken;
1376
+ }
1377
+ if (!stored.refreshToken) {
1378
+ throw operationalError("Login expired. Run `mcpjam login` again.");
1379
+ }
1380
+ const refreshed = await refreshStoredAuth(stored, deps);
1381
+ return refreshed.accessToken;
1382
+ }
1383
+ async function refreshStoredAuth(stored, deps) {
1384
+ const tokens = await exchangeToken(
1385
+ stored.tokenEndpoint,
1386
+ {
1387
+ grant_type: "refresh_token",
1388
+ client_id: stored.clientId,
1389
+ refresh_token: stored.refreshToken
1390
+ },
1391
+ deps.fetchFn ?? fetch,
1392
+ "Token refresh failed. Run `mcpjam login` again.",
1393
+ deps.now
1394
+ );
1395
+ const refreshed = {
1396
+ ...stored,
1397
+ accessToken: tokens.accessToken,
1398
+ // AuthKit rotates refresh tokens; keep the old one only if none returned.
1399
+ ...tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {},
1400
+ ...tokens.expiresAt !== void 0 ? { expiresAt: tokens.expiresAt } : {}
1401
+ };
1402
+ await writeStoredAuth(refreshed, deps.authFilePath);
1403
+ return refreshed;
1404
+ }
1405
+ async function runPlatformLogin(target, deps = {}) {
1406
+ const fetchFn = deps.fetchFn ?? fetch;
1407
+ const config = await fetchCliAuthConfig(target.origin, fetchFn);
1408
+ const codeVerifier = generateRandomString(64);
1409
+ const state = generateRandomString(32);
1410
+ const codeChallenge = await generateCodeChallenge(codeVerifier);
1411
+ const session = await (deps.createSession ?? createInteractiveAuthorizationSession)();
1412
+ let code;
1413
+ try {
1414
+ const authorizationUrl = new URL(config.authStartUrl);
1415
+ authorizationUrl.searchParams.set("redirect_uri", session.redirectUrl);
1416
+ authorizationUrl.searchParams.set("state", state);
1417
+ authorizationUrl.searchParams.set("code_challenge", codeChallenge);
1418
+ authorizationUrl.searchParams.set("code_challenge_method", "S256");
1419
+ ({ code } = await session.authorize({
1420
+ authorizationUrl: authorizationUrl.toString(),
1421
+ expectedState: state,
1422
+ timeoutMs: deps.timeoutMs ?? DEFAULT_LOGIN_TIMEOUT_MS,
1423
+ openUrl: deps.openUrl ?? openUrlInBrowser
1424
+ }));
1425
+ } finally {
1426
+ await session.stop().catch(() => void 0);
1427
+ }
1428
+ const tokens = await exchangeToken(
1429
+ config.tokenEndpoint,
1430
+ {
1431
+ grant_type: "authorization_code",
1432
+ client_id: config.clientId,
1433
+ code,
1434
+ redirect_uri: config.redirectUri,
1435
+ code_verifier: codeVerifier
1436
+ },
1437
+ fetchFn,
1438
+ "Login failed during the token exchange.",
1439
+ deps.now
1440
+ );
1441
+ if (!tokens.refreshToken) {
1442
+ throw operationalError(
1443
+ "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."
1444
+ );
1445
+ }
1446
+ const authFilePath = deps.authFilePath ?? getAuthFilePath();
1447
+ await writeStoredAuth(
1448
+ {
1449
+ version: 1,
1450
+ issuer: config.issuer,
1451
+ clientId: config.clientId,
1452
+ tokenEndpoint: config.tokenEndpoint,
1453
+ apiUrl: target.apiUrl,
1454
+ accessToken: tokens.accessToken,
1455
+ refreshToken: tokens.refreshToken,
1456
+ ...tokens.expiresAt !== void 0 ? { expiresAt: tokens.expiresAt } : {}
1457
+ },
1458
+ authFilePath
1459
+ );
1460
+ return {
1461
+ authFilePath,
1462
+ issuer: config.issuer,
1463
+ ...tokens.expiresAt !== void 0 ? { expiresAt: tokens.expiresAt } : {}
1464
+ };
1465
+ }
1466
+ async function runPlatformLogout(authFilePath = getAuthFilePath()) {
1467
+ const loggedOut = await clearStoredAuth(authFilePath);
1468
+ return { loggedOut, authFilePath };
1469
+ }
1470
+ async function fetchCliAuthConfig(platformOrigin, fetchFn) {
1471
+ const configUrl = `${platformOrigin.replace(/\/+$/, "")}/api/cli/auth/config`;
1472
+ let response;
1473
+ try {
1474
+ response = await fetchFn(configUrl);
1475
+ } catch (error) {
1476
+ throw operationalError(
1477
+ `Could not reach ${configUrl}: ${error instanceof Error ? error.message : String(error)}`
1478
+ );
1479
+ }
1480
+ if (response.status === 501) {
1481
+ throw operationalError(
1482
+ `CLI login is not enabled on ${platformOrigin}. Use an sk_ API key via --api-key / MCPJAM_API_KEY instead.`
1483
+ );
1484
+ }
1485
+ if (!response.ok) {
1486
+ throw operationalError(
1487
+ `Fetching the login configuration from ${configUrl} failed (${response.status}).`
1488
+ );
1489
+ }
1490
+ const body = await response.json().catch(() => null);
1491
+ for (const field of [
1492
+ "issuer",
1493
+ "clientId",
1494
+ "authStartUrl",
1495
+ "tokenEndpoint",
1496
+ "redirectUri"
1497
+ ]) {
1498
+ if (typeof body?.[field] !== "string" || !body[field]) {
1499
+ throw operationalError(
1500
+ `The login configuration from ${configUrl} is missing "${field}".`
1501
+ );
1502
+ }
1503
+ }
1504
+ return {
1505
+ issuer: body.issuer,
1506
+ clientId: body.clientId,
1507
+ authStartUrl: body.authStartUrl,
1508
+ tokenEndpoint: body.tokenEndpoint,
1509
+ redirectUri: body.redirectUri
1510
+ };
1511
+ }
1512
+ async function exchangeToken(tokenEndpoint, params, fetchFn, failureMessage, now = Date.now) {
1513
+ let response;
1514
+ try {
1515
+ response = await fetchFn(tokenEndpoint, {
1516
+ method: "POST",
1517
+ headers: { "content-type": "application/x-www-form-urlencoded" },
1518
+ body: new URLSearchParams(params).toString()
1519
+ });
1520
+ } catch (error) {
1521
+ throw operationalError(
1522
+ `${failureMessage} Could not reach ${tokenEndpoint}: ${error instanceof Error ? error.message : String(error)}`
1523
+ );
1524
+ }
1525
+ const body = await response.json().catch(() => null);
1526
+ if (!response.ok || typeof body?.access_token !== "string") {
1527
+ const detail = typeof body?.error_description === "string" ? body.error_description : typeof body?.error === "string" ? body.error : `HTTP ${response.status}`;
1528
+ throw operationalError(`${failureMessage} (${detail})`);
1529
+ }
1530
+ return {
1531
+ accessToken: body.access_token,
1532
+ ...typeof body.refresh_token === "string" ? { refreshToken: body.refresh_token } : {},
1533
+ ...typeof body.expires_in === "number" && Number.isFinite(body.expires_in) ? { expiresAt: now() + body.expires_in * 1e3 } : {}
1534
+ };
1535
+ }
1536
+ function validateApiUrl(value, source) {
1537
+ let parsed;
1538
+ try {
1539
+ parsed = new URL(value);
1540
+ } catch {
1541
+ throw usageError(
1542
+ `Invalid ${source} value "${value}". Expected a full URL like ${DEFAULT_PLATFORM_API_BASE_URL}.`
1543
+ );
1544
+ }
1545
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
1546
+ throw usageError(
1547
+ `Invalid ${source} value "${value}". Expected an http(s) URL like ${DEFAULT_PLATFORM_API_BASE_URL}.`
1548
+ );
1549
+ }
1550
+ return value;
1551
+ }
1552
+ function resolveExplicitApiUrl(options, env) {
1553
+ const flagUrl = options.apiUrl?.trim();
1554
+ if (flagUrl) {
1555
+ return validateApiUrl(flagUrl, "--api-url");
1556
+ }
1557
+ const envUrl = env.MCPJAM_API_URL?.trim();
1558
+ if (envUrl) {
1559
+ return validateApiUrl(envUrl, "MCPJAM_API_URL");
1560
+ }
1561
+ return void 0;
1562
+ }
1563
+ function resolvePlatformBaseUrl(options, env = process.env) {
1564
+ return resolveExplicitApiUrl(options, env) ?? DEFAULT_PLATFORM_API_BASE_URL;
1565
+ }
1566
+ function resolvePlatformOrigin(options, env = process.env) {
1567
+ return new URL(resolvePlatformBaseUrl(options, env)).origin;
1568
+ }
1569
+ function buildPlatformClient(options, deps = {}) {
1570
+ const env = deps.env ?? process.env;
1571
+ const credential = resolvePlatformCredential(options, deps);
1572
+ let baseUrl = resolveExplicitApiUrl(options, env);
1573
+ if (!baseUrl && credential.kind === "oauth") {
1574
+ const stored = readStoredAuth(deps.authFilePath ?? getAuthFilePath({ env }));
1575
+ baseUrl = stored?.apiUrl;
1576
+ }
1577
+ const client = new PlatformApiClient({
1578
+ baseUrl: baseUrl ?? DEFAULT_PLATFORM_API_BASE_URL,
1579
+ getAuth: credential.getAuth,
1580
+ ...deps.fetchFn ? { fetch: deps.fetchFn } : {},
1581
+ ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
1582
+ userAgent: `mcpjam-cli/${package_default.version}`
1583
+ });
1584
+ return { client, credentialKind: credential.kind };
1585
+ }
1586
+ function toCliError(error) {
1587
+ if (error instanceof CliError) {
1588
+ return error;
1589
+ }
1590
+ if (isPlatformApiError(error)) {
1591
+ const message = error.code === "UNAUTHORIZED" ? `${error.message} Run \`mcpjam login\` or pass a valid sk_ API key.` : error.message;
1592
+ return cliError(error.code, message, 1, error.details);
1593
+ }
1594
+ return cliError(
1595
+ "INTERNAL_ERROR",
1596
+ error instanceof Error ? error.message : String(error)
1597
+ );
1598
+ }
1599
+
1600
+ // src/commands/auth.ts
1601
+ function registerAuthCommands(program) {
1602
+ program.command("login").description(
1603
+ "Log in to MCPJam. Opens your browser for OAuth and stores the session locally."
1604
+ ).option(
1605
+ "--api-url <url>",
1606
+ "MCPJam API base URL (defaults to https://app.mcpjam.com/api/v1)"
1607
+ ).option(
1608
+ "--no-browser",
1609
+ "Print the login URL instead of opening a browser"
1610
+ ).action(async (options, command) => {
1611
+ const globalOptions = getGlobalOptions(command);
1612
+ const apiUrl = resolvePlatformBaseUrl(options);
1613
+ const origin = resolvePlatformOrigin(options);
1614
+ const result = await runPlatformLogin({ origin, apiUrl }, {
1615
+ ...options.browser === false ? {
1616
+ openUrl: async (url) => {
1617
+ process.stderr.write(
1618
+ `Open this URL in your browser to continue:
1619
+
1620
+ ${url}
1621
+
1622
+ `
1623
+ );
1624
+ }
1625
+ } : {}
1626
+ });
1627
+ writeResult(
1628
+ {
1629
+ status: "logged_in",
1630
+ issuer: result.issuer,
1631
+ authFile: result.authFilePath,
1632
+ ...result.expiresAt !== void 0 ? { expiresAt: new Date(result.expiresAt).toISOString() } : {}
1633
+ },
1634
+ globalOptions.format
1635
+ );
1636
+ });
1637
+ program.command("logout").description("Remove the stored MCPJam login.").action(async (_options, command) => {
1638
+ const globalOptions = getGlobalOptions(command);
1639
+ const result = await runPlatformLogout();
1640
+ writeResult(
1641
+ {
1642
+ status: result.loggedOut ? "logged_out" : "not_logged_in",
1643
+ authFile: result.authFilePath
1644
+ },
1645
+ globalOptions.format
1646
+ );
1647
+ });
1648
+ 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(
1649
+ "--api-url <url>",
1650
+ "MCPJam API base URL (defaults to https://app.mcpjam.com/api/v1)"
1651
+ ).action(async (options, command) => {
1652
+ const globalOptions = getGlobalOptions(command);
1653
+ try {
1654
+ const { client, credentialKind } = buildPlatformClient(options);
1655
+ const me = await client.getMe();
1656
+ writeResult(
1657
+ {
1658
+ id: me.id,
1659
+ email: me.email,
1660
+ name: me.name,
1661
+ ...me.plan ? { plan: me.plan } : {},
1662
+ credential: credentialKind
1663
+ },
1664
+ globalOptions.format
1665
+ );
1666
+ } catch (error) {
1667
+ throw toCliError(error);
1668
+ }
1669
+ });
1670
+ }
1671
+
1672
+ // src/lib/projects-render.ts
1673
+ function formatTimestamp(value) {
1674
+ return typeof value === "number" ? new Date(value).toISOString() : "-";
1675
+ }
1676
+ function table(rows) {
1677
+ if (rows.length === 0) {
1678
+ return [];
1679
+ }
1680
+ const widths = rows[0].map(
1681
+ (_cell, column) => Math.max(...rows.map((row) => row[column]?.length ?? 0))
1682
+ );
1683
+ return rows.map(
1684
+ (row) => row.map(
1685
+ (cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])
1686
+ ).join(" ").trimEnd()
1687
+ );
1688
+ }
1689
+ function formatProjectsHuman(projects) {
1690
+ if (projects.length === 0) {
1691
+ return "No accessible projects.";
1692
+ }
1693
+ const lines = table([
1694
+ ["ID", "NAME", "UPDATED"],
1695
+ ...projects.map((project) => [
1696
+ project.id,
1697
+ project.name,
1698
+ formatTimestamp(project.updatedAt)
1699
+ ])
1700
+ ]);
1701
+ lines.push("", `${projects.length} project(s).`);
1702
+ return lines.join("\n");
1703
+ }
1704
+ function formatProjectServersHuman(result) {
1705
+ const lines = [`Project: ${result.project.name} (${result.project.id})`, ""];
1706
+ if (result.items.length === 0) {
1707
+ lines.push("No servers in this project.");
1708
+ } else {
1709
+ lines.push(
1710
+ ...table([
1711
+ ["ID", "NAME", "TRANSPORT", "URL", "ENABLED"],
1712
+ ...result.items.map((server) => [
1713
+ server.id,
1714
+ server.name,
1715
+ server.transportType,
1716
+ server.url ?? "-",
1717
+ server.enabled ? "yes" : "no"
1718
+ ])
1719
+ ])
1720
+ );
1721
+ }
1722
+ appendOtherProjects(lines, result.otherProjects);
1723
+ return lines.join("\n");
1724
+ }
1725
+ function formatShowServersHuman(payload) {
1726
+ const lines = [
1727
+ `Project: ${payload.project.name} (${payload.project.id})`,
1728
+ ""
1729
+ ];
1730
+ if (payload.servers.length === 0) {
1731
+ lines.push("No servers in this project.");
1732
+ } else {
1733
+ for (const server of payload.servers) {
1734
+ const headline = `${statusGlyph(server.status)} ${server.name} [${server.status}]`;
1735
+ lines.push(server.url ? `${headline} ${server.url}` : headline);
1736
+ if (server.statusDetail) {
1737
+ lines.push(` ${server.statusDetail}`);
1738
+ }
1739
+ if (server.serverInfo?.name || server.serverInfo?.version) {
1740
+ lines.push(
1741
+ ` Server: ${server.serverInfo.name ?? "unknown"}${server.serverInfo.version ? ` v${server.serverInfo.version}` : ""}`
1742
+ );
1743
+ }
1744
+ if (server.primitives) {
1745
+ lines.push(
1746
+ ` Primitives: tools ${server.primitives.tools.items.length}, resources ${server.primitives.resources.items.length}, prompts ${server.primitives.prompts.items.length}`
1747
+ );
1748
+ }
1749
+ }
1750
+ }
1751
+ const summary = payload.summary;
1752
+ lines.push(
1753
+ "",
1754
+ `Summary: ${summary.reachable} reachable, ${summary.unreachable} unreachable, ${summary.skipped} skipped, ${summary.error} error(s).`
1755
+ );
1756
+ appendOtherProjects(lines, payload.otherProjects);
1757
+ lines.push(`Generated at ${payload.generatedAt}.`);
1758
+ return lines.join("\n");
1759
+ }
1760
+ function appendOtherProjects(lines, otherProjects) {
1761
+ if (otherProjects.length > 0) {
1762
+ lines.push(
1763
+ "",
1764
+ `Other projects: ${otherProjects.map((project) => project.name).join(", ")} (switch with --project)`
1765
+ );
1766
+ }
1767
+ }
1768
+ function statusGlyph(status) {
1769
+ switch (status) {
1770
+ case "reachable":
1771
+ return "\u2713";
1772
+ case "unreachable":
1773
+ return "\u2717";
1774
+ case "skipped":
1775
+ return "-";
1776
+ case "error":
1777
+ return "!";
1778
+ }
1779
+ }
1780
+
1781
+ // src/commands/projects.ts
1782
+ function addPlatformOptions(command) {
1783
+ return command.option("--api-key <key>", "MCPJam sk_ API key (overrides MCPJAM_API_KEY)").option(
1784
+ "--api-url <url>",
1785
+ "MCPJam API base URL (defaults to https://app.mcpjam.com/api/v1)"
1786
+ );
1787
+ }
1788
+ async function runPlatformCommand(options, timeoutMs, execute) {
1789
+ const controller = new AbortController();
1790
+ const timeoutHandle = setTimeout(() => {
1791
+ controller.abort(
1792
+ new PlatformApiError(
1793
+ `Request timed out after ${timeoutMs}ms`,
1794
+ "TIMEOUT",
1795
+ {
1796
+ status: 0
1797
+ }
1798
+ )
1799
+ );
1800
+ }, timeoutMs);
1801
+ timeoutHandle.unref?.();
1802
+ try {
1803
+ const { client } = buildPlatformClient({ ...options, timeoutMs });
1804
+ return await execute({ client, signal: controller.signal });
1805
+ } catch (error) {
1806
+ if (controller.signal.aborted && controller.signal.reason instanceof PlatformApiError) {
1807
+ throw toCliError(controller.signal.reason);
1808
+ }
1809
+ throw toCliError(error);
1810
+ } finally {
1811
+ clearTimeout(timeoutHandle);
1812
+ }
1813
+ }
1814
+ function registerProjectsCommands(program) {
1815
+ const projects = program.command("projects").description("Operate the MCP servers saved in your hosted MCPJam projects");
1816
+ addPlatformOptions(
1817
+ projects.command("list").description("List the projects you can access")
1818
+ ).action(async (options, command) => {
1819
+ const globalOptions = getGlobalOptions(command);
1820
+ const result = await runPlatformCommand(
1821
+ options,
1822
+ globalOptions.timeout,
1823
+ ({ client, signal }) => listProjectsOperation.execute({}, { client, signal })
1824
+ );
1825
+ if (globalOptions.format === "human") {
1826
+ process.stdout.write(`${formatProjectsHuman(result.items)}
1827
+ `);
1828
+ } else {
1829
+ writeResult(result, globalOptions.format);
1830
+ }
1831
+ });
1832
+ addPlatformOptions(
1833
+ projects.command("servers").description("List the servers saved in a project").option(
1834
+ "--project <id-or-name>",
1835
+ "Project name or ID (defaults to the most recently updated project)"
1836
+ )
1837
+ ).action(async (options, command) => {
1838
+ const globalOptions = getGlobalOptions(command);
1839
+ const result = await runPlatformCommand(
1840
+ options,
1841
+ globalOptions.timeout,
1842
+ ({ client, signal }) => listProjectServersOperation.execute(
1843
+ { project: options.project },
1844
+ { client, signal }
1845
+ )
1846
+ );
1847
+ if (globalOptions.format === "human") {
1848
+ process.stdout.write(`${formatProjectServersHuman(result)}
1849
+ `);
1850
+ } else {
1851
+ writeResult(result, globalOptions.format);
1852
+ }
1853
+ });
1854
+ addPlatformOptions(
1855
+ projects.command("status").description(
1856
+ "Health-check every server in a project (hosted doctor per server)"
1857
+ ).option(
1858
+ "--project <id-or-name>",
1859
+ "Project name or ID (defaults to the most recently updated project)"
1860
+ )
1861
+ ).action(async (options, command) => {
1862
+ const globalOptions = getGlobalOptions(command);
1863
+ const payload = await runPlatformCommand(
1864
+ options,
1865
+ globalOptions.timeout,
1866
+ ({ client, signal }) => showServersOperation.execute(
1867
+ { project: options.project },
1868
+ { client, signal }
1869
+ )
1870
+ );
1871
+ if (globalOptions.format === "human") {
1872
+ process.stdout.write(`${formatShowServersHuman(payload)}
1873
+ `);
1874
+ } else {
1875
+ writeResult(payload, globalOptions.format);
1876
+ }
1877
+ });
1878
+ }
1246
1879
  function registerProtocolCommands(program) {
1247
1880
  const protocol = program.command("protocol").description("MCP protocol inspection and conformance checks");
1248
1881
  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(
@@ -5299,6 +5932,8 @@ async function main(argv = process.argv, dependencies = {}) {
5299
5932
  registerAppsCommands(program);
5300
5933
  registerOAuthCommands(program);
5301
5934
  registerProtocolCommands(program);
5935
+ registerAuthCommands(program);
5936
+ registerProjectsCommands(program);
5302
5937
  registerInspectorCommands(program);
5303
5938
  registerTelemetryCommands(program, dependencies.telemetry);
5304
5939
  if (argv.length <= 2) {