Guided-auth removal, OAuth smoke testing, and TUI/CLI support (#1531)

* refactor(web): update OAuth E2E tests to use new authentication method

- Replaced `runGuidedAuth` with `authenticate` in the InspectorClient OAuth end-to-end tests to support quick authentication with CIMD pre-registration.
- Updated comments to reflect the change in authentication method and its support for HTTP test metadata URLs.
- Ensured that the tests continue to validate the expected authorization URL after the change.

Additionally, imported `ensureCimdClientRegistration` in the OAuthManager to streamline client registration during the authentication process.

* Guided-auth removal, OAuth smoke testing, and TUI/CLI support

* Added CLI OAuth runner flags tests

* Added clarifying comment on port 0 binding

* README notes on TUI oauth callback port, prettier fixes for CLI tests

* CIMD validation uses inline like EMA IdP

* Fixed TUI test failures from merge

* test: bring 5 OAuth files over the 90 per-file coverage gate

The guided-auth-removal work added/touched several files that fell below
the repo's >=90 per-file coverage gate (npm run coverage). CI doesn't run
the gate (it's local-only), so validate + test:integration passed while
these gaps slipped through. Bring them all back over the line:

- core/auth/node/runner-oauth-callback.ts: test bad-URL/non-http-scheme
  throws, no-port->80 default, and IPv6 hostname bracketing. Annotate the
  provably-dead guards (empty host, out-of-range port, String(err)
  fallback, pathname "/" fallback) -- all rejected by new URL() upstream --
  with justified v8 ignore comments instead of lowering the gate.
- core/auth/cimd.ts: test the AS-doesn't-support-CIMD early return.
- core/react/useClientSettingsDraft.ts: test the functional-updater path,
  the stale-onChange-after-close prev===null guard, and the
  timer-fires-after-close value===null guard.
- ClientSettingsForm.tsx: test the CIMD checkbox toggle and CIMD URL clear.
- clients/tui/src/utils/oauthDisplay.ts: test static/dcr registration
  kinds, the expired IdP session, and the configured-scope/empty-scope
  branches of formatScopes.

npm run coverage now passes (exit 0) across web, cli, tui, launcher.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: cliffhall <cliff@futurescale.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Bob Dickinson 2026-06-29 12:35:51 -07:00 • committed by GitHub
commit 13dafe457b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
29 changed files with 5702 additions and 4444 deletions

View file

@ -55,6 +55,6 @@ export class BrowserOAuthClientProvider extends BaseOAuthClientProvider {
};
const navigation = new BrowserNavigation();
super(serverUrl, { storage, redirectUrlProvider, navigation }, "quick");
super(serverUrl, { storage, redirectUrlProvider, navigation });
}
}

54
core/auth/cimd.ts Normal file
View file

@ -0,0 +1,54 @@
import {
discoverAuthorizationServerMetadata,
discoverOAuthProtectedResourceMetadata,
} from "@modelcontextprotocol/sdk/client/auth.js";
import type { OAuthClientInformation } from "@modelcontextprotocol/sdk/shared/auth.js";
import { getAuthorizationServerUrl } from "./discovery.js";
import type { BaseOAuthClientProvider } from "./providers.js";
/**
* When the authorization server supports URL-based client IDs (SEP-991 / CIMD),
* pre-register `{ client_id: clientMetadataUrl }` before SDK `auth()`.
*
* SDK `auth()` rejects non-HTTPS `clientMetadataUrl` during registration, but
* accepts an already-stored `client_id` (including `http://` URLs used by local
* dev/test metadata servers). Production CIMD metadata documents should still
* use HTTPS per SEP-991.
*/
export async function ensureCimdClientRegistration(params: {
serverUrl: string;
provider: BaseOAuthClientProvider;
fetchFn?: typeof fetch;
}): Promise<void> {
const clientMetadataUrl = params.provider.clientMetadataUrl?.trim();
if (!clientMetadataUrl) return;
const existing = await params.provider.clientInformation();
if (existing?.client_id) return;
let resourceMetadata;
try {
resourceMetadata = await discoverOAuthProtectedResourceMetadata(
params.serverUrl,
);
} catch {
resourceMetadata = undefined;
}
const authServerUrl = getAuthorizationServerUrl(
params.serverUrl,
resourceMetadata,
);
const metadata = await discoverAuthorizationServerMetadata(authServerUrl, {
...(params.fetchFn && { fetchFn: params.fetchFn }),
});
if (!metadata?.client_id_metadata_document_supported) return;
const clientInformation: OAuthClientInformation = {
client_id: clientMetadataUrl,
};
await params.provider.saveClientInformation(clientInformation, {
registrationKind: "cimd",
});
}

View file

@ -7,7 +7,7 @@ import { getEmaIdpLoginState, normalizeIdpIssuer } from "./ema/idpSession.js";
import { idpOAuthStorageKey } from "./ema/storage.js";
import { isJwtExpired } from "./ema/jwt.js";
import type { OAuthStorage } from "./storage.js";
import type { AuthProtocol, OAuthConnectionState, OAuthFlowState } from "./types.js";
import type { AuthProtocol, OAuthClientRegistrationKind, OAuthConnectionState, OAuthFlowState } from "./types.js";
import { authProtocolFromEnterpriseManaged } from "./types.js";
export interface BuildOAuthConnectionStateParams {
@ -27,13 +27,28 @@ function isAccessTokenUsable(tokens: OAuthTokens | undefined): boolean {
function resolveClient(
preregistered: OAuthClientInformation | undefined,
dynamic: OAuthClientInformation | undefined,
dynamicRegistrationKind: Extract<
OAuthClientRegistrationKind,
"dcr" | "cimd"
> | undefined,
): OAuthConnectionState["client"] | undefined {
const info = preregistered ?? dynamic;
if (!info?.client_id) return undefined;
if (preregistered?.client_id) {
return {
registrationKind: "static",
clientId: preregistered.client_id,
hasClientSecret:
preregistered.client_secret !== undefined &&
preregistered.client_secret !== "",
};
}
if (!dynamic?.client_id) return undefined;
return {
source: preregistered ? "preregistered" : "dynamic",
clientId: info.client_id,
hasClientSecret: info.client_secret !== undefined && info.client_secret !== "",
...(dynamicRegistrationKind && {
registrationKind: dynamicRegistrationKind,
}),
clientId: dynamic.client_id,
hasClientSecret:
dynamic.client_secret !== undefined && dynamic.client_secret !== "",
};
}
@ -76,7 +91,17 @@ export async function buildOAuthConnectionState(
const authorized = isAccessTokenUsable(tokens);
const grantedScope = resolveGrantedScope(tokens, storageScope);
const client = resolveClient(preregistered, dynamic);
const registrationKind = storage.getClientRegistrationKind(serverUrl);
const dynamicRegistrationKind =
registrationKind === "dcr" || registrationKind === "cimd"
? registrationKind
: undefined;
const client = resolveClient(
preregistered,
dynamic,
preregistered?.client_id ? undefined : dynamicRegistrationKind,
);
const state: OAuthConnectionState = {
authorized,
@ -114,12 +139,31 @@ export function isServerOAuthConfigured(config: {
clientSecret?: string;
scope?: string;
enterpriseManaged?: boolean;
clientMetadataUrl?: string;
}): boolean {
return (
config.enterpriseManaged === true ||
!!config.clientId?.trim() ||
!!config.clientSecret?.trim() ||
!!config.scope?.trim()
!!config.scope?.trim() ||
!!config.clientMetadataUrl?.trim()
);
}
/** True when persisted OAuth storage has tokens or client registration for a server. */
export async function hasPersistedOAuthServerState(
storage: OAuthStorage,
serverUrl: string,
): Promise<boolean> {
const [tokens, preregistered, dynamic] = await Promise.all([
storage.getTokens(serverUrl),
storage.getClientInformation(serverUrl, true),
storage.getClientInformation(serverUrl),
]);
return !!(
tokens?.access_token ||
preregistered?.client_id ||
dynamic?.client_id
);
}

View file

@ -11,7 +11,7 @@ export function getAuthorizationServerUrl(
resourceMetadata?: OAuthProtectedResourceMetadata | null,
): URL {
const first = resourceMetadata?.authorization_servers?.[0];
// Use truthy check to match original state-machine: empty string falls back to serverUrl
// Empty string falls back to serverUrl
if (first) {
return parseHttpUrl(first, "protected resource authorization_servers[0]");
}

View file

@ -10,7 +10,7 @@ import type {
import { OAuthMetadataSchema } from "@modelcontextprotocol/sdk/shared/auth.js";
import type { OAuthStorage } from "../storage.js";
import type { EnterpriseManagedAuthIdpConfig } from "../../client/types.js";
import { generateOAuthStateWithExecution, parseHttpUrl } from "../utils.js";
import { generateOAuthState, parseHttpUrl } from "../utils.js";
import { IDP_OIDC_SCOPES } from "./constants.js";
import { isJwtExpired, jwtExpiresAtMs } from "./jwt.js";
import { idpOAuthStorageKey, normalizeIdpIssuer } from "./storage.js";
@ -66,7 +66,7 @@ export async function startIdpOidcAuthorization(params: {
const metadata = await discoverIdpMetadata(issuer, params.fetchFn);
const clientInformation = idpClientInformation(params.idp);
const storageKey = idpOAuthStorageKey(issuer);
const state = generateOAuthStateWithExecution("quick");
const state = generateOAuthState();
const issuerUrl = parseHttpUrl(issuer, "EMA IdP issuer (Client Settings)");
const { authorizationUrl, codeVerifier } = await startAuthorization(
issuerUrl,

View file

@ -1,8 +1,8 @@
// Types
export type {
OAuthStep,
AuthExecution,
AuthProtocol,
OAuthClientRegistrationKind,
MessageType,
StatusMessage,
OAuthFlowState,
@ -16,13 +16,16 @@ export {
export {
buildOAuthConnectionState,
hasPersistedOAuthServerState,
isServerOAuthConfigured,
protocolFromOAuthConfig,
} from "./connection-state.js";
export type { BuildOAuthConnectionStateParams } from "./connection-state.js";
export { ensureCimdClientRegistration } from "./cimd.js";
// Storage
export type { OAuthStorage, IdpSessionState } from "./storage.js";
export type { OAuthStorage, IdpSessionState, SaveClientInformationOptions } from "./storage.js";
export { getServerSpecificKey, OAUTH_STORAGE_KEYS } from "./storage.js";
// Providers
@ -44,10 +47,9 @@ export {
parseHttpUrl,
parseOAuthCallbackParams,
generateOAuthState,
generateOAuthStateWithExecution,
generateOAuthStateWithMode,
parseOAuthState,
generateOAuthErrorDescription,
isUnauthorizedError,
} from "./utils.js";
// Discovery
@ -55,6 +57,3 @@ export { discoverScopes } from "./discovery.js";
// Logging (re-exported from core/logging)
export { silentLogger } from "../logging/index.js";
// State Machine
export type { StateMachineContext, StateTransition } from "./state-machine.js";
export { oauthTransitions, OAuthStateMachine } from "./state-machine.js";

View file

@ -14,3 +14,12 @@ export type {
OAuthCallbackServerStartOptions,
OAuthCallbackServerStartResult,
} from "./oauth-callback-server.js";
export {
DEFAULT_RUNNER_OAUTH_CALLBACK_URL,
RUNNER_OAUTH_CALLBACK_DEFAULT_HOSTNAME,
RUNNER_OAUTH_CALLBACK_DEFAULT_PORT,
RUNNER_OAUTH_CALLBACK_PATH,
formatRunnerOAuthRedirectUrl,
parseRunnerOAuthCallbackUrl,
} from "./runner-oauth-callback.js";
export type { RunnerOAuthCallbackConfig } from "./runner-oauth-callback.js";

View file

@ -52,7 +52,7 @@ export interface OAuthCallbackServerStartResult {
/**
* Minimal HTTP server that receives OAuth 2.1 redirects at GET /oauth/callback.
* Used by TUI/CLI to complete the authorization code flow (both quick and guided).
* Used by TUI/CLI to complete the authorization code flow.
* Caller provides onCallback/onError; typically onCallback calls
* InspectorClient.completeOAuthFlow(code) then stops the server.
*/
@ -65,7 +65,8 @@ export class OAuthCallbackServer {
private onError?: OAuthErrorHandler;
/**
* Start the server. Listens on the given port (default 0 = random).
* Start the server. Port defaults to 0 (random) when omitted; TUI/CLI callers
* pass the resolved port from {@link parseRunnerOAuthCallbackUrl} (6276 by default).
* Returns port and redirectUrl for use as oauth.redirectUrl.
*/
async start(

View file

@ -0,0 +1,98 @@
/**
* Default OAuth callback URL for Node runners (TUI / CLI).
*
* Web uses the main Hono server (`localhost:6274` by default). Runners spin up
* a minimal loopback listener; default port 6276 (T9 "MCPO", MCP OAuth) avoids colliding
* with the web dev server while staying in the Inspector 627x family.
*
* Port 6276 is fixed so EMA, CIMD, and static OAuth apps can pre-register
* `http://127.0.0.1:6276/oauth/callback`. Concurrent TUI OAuth on that port is
* unsupported; override via `--callback-url` / `MCP_OAUTH_CALLBACK_URL`.
*/
export const RUNNER_OAUTH_CALLBACK_DEFAULT_HOSTNAME = "127.0.0.1";
/** Default loopback port for TUI/CLI OAuth callback (6276 ≈ T9 "MCPO", MCP OAuth). */
export const RUNNER_OAUTH_CALLBACK_DEFAULT_PORT = 6276;
export const RUNNER_OAUTH_CALLBACK_PATH = "/oauth/callback";
export const DEFAULT_RUNNER_OAUTH_CALLBACK_URL = `http://${RUNNER_OAUTH_CALLBACK_DEFAULT_HOSTNAME}:${RUNNER_OAUTH_CALLBACK_DEFAULT_PORT}${RUNNER_OAUTH_CALLBACK_PATH}`;
export interface RunnerOAuthCallbackConfig {
hostname: string;
port: number;
pathname: string;
}
/**
* Resolve the callback listener URL for TUI/CLI.
* Precedence: CLI `--callback-url` → `MCP_OAUTH_CALLBACK_URL` → default 6276.
* Pass `http://127.0.0.1:0/oauth/callback` for an OS-assigned ephemeral port.
*/
export function parseRunnerOAuthCallbackUrl(
cliCallbackUrl?: string,
): RunnerOAuthCallbackConfig {
const raw =
cliCallbackUrl?.trim() ||
process.env.MCP_OAUTH_CALLBACK_URL?.trim() ||
"";
if (!raw) {
return {
hostname: RUNNER_OAUTH_CALLBACK_DEFAULT_HOSTNAME,
port: RUNNER_OAUTH_CALLBACK_DEFAULT_PORT,
pathname: RUNNER_OAUTH_CALLBACK_PATH,
};
}
let url: URL;
try {
url = new URL(raw);
} catch (err) {
/* v8 ignore next -- new URL() only throws an Error with a message; the String(err) fallback is unreachable */
const reason = (err as Error)?.message ?? String(err);
throw new Error(`Invalid OAuth callback URL: ${reason}`);
}
if (url.protocol !== "http:") {
throw new Error("OAuth callback URL must use http scheme");
}
const hostname = url.hostname;
/* v8 ignore start -- a parseable http: URL always has a non-empty hostname; empty-host http URLs throw at new URL() above */
if (!hostname) {
throw new Error("OAuth callback URL must include a hostname");
}
/* v8 ignore stop */
/* v8 ignore next -- an http: URL always has a non-empty pathname (min "/"), so the fallback is unreachable */
const pathname = url.pathname || "/";
let port: number;
if (url.port === "") {
port = 80;
} else {
port = Number(url.port);
/* v8 ignore start -- new URL() already rejects out-of-range/non-numeric ports, so url.port is always a valid 0-65535 numeric string here */
if (
!Number.isFinite(port) ||
!Number.isInteger(port) ||
port < 0 ||
port > 65535
) {
throw new Error("OAuth callback URL port must be between 0 and 65535");
}
/* v8 ignore stop */
}
return { hostname, port, pathname };
}
/**
* Build the redirect_uri string sent to the authorization server.
* Port 0 yields `…:0/…`; the TUI overwrites `redirectUrlProvider.redirectUrl`
* with the bound listener URL before OAuth starts, so :0 is never sent to the AS.
*/
export function formatRunnerOAuthRedirectUrl(
config: RunnerOAuthCallbackConfig,
): string {
const needsBrackets =
config.hostname.includes(":") && !config.hostname.startsWith("[");
const formattedHost = needsBrackets
? `[${config.hostname}]`
: config.hostname;
return `http://${formattedHost}:${config.port}${config.pathname}`;
}

View file

@ -9,7 +9,12 @@ import {
} from "@modelcontextprotocol/sdk/shared/auth.js";
import type { OAuthStorage } from "./storage.js";
import { type createOAuthStore, type ServerOAuthState } from "./store.js";
import type { IdpSessionState, SaveTokensOptions } from "./storage.js";
import type {
IdpSessionState,
OAuthClientRegistrationKind,
SaveClientInformationOptions,
SaveTokensOptions,
} from "./storage.js";
/**
* Concrete OAuthStorage implementation parameterized on a Zustand store.
@ -39,12 +44,21 @@ export class OAuthStorageBase implements OAuthStorage {
return await OAuthClientInformationSchema.parseAsync(clientInfo);
}
getClientRegistrationKind(
serverUrl: string,
): OAuthClientRegistrationKind | undefined {
return this.store.getState().getServerState(serverUrl)
.clientRegistrationKind;
}
async saveClientInformation(
serverUrl: string,
clientInformation: OAuthClientInformation,
options: SaveClientInformationOptions,
): Promise<void> {
this.store.getState().setServerState(serverUrl, {
clientInformation,
clientRegistrationKind: options.registrationKind,
});
}
@ -54,6 +68,7 @@ export class OAuthStorageBase implements OAuthStorage {
): Promise<void> {
this.store.getState().setServerState(serverUrl, {
preregisteredClientInformation: clientInformation,
clientRegistrationKind: "static",
});
}
@ -64,6 +79,7 @@ export class OAuthStorageBase implements OAuthStorage {
updates.preregisteredClientInformation = undefined;
} else {
updates.clientInformation = undefined;
updates.clientRegistrationKind = undefined;
}
this.store.getState().setServerState(serverUrl, updates);

View file

@ -5,21 +5,20 @@ import type {
OAuthTokens,
OAuthMetadata,
} from "@modelcontextprotocol/sdk/shared/auth.js";
import type { OAuthStorage } from "./storage.js";
import type { AuthExecution } from "./types.js";
import { generateOAuthStateWithExecution } from "./utils.js";
import type { OAuthStorage, SaveClientInformationOptions } from "./storage.js";
import { generateOAuthState } from "./utils.js";
/**
* Redirect URL provider. Returns the redirect URL for the requested mode.
* Caller populates the URLs before authenticate() (e.g. from callback server).
* Redirect URL provider. Returns the redirect URL for OAuth flows.
* Caller populates the URL before authenticate() (e.g. from callback server).
*/
export interface RedirectUrlProvider {
getRedirectUrl(execution?: AuthExecution): string;
getRedirectUrl(): string;
}
/**
* Mutable redirect URL provider for TUI/CLI. Caller sets redirectUrl
* before authenticate(); same URL is used for both quick and guided flows.
* before authenticate().
*/
export class MutableRedirectUrlProvider implements RedirectUrlProvider {
redirectUrl = "";
@ -109,19 +108,13 @@ export class BaseOAuthClientProvider implements OAuthClientProvider {
protected redirectUrlProvider: RedirectUrlProvider;
protected navigation: OAuthNavigation;
public clientMetadataUrl?: string;
protected execution: AuthExecution;
constructor(
serverUrl: string,
oauthConfig: OAuthProviderConfig,
execution: AuthExecution = "quick",
) {
constructor(serverUrl: string, oauthConfig: OAuthProviderConfig) {
this.serverUrl = serverUrl;
this.storage = oauthConfig.storage;
this.redirectUrlProvider = oauthConfig.redirectUrlProvider;
this.navigation = oauthConfig.navigation;
this.clientMetadataUrl = oauthConfig.clientMetadataUrl;
this.execution = execution;
}
/**
@ -149,13 +142,12 @@ export class BaseOAuthClientProvider implements OAuthClientProvider {
return this.storage.getScope(this.serverUrl);
}
/** Redirect URL for the current flow (quick or guided). */
get redirectUrl(): string {
return this.redirectUrlProvider.getRedirectUrl(this.execution);
return this.redirectUrlProvider.getRedirectUrl();
}
get redirect_uris(): string[] {
return [this.redirectUrlProvider.getRedirectUrl("quick")];
return [this.redirectUrl];
}
get clientMetadata(): OAuthClientMetadata {
@ -176,7 +168,7 @@ export class BaseOAuthClientProvider implements OAuthClientProvider {
}
state(): string | Promise<string> {
return generateOAuthStateWithExecution(this.execution);
return generateOAuthState();
}
async clientInformation(): Promise<OAuthClientInformation | undefined> {
@ -193,8 +185,11 @@ export class BaseOAuthClientProvider implements OAuthClientProvider {
async saveClientInformation(
clientInformation: OAuthClientInformation,
options?: SaveClientInformationOptions,
): Promise<void> {
await this.storage.saveClientInformation(this.serverUrl, clientInformation);
await this.storage.saveClientInformation(this.serverUrl, clientInformation, {
registrationKind: options?.registrationKind ?? "dcr",
});
}
async saveScope(scope: string | undefined): Promise<void> {

View file

@ -1,292 +0,0 @@
import type { OAuthStep, OAuthFlowState } from "./types.js";
import type { BaseOAuthClientProvider } from "./providers.js";
import { discoverScopes, getAuthorizationServerUrl } from "./discovery.js";
import {
discoverAuthorizationServerMetadata,
registerClient,
startAuthorization,
exchangeAuthorization,
discoverOAuthProtectedResourceMetadata,
selectResourceURL,
} from "@modelcontextprotocol/sdk/client/auth.js";
import {
OAuthMetadataSchema,
type OAuthProtectedResourceMetadata,
} from "@modelcontextprotocol/sdk/shared/auth.js";
export interface StateMachineContext {
state: OAuthFlowState;
serverUrl: string;
provider: BaseOAuthClientProvider;
updateState: (updates: Partial<OAuthFlowState>) => void;
fetchFn?: typeof fetch;
}
export interface StateTransition {
canTransition: (context: StateMachineContext) => Promise<boolean>;
execute: (context: StateMachineContext) => Promise<void>;
}
// State machine transitions
export const oauthTransitions: Record<OAuthStep, StateTransition> = {
metadata_discovery: {
canTransition: async () => true,
execute: async (context) => {
let resourceMetadata: OAuthProtectedResourceMetadata | null = null;
let resourceMetadataError: Error | null = null;
try {
resourceMetadata = await discoverOAuthProtectedResourceMetadata(
context.serverUrl as string | URL,
);
} catch (e) {
if (e instanceof Error) {
resourceMetadataError = e;
} else {
resourceMetadataError = new Error(String(e));
}
}
const authServerUrl = getAuthorizationServerUrl(
context.serverUrl,
resourceMetadata,
);
const resource: URL | undefined = resourceMetadata
? await selectResourceURL(
context.serverUrl,
context.provider,
resourceMetadata,
)
: undefined;
const metadata = await discoverAuthorizationServerMetadata(
authServerUrl,
{
...(context.fetchFn && { fetchFn: context.fetchFn }),
},
);
if (!metadata) {
throw new Error("Failed to discover OAuth metadata");
}
const parsedMetadata = await OAuthMetadataSchema.parseAsync(metadata);
await context.provider.saveServerMetadata(parsedMetadata);
context.updateState({
resourceMetadata,
resource,
resourceMetadataError,
authServerUrl,
oauthMetadata: parsedMetadata,
oauthStep: "client_registration",
});
},
},
client_registration: {
canTransition: async (context) => !!context.state.oauthMetadata,
execute: async (context) => {
const metadata = context.state.oauthMetadata!;
const clientMetadata = context.provider.clientMetadata;
// Priority: user-provided scope > discovered scopes
if (!context.provider.scope || context.provider.scope.trim() === "") {
// Prefer scopes from resource metadata if available
const scopesSupported =
context.state.resourceMetadata?.scopes_supported ||
metadata.scopes_supported;
// Add all supported scopes to client registration
if (scopesSupported) {
clientMetadata.scope = scopesSupported.join(" ");
}
}
// Use pre-set client info from state (static client) when present; otherwise provider lookup → CIMD → DCR
let fullInformation =
context.state.oauthClientInfo ??
(await context.provider.clientInformation());
if (!fullInformation) {
// Check if provider has clientMetadataUrl (CIMD mode)
const clientMetadataUrl =
"clientMetadataUrl" in context.provider &&
context.provider.clientMetadataUrl
? context.provider.clientMetadataUrl
: undefined;
// Check for CIMD support (SDK handles this in authInternal - we replicate it here)
const supportsUrlBasedClientId =
metadata?.client_id_metadata_document_supported === true;
const shouldUseUrlBasedClientId =
supportsUrlBasedClientId && clientMetadataUrl;
if (shouldUseUrlBasedClientId) {
// SEP-991: URL-based Client IDs (CIMD)
// SDK creates { client_id: clientMetadataUrl } directly - no registration needed
fullInformation = {
client_id: clientMetadataUrl,
};
} else {
// Fallback to DCR registration
fullInformation = await registerClient(context.serverUrl, {
metadata,
clientMetadata,
...(context.fetchFn && { fetchFn: context.fetchFn }),
});
}
await context.provider.saveClientInformation(fullInformation);
}
context.updateState({
oauthClientInfo: fullInformation,
oauthStep: "authorization_redirect",
});
},
},
authorization_redirect: {
canTransition: async (context) =>
!!context.state.oauthMetadata && !!context.state.oauthClientInfo,
execute: async (context) => {
const metadata = context.state.oauthMetadata!;
const clientInformation = context.state.oauthClientInfo!;
// Priority: user-provided scope > discovered scopes
let scope = context.provider.scope;
if (!scope || scope.trim() === "") {
scope = await discoverScopes(
context.serverUrl,
context.state.resourceMetadata ?? undefined,
context.fetchFn,
);
}
const providerState = context.provider.state();
const state = await Promise.resolve(providerState);
const { authorizationUrl, codeVerifier } = await startAuthorization(
context.serverUrl,
{
metadata,
clientInformation,
redirectUrl: context.provider.redirectUrl,
scope,
state,
resource: context.state.resource ?? undefined,
},
);
await context.provider.saveCodeVerifier(codeVerifier);
context.updateState({
authorizationUrl: authorizationUrl,
oauthStep: "authorization_code",
});
},
},
authorization_code: {
canTransition: async () => true,
execute: async (context) => {
if (
!context.state.authorizationCode ||
context.state.authorizationCode.trim() === ""
) {
context.updateState({
validationError: "You need to provide an authorization code",
});
// Don't advance if no code
throw new Error("Authorization code required");
}
context.updateState({
validationError: null,
oauthStep: "token_request",
});
},
},
token_request: {
canTransition: async (context) => {
const hasMetadata = !!context.provider.getServerMetadata();
const clientInfo =
context.state.oauthClientInfo ??
(await context.provider.clientInformation());
return !!context.state.authorizationCode && hasMetadata && !!clientInfo;
},
execute: async (context) => {
const codeVerifier = context.provider.codeVerifier();
const metadata = context.provider.getServerMetadata();
if (!metadata) {
throw new Error("OAuth metadata not available");
}
const clientInformation =
context.state.oauthClientInfo ??
(await context.provider.clientInformation());
if (!clientInformation) {
throw new Error("Client information not available for token exchange");
}
const tokens = await exchangeAuthorization(context.serverUrl, {
metadata,
clientInformation,
authorizationCode: context.state.authorizationCode,
codeVerifier,
redirectUri: context.provider.redirectUrl,
resource: context.state.resource
? context.state.resource instanceof URL
? context.state.resource
: new URL(context.state.resource)
: undefined,
...(context.fetchFn && { fetchFn: context.fetchFn }),
});
await context.provider.saveTokens(tokens);
context.updateState({
oauthTokens: tokens,
oauthStep: "complete",
});
},
},
complete: {
canTransition: async () => false,
execute: async () => {
// No-op for complete state
},
},
};
export class OAuthStateMachine {
private serverUrl: string;
private provider: BaseOAuthClientProvider;
private updateState: (updates: Partial<OAuthFlowState>) => void;
private fetchFn?: typeof fetch;
constructor(
serverUrl: string,
provider: BaseOAuthClientProvider,
updateState: (updates: Partial<OAuthFlowState>) => void,
fetchFn?: typeof fetch,
) {
this.serverUrl = serverUrl;
this.provider = provider;
this.updateState = updateState;
this.fetchFn = fetchFn;
}
async executeStep(state: OAuthFlowState): Promise<void> {
const context: StateMachineContext = {
state,
serverUrl: this.serverUrl,
provider: this.provider,
updateState: this.updateState,
...(this.fetchFn && { fetchFn: this.fetchFn }),
};
const transition = oauthTransitions[state.oauthStep];
if (!(await transition.canTransition(context))) {
throw new Error(`Cannot transition from ${state.oauthStep}`);
}
await transition.execute(context);
}
}

View file

@ -3,6 +3,7 @@ import type {
OAuthTokens,
OAuthMetadata,
} from "@modelcontextprotocol/sdk/shared/auth.js";
import type { OAuthClientRegistrationKind } from "./types.js";
/**
* Abstract storage interface for OAuth state
@ -13,6 +14,12 @@ export interface SaveTokensOptions {
enterpriseManaged?: boolean;
}
export type { OAuthClientRegistrationKind };
export interface SaveClientInformationOptions {
registrationKind: "dcr" | "cimd";
}
export interface OAuthStorage {
/**
* Get client information (preregistered or dynamically registered)
@ -22,12 +29,20 @@ export interface OAuthStorage {
isPreregistered?: boolean,
): Promise<OAuthClientInformation | undefined>;
/**
* Get how the dynamic client registration slot was established.
*/
getClientRegistrationKind(
serverUrl: string,
): OAuthClientRegistrationKind | undefined;
/**
* Save client information (dynamically registered)
*/
saveClientInformation(
serverUrl: string,
clientInformation: OAuthClientInformation,
options: SaveClientInformationOptions,
): Promise<void>;
/**
@ -93,12 +108,12 @@ export interface OAuthStorage {
clearScope(serverUrl: string): void;
/**
* Get server metadata (for guided mode)
* Get server metadata discovered during OAuth
*/
getServerMetadata(serverUrl: string): OAuthMetadata | null;
/**
* Save server metadata (for guided mode)
* Save server metadata discovered during OAuth
*/
saveServerMetadata(serverUrl: string, metadata: OAuthMetadata): Promise<void>;

View file

@ -10,13 +10,15 @@ import type {
OAuthTokens,
OAuthMetadata,
} from "@modelcontextprotocol/sdk/shared/auth.js";
import type { IdpSessionState } from "./storage.js";
import type { IdpSessionState, OAuthClientRegistrationKind } from "./storage.js";
/**
* OAuth state for a single server
*/
export interface ServerOAuthState {
clientInformation?: OAuthClientInformation;
/** Set when {@link clientInformation} is saved — DCR vs CIMD. */
clientRegistrationKind?: OAuthClientRegistrationKind;
preregisteredClientInformation?: OAuthClientInformation;
tokens?: OAuthTokens;
codeVerifier?: string;

View file

@ -23,12 +23,12 @@ export interface StatusMessage {
message: string;
}
/** How the auth flow is stepped through (orthogonal to {@link AuthProtocol}). */
export type AuthExecution = "quick" | "guided";
/** Which authorization protocol applies (orthogonal to {@link AuthExecution}). */
/** Which authorization protocol applies. */
export type AuthProtocol = "standard" | "ema";
/** How the active OAuth client id was established for this MCP server. */
export type OAuthClientRegistrationKind = "static" | "dcr" | "cimd";
/** Persisted OAuth authorization snapshot for an HTTP MCP server (storage + config). */
export interface OAuthConnectionState {
authorized: boolean;
@ -38,8 +38,9 @@ export interface OAuthConnectionState {
grantedScope?: string;
tokens?: OAuthTokens;
client?: {
source: "preregistered" | "dynamic";
clientId: string;
/** Absent for legacy storage entries predating registration kind tracking. */
registrationKind?: OAuthClientRegistrationKind;
hasClientSecret: boolean;
};
authorizationServerMetadata?: OAuthMetadata;
@ -58,10 +59,8 @@ export function authProtocolFromEnterpriseManaged(
return enterpriseManaged ? "ema" : "standard";
}
/** In-memory snapshot while an OAuth flow is active or just completed (quick or guided). */
/** In-memory snapshot while an OAuth flow is active or just completed. */
export interface OAuthFlowState {
/** Quick (SDK / one-shot) vs guided (state machine with step events). */
execution: AuthExecution;
/** When auth reached step "complete" (ms since epoch), if applicable. */
completedAt: number | null;
isInitiatingAuth: boolean;
@ -81,11 +80,10 @@ export interface OAuthFlowState {
}
export const EMPTY_OAUTH_FLOW_STATE: OAuthFlowState = {
execution: "guided",
completedAt: null,
isInitiatingAuth: false,
oauthTokens: null,
oauthStep: "metadata_discovery",
oauthStep: "authorization_code",
oauthMetadata: null,
resourceMetadata: null,
resourceMetadataError: null,

View file

@ -1,4 +1,3 @@
import type { AuthExecution } from "./types.js";
import type { CallbackParams } from "./types.js";
/**
@ -71,47 +70,13 @@ export const generateOAuthState = (): string => {
};
/**
* Generate OAuth `state` with execution prefix for single-redirect-URL flows.
* Format: `{execution}:{authId}` (e.g. "guided:a1b2c3...").
* Protocol (standard vs EMA) is not encoded here — it comes from server config.
* The authId is 64 hex chars for CSRF protection and serves as session identifier.
* Parse OAuth `state` to extract the auth session id (CSRF token).
* Must be the 64-char hex value from {@link generateOAuthState}.
*/
export const generateOAuthStateWithExecution = (
execution: AuthExecution,
): string => {
const authId = generateOAuthState();
return `${execution}:${authId}`;
};
/** @deprecated Use {@link generateOAuthStateWithExecution}. */
export const generateOAuthStateWithMode = generateOAuthStateWithExecution;
/**
* Parse OAuth `state` to extract execution and authId.
* Returns null if invalid.
* Legacy prefixes `normal:` and `ema-idp:` map to `quick`.
* Plain 64-char hex (no prefix) is treated as quick.
*/
export const parseOAuthState = (
state: string,
): { execution: AuthExecution; authId: string } | null => {
export const parseOAuthState = (state: string): { authId: string } | null => {
if (!state || typeof state !== "string") return null;
if (state.startsWith("quick:")) {
return { execution: "quick", authId: state.slice(6) };
}
if (state.startsWith("guided:")) {
return { execution: "guided", authId: state.slice(7) };
}
// Legacy execution prefixes
if (state.startsWith("normal:")) {
return { execution: "quick", authId: state.slice(7) };
}
if (state.startsWith("ema-idp:")) {
return { execution: "quick", authId: state.slice(8) };
}
// Legacy: plain 64-char hex
if (/^[a-f0-9]{64}$/i.test(state)) {
return { execution: "quick", authId: state };
return { authId: state };
}
return null;
};
@ -136,3 +101,19 @@ export const generateOAuthErrorDescription = (
.filter(Boolean)
.join("\n");
};
/**
* True when a thrown connect error represents an upstream 401. The remote
* transport preserves the status on the error object; as a fallback, match
* transport wording `"failed …(401)"` so unrelated `(401)` in messages does
* not trigger OAuth.
*/
export function isUnauthorizedError(err: unknown): boolean {
if (typeof err === "object" && err !== null) {
const status = (err as { status?: number; code?: number }).status;
const code = (err as { code?: number }).code;
if (status === 401 || code === 401) return true;
}
const message = err instanceof Error ? err.message : String(err);
return /\bfailed\b[^\n]*\(401\)/i.test(message);
}

View file

@ -54,6 +54,76 @@ const HttpUrlStringSchema = z
}
});
/** Field-level error when a CIMD metadata URL is not a parseable http(s) URL. */
export const CIMD_METADATA_URL_INVALID_ERROR =
"Must be a valid URL, like https://example.com/oauth/client.json";
/** Field-level error when a CIMD metadata URL is not HTTPS. */
export const CIMD_METADATA_URL_HTTPS_ERROR =
"CIMD client metadata URL must use HTTPS";
/** Field-level error when a CIMD metadata URL has no path segment. */
export const CIMD_METADATA_URL_PATH_ERROR =
"Must include a path (not the site root), like https://example.com/oauth/client.json";
/**
* Inline / form validation for a non-empty CIMD client metadata URL.
* Returns undefined when the value is valid; empty strings are not flagged here
* (required-field gating lives in {@link canPersistClientSettingsDraft}).
*/
export function getCimdClientMetadataUrlError(value: string): string | undefined {
const trimmed = value.trim();
if (trimmed === "") return undefined;
if (!isAbsoluteHttpUrl(trimmed)) {
return CIMD_METADATA_URL_INVALID_ERROR;
}
try {
const url = new URL(trimmed);
if (url.protocol !== "https:") {
return CIMD_METADATA_URL_HTTPS_ERROR;
}
if (url.pathname === "/" || url.pathname === "") {
return CIMD_METADATA_URL_PATH_ERROR;
}
} catch {
return CIMD_METADATA_URL_INVALID_ERROR;
}
return undefined;
}
function refineCimdMetadataUrl(
val: string,
ctx: z.RefinementCtx,
required: boolean,
): void {
const trimmed = val.trim();
if (trimmed === "") {
if (required) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "CIMD client metadata URL is required when CIMD is enabled",
});
}
return;
}
const error = getCimdClientMetadataUrlError(trimmed);
if (error) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: error,
});
}
}
const CimdConfigSchema = z
.object({
enabled: z.boolean(),
clientMetadataUrl: z.string(),
})
.superRefine((data, ctx) => {
refineCimdMetadataUrl(data.clientMetadataUrl, ctx, data.enabled === true);
});
const EnterpriseManagedAuthIdpConfigSchema = z.object({
issuer: HttpUrlStringSchema,
clientId: z.string().min(1),
@ -67,6 +137,7 @@ const ClientConfigSchema = z.object({
idp: EnterpriseManagedAuthIdpConfigSchema,
})
.optional(),
cimd: CimdConfigSchema.optional(),
});
/**

View file

@ -1,9 +1,12 @@
export type {
ClientConfig,
CimdConfig,
EnterpriseManagedAuthIdpConfig,
} from "./types.js";
export {
getActiveCimdClientMetadataUrl,
getActiveEnterpriseManagedAuthIdp,
isCimdEnabled,
isEnterpriseManagedAuthEnabled,
} from "./types.js";
export {
@ -18,3 +21,10 @@ export {
saveClientConfigRemote,
type RemoteClientConfigOptions,
} from "./remote.js";
export {
buildRunnerClientAuthOptions,
isOAuthCapableServerConfig,
loadRunnerClientConfig,
type LoadRunnerClientConfigOptions,
type RunnerClientConfigOverrides,
} from "./runner.js";

116
core/client/runner.ts Normal file
View file

@ -0,0 +1,116 @@
/**
* Install-level client config loading and InspectorClient auth option wiring
* for Node runners (TUI, CLI).
*/
import { KeyringSecretStore } from "../auth/node/secret-store.js";
import type { InspectorClientOptions, InspectorServerSettings } from "../mcp/types.js";
import { loadClientConfig } from "./config.js";
import type { ClientConfig } from "./types.js";
import {
getActiveCimdClientMetadataUrl,
getActiveEnterpriseManagedAuthIdp,
} from "./types.js";
export interface LoadRunnerClientConfigOptions {
/** Explicit path from `--client-config` (or MCP_CLIENT_CONFIG_PATH when unset). */
clientConfigPath?: string;
}
/** Load install-level client.json with keychain-backed IdP secrets. */
export async function loadRunnerClientConfig(
options?: LoadRunnerClientConfigOptions,
): Promise<ClientConfig> {
const customPath =
options?.clientConfigPath?.trim() ||
process.env.MCP_CLIENT_CONFIG_PATH?.trim() ||
undefined;
const secretStore = new KeyringSecretStore();
return loadClientConfig({ filePath: customPath, secretStore });
}
export interface RunnerClientConfigOverrides {
clientId?: string;
clientSecret?: string;
clientMetadataUrl?: string;
}
/** HTTP transports (SSE, streamable-http) can use OAuth. */
export function isOAuthCapableServerConfig(
config: { type?: string } | null | undefined,
): boolean {
if (!config) return false;
return config.type === "sse" || config.type === "streamable-http";
}
/**
* Derive OAuth / EMA / CIMD InspectorClient options from install client.json,
* per-server settings, and CLI flag overrides (flags win over client.json).
*/
export function buildRunnerClientAuthOptions(
clientConfig: ClientConfig,
savedSettings?: InspectorServerSettings,
cliOverrides?: RunnerClientConfigOverrides,
): Pick<
InspectorClientOptions,
"oauth" | "enterpriseManagedAuth" | "installEnterpriseManagedAuth"
> {
const activeIdp = getActiveEnterpriseManagedAuthIdp(clientConfig);
const activeCimdUrl = getActiveCimdClientMetadataUrl(clientConfig);
const oauthFromServer =
savedSettings &&
(savedSettings.oauthClientId ||
savedSettings.oauthClientSecret ||
savedSettings.oauthScopes ||
savedSettings.enterpriseManaged)
? {
...(savedSettings.oauthClientId && {
clientId: savedSettings.oauthClientId,
}),
...(savedSettings.oauthClientSecret && {
clientSecret: savedSettings.oauthClientSecret,
}),
...(savedSettings.oauthScopes && {
scope: savedSettings.oauthScopes,
}),
...(savedSettings.enterpriseManaged && {
enterpriseManaged: true,
}),
}
: undefined;
const clientMetadataUrl =
cliOverrides?.clientMetadataUrl?.trim() || activeCimdUrl;
const oauthFromCli =
cliOverrides?.clientId ||
cliOverrides?.clientSecret ||
clientMetadataUrl
? {
...(cliOverrides?.clientId && { clientId: cliOverrides.clientId }),
...(cliOverrides?.clientSecret && {
clientSecret: cliOverrides.clientSecret,
}),
...(clientMetadataUrl && { clientMetadataUrl }),
}
: undefined;
const oauth =
oauthFromServer || oauthFromCli
? {
...(oauthFromServer ?? {}),
...(oauthFromCli ?? {}),
}
: undefined;
return {
...(oauth && { oauth }),
...(activeIdp && {
enterpriseManagedAuth: { idp: activeIdp },
}),
...(clientConfig.enterpriseManagedAuth && {
installEnterpriseManagedAuth: clientConfig.enterpriseManagedAuth,
}),
};
}

View file

@ -11,12 +11,20 @@ export interface EnterpriseManagedAuthIdpConfig {
clientSecret?: string;
}
/** Install-level CIMD (Client ID Metadata Document) settings. */
export interface CimdConfig {
/** When false, the metadata URL is kept but CIMD is inactive install-wide. */
enabled?: boolean;
clientMetadataUrl: string;
}
export interface ClientConfig {
enterpriseManagedAuth?: {
/** When false, IdP credentials are kept but EMA is inactive install-wide. */
enabled?: boolean;
idp: EnterpriseManagedAuthIdpConfig;
};
cimd?: CimdConfig;
}
/** True when install-level EMA IdP config is active (not just stored). */
@ -34,3 +42,16 @@ export function getActiveEnterpriseManagedAuthIdp(
if (!isEnterpriseManagedAuthEnabled(config)) return undefined;
return config.enterpriseManagedAuth!.idp;
}
/** True when install-level CIMD is active (not just stored). */
export function isCimdEnabled(config: ClientConfig): boolean {
return config.cimd?.enabled === true;
}
export function getActiveCimdClientMetadataUrl(
config: ClientConfig,
): string | undefined {
if (!isCimdEnabled(config)) return undefined;
const url = config.cimd?.clientMetadataUrl?.trim();
return url || undefined;
}

Some files were not shown because too many files have changed in this diff Show more