CLI: catalog listing, auth flags, and OAuth browser UX (#1782)

* feat(cli): catalog listing, auth flags, and OAuth browser UX

Add servers/list and servers/show, --relogin / --stored-auth-only, browser
OAuth navigation with OSC 8 links, and extract method handlers under
clients/cli/src/handlers. Tracks #1781.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): address #1782 review — relogin clear, stored-auth-only, docs

Clear both raw and normalized OAuth keys on --relogin; check the shared
store before bailing under --stored-auth-only mid-session; restore the
tests README link target; document servers/show redaction limits; keep
mcpi groundwork with TODO(#1432) markers.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): gate OAuth browser open and harden #1782 review follow-ups

Arm auto-open only for CLI-owned interactive OAuth, honor MCP_AUTO_OPEN_ENABLED,
move --relogin clear after validation, skip keychain on servers/list, and cover
secret redaction after rehydrate.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): silence disarmed OAuth URLs and round-3 review nits

Suppress authorize URL print when navigation is disarmed or
--stored-auth-only; document MCP_AUTO_OPEN_ENABLED; redact Cookie/auth
headers; keep servers/show unit tests off the OS keychain.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(cli): cover withArmedAutoOpen for the ≥90 branch gate

CI failed on cliOAuth.ts branch coverage after the auto-open arming
helper landed; exercise the armed path through runCliInteractiveOAuth.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): mid-RPC unauthorized recovery and clear round-4 nits

Mirror connect's UnauthorizedError path in withCliAuthRecoveryRetry, let
MCP_AUTO_OPEN_ENABLED=true force open off-TTY, mock open-url in the
in-process runner, reject --relogin on catalog methods, restore the
__tests__ README inventory, and narrow OAuth helpers to structural client types.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): reconnect after mid-RPC OAuth and finish round-5 nits

Reconnect before retrying after unauthorized recovery, guard non-OAuth
configs, decouple forceAutoOpen, move open-url mock to vitest setupFiles,
and reject --relogin with stored-auth short-circuits.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): fail fast on non-TTY interactive OAuth and round-6 nits

Skip interactive OAuth without a TTY unless MCP_AUTO_OPEN_ENABLED=true;
document --stored-auth-only for CI; redact settings.metadata; reject
--relogin for stdio; clarify AuthRecoveryRequired reconnect comments.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): admit interactive OAuth when stdin is a TTY (round-7)

Gate on stdin||stderr so `2>&1 | tee` still works; fold confirm/auto-open/
TTY into CliOAuthConnectOptions; rename authRequiredFailure; document
MCP_AUTO_OPEN_ENABLED=true as non-TTY admit.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): fail fast on step-up without stdin (round-8)

Decline [y/N] on readline EOF/close, require a stdin TTY for the default
step-up confirmer (force-open admit is not enough), document stderr-only
browser auto-open vs stdin||stderr flow admit, and drop the alias wrapper.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): allow piped step-up answers; bound silent pipes (round-9)

Drop the hard stdin-TTY gate that broke `echo y | …`. Keep EOF decline and
add a short non-TTY timeout so an open pipe that never writes cannot hang.
Clarify isTTY as admit-only; extract the readline mock factory.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): keep partial piped step-up answers (round-10)

Capture readline `line` before close so `printf y` without a newline is
not treated as decline; timeout is auth_required with a distinct message;
document the 5s bound and post-confirm callback wait; pin the TTY no-timeout arm.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli): tighten step-up timeout messaging and TTY test (round-11)

Make the TTY no-timeout assertion use a settled flag (the Promise.race
check was vacuous), say "timed out" instead of "declined" on the pipe
bound, and document that piped answers need a newline or stdin close.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Bob Dickinson 2026-07-26 13:55:25 -07:00 • committed by GitHub
commit 33e88eac9f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -0,0 +1,226 @@
import type {
InspectorServerSettings,
MCPServerConfig,
} from "@inspector/core/mcp/types.js";
import { InMemorySecretStore } from "@inspector/core/auth/node/secret-store.js";
import {
loadServerEntries,
selectServerEntry,
type ServerLoadOptions,
} from "@inspector/core/mcp/node/index.js";
/** One catalog/config entry as returned by `servers/list`. */
export type ServerListEntry = {
name: string;
type: string;
/** Command line, URL, or other short identity for display. */
detail: string;
/**
* Optional live-session name when a caller annotates catalog entries
* with connected sessions (omitted for plain catalog listing).
*/
session?: string;
/** True when that session is the most-recently-used connected session. */
isMru?: boolean;
};
/** Minimal session shape needed to annotate catalog entries. */
export type SessionListRef = {
name: string;
isMru?: boolean;
};
/**
* Mark catalog entries that have a live session with the same name.
* Does not mutate `entries`.
*
* TODO(#1432): consumed by the experimental session CLI (`mcpi`); kept here so
* that client can reuse catalog listing without duplicating this helper.
*/
export function annotateServerEntriesWithSessions(
entries: ServerListEntry[],
sessions: SessionListRef[],
): ServerListEntry[] {
if (sessions.length === 0) return entries;
const byName = new Map(sessions.map((s) => [s.name, s] as const));
return entries.map((entry) => {
const session = byName.get(entry.name);
if (!session) return entry;
return {
...entry,
session: session.name,
...(session.isMru === true ? { isMru: true } : {}),
};
});
}
/** Detail view for `servers/show` (secrets redacted). */
export type ServerShowEntry = {
name: string;
type: string;
detail: string;
config: Record<string, unknown>;
settings?: Record<string, unknown>;
};
const REDACTED = "[redacted]";
/**
* Summarise an {@link MCPServerConfig} for catalog listing (no connection).
*/
export function summarizeServerConfig(config: MCPServerConfig): {
type: string;
detail: string;
} {
// Narrow on the URL-bearing transports first — stdio's `type` is optional, so
// an else-after-`=== "stdio"` check would still leave `StdioServerConfig` in
// the residual union (see `StdioServerConfig` in core/mcp/types.ts).
if (config.type === "sse" || config.type === "streamable-http") {
return { type: config.type, detail: config.url ?? "" };
}
const args = config.args?.length ? ` ${config.args.join(" ")}` : "";
return { type: "stdio", detail: `${config.command}${args}` };
}
/**
* Load catalog/config entries and return a sorted name + summary list.
* Uses an empty in-memory secret store by default so listing never touches the
* OS keychain (names/types/details do not need rehydrated secrets).
*/
export async function listServerEntries(
serverOptions: ServerLoadOptions = {},
): Promise<ServerListEntry[]> {
const entries = await loadServerEntries({
...serverOptions,
secretStore: serverOptions.secretStore ?? new InMemorySecretStore(),
});
return Object.entries(entries)
.map(([name, resolved]) => {
const { type, detail } = summarizeServerConfig(resolved.config);
return { name, type, detail };
})
.sort((a, b) => a.name.localeCompare(b.name));
}
/**
* Resolve one catalog/config entry for `servers/show` (no MCP connection).
* Secret-bearing fields (env values, OAuth client secret, sensitive headers)
* are replaced with {@link REDACTED}.
*/
export async function showServerEntry(
serverName: string,
serverOptions: ServerLoadOptions = {},
): Promise<ServerShowEntry> {
const name = serverName.trim();
if (!name) {
throw new Error("servers/show requires a server name.");
}
const entries = await loadServerEntries(serverOptions);
const selected = selectServerEntry(entries, name);
const { type, detail } = summarizeServerConfig(selected.config);
const result: ServerShowEntry = {
name,
type,
detail,
config: sanitizeServerConfig(selected.config),
};
if (selected.settings) {
result.settings = sanitizeServerSettings(selected.settings);
}
return result;
}
/** Visible for tests. */
export function sanitizeServerConfig(
config: MCPServerConfig,
): Record<string, unknown> {
const out: Record<string, unknown> = { ...config };
if ("env" in config && config.env) {
out.env = redactStringRecord(config.env);
}
if ("requestInit" in config && isPlainObject(config.requestInit)) {
out.requestInit = sanitizeInitRecord(config.requestInit);
}
if ("eventSourceInit" in config && isPlainObject(config.eventSourceInit)) {
out.eventSourceInit = sanitizeInitRecord(config.eventSourceInit);
}
return out;
}
/** Visible for tests. */
export function sanitizeServerSettings(
settings: InspectorServerSettings,
): Record<string, unknown> {
const out: Record<string, unknown> = {
...settings,
headers: (settings.headers ?? []).map((h) => ({
key: h.key,
value: isSensitiveHeader(h.key) ? REDACTED : h.value,
})),
metadata: (settings.metadata ?? []).map((m) => ({
key: m.key,
value: isSensitiveHeader(m.key) ? REDACTED : m.value,
})),
env: (settings.env ?? []).map((e) => ({
key: e.key,
value: REDACTED,
})),
};
if (settings.oauthClientSecret !== undefined) {
out.oauthClientSecret = REDACTED;
}
return out;
}
function redactStringRecord(
record: Record<string, string>,
): Record<string, string> {
return Object.fromEntries(Object.keys(record).map((key) => [key, REDACTED]));
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
/** Redact sensitive header values inside requestInit / eventSourceInit. */
function sanitizeInitRecord(
init: Record<string, unknown>,
): Record<string, unknown> {
const out: Record<string, unknown> = { ...init };
if (isPlainObject(init.headers)) {
out.headers = Object.fromEntries(
Object.entries(init.headers).map(([key, value]) => [
key,
isSensitiveHeader(key) ? REDACTED : value,
]),
);
} else if (Array.isArray(init.headers)) {
// HeadersInit pair form: [["Authorization", "Bearer …"], …]
out.headers = init.headers.map((entry) => {
if (
Array.isArray(entry) &&
entry.length >= 2 &&
typeof entry[0] === "string"
) {
const key = entry[0];
const value = entry[1];
return [key, isSensitiveHeader(key) ? REDACTED : value];
}
return entry;
});
}
return out;
}
function isSensitiveHeader(key: string): boolean {
const k = key.toLowerCase();
return (
k.includes("auth") ||
k.includes("cookie") ||
k.includes("secret") ||
k.includes("token") ||
k.includes("password") ||
k.includes("api-key") ||
k.includes("apikey")
);
}