import { C as ClientCapabilityOptions, M as MCPServerConfig, R as RpcLogger, a as RetryPolicy, H as HttpServerConfig } from './types-BJY6bi4K.js';
import { p as probeMcpServer, C as ConnectedServerDoctorState, S as ServerDoctorResult, O as OAuthProtocolVersion, R as RegistrationStrategy2025_03_26, k as RegistrationStrategy2025_06_18, l as RegistrationStrategy2025_11_25, u as OAuthAuthMode, B as BaseOAuthStateMachineConfig, t as OAuthStateMachine, o as OAuthFlowStep, H as HttpHistoryEntry, m as OAuthFlowState, M as MaybePromise } from './server-doctor-core-D4xjC7Kq.js';
import { M as MCPClientManager } from './index-B5O2YzC_.js';

declare const MCP_UI_EXTENSION_ID = "io.modelcontextprotocol/ui";
declare const MCP_UI_RESOURCE_MIME_TYPE = "text/html;profile=mcp-app";
declare function getDefaultClientCapabilities(): ClientCapabilityOptions;
declare function normalizeClientCapabilities(capabilities?: ClientCapabilityOptions): ClientCapabilityOptions;
/**
 * Adds runtime-gated capabilities that are only valid when the corresponding
 * handlers are actually installed on the client.
 */
declare function applyRuntimeClientCapabilities(capabilities?: ClientCapabilityOptions, runtime?: {
    elicitation?: boolean;
}): ClientCapabilityOptions;
declare function mergeClientCapabilities(base?: ClientCapabilityOptions, overrides?: ClientCapabilityOptions): ClientCapabilityOptions;

interface RunServerDoctorInput<TTarget = unknown> {
    config: MCPServerConfig;
    target: TTarget;
    timeout: number;
    rpcLogger?: RpcLogger;
    retryPolicy?: RetryPolicy;
}
type WithConnectedManager = <T>(config: MCPServerConfig, fn: (manager: MCPClientManager, serverId: string) => Promise<T>, options?: {
    timeout?: number;
    rpcLogger?: RpcLogger;
    retryPolicy?: RetryPolicy;
}) => Promise<T>;
interface ServerDoctorDependencies {
    probeServer?: typeof probeMcpServer;
    withManager?: WithConnectedManager;
}
declare function runServerDoctor<TTarget = unknown>(input: RunServerDoctorInput<TTarget>, dependencies?: ServerDoctorDependencies): Promise<ServerDoctorResult<TTarget>>;
declare function collectConnectedServerDoctorState(manager: MCPClientManager, serverId: string): Promise<ConnectedServerDoctorState>;

type OAuthRegistrationStrategy = RegistrationStrategy2025_03_26 | RegistrationStrategy2025_06_18 | RegistrationStrategy2025_11_25;
type OAuthProtocolMode = "auto" | OAuthProtocolVersion;
type OAuthRegistrationMode = "auto" | OAuthRegistrationStrategy;
interface AuthorizationDiscoverySnapshot {
    registrationStrategies?: Array<"preregistered" | "dcr" | "cimd">;
    authorizationServerMetadataUrl?: string;
    authorizationServerMetadata?: Record<string, unknown>;
    resourceMetadataUrl?: string;
    resourceMetadata?: Record<string, unknown>;
    discoveryError?: string;
}
interface AuthorizationPlanInput {
    serverUrl?: string;
    protocolMode?: OAuthProtocolMode;
    protocolVersion?: OAuthProtocolVersion;
    registrationMode?: OAuthRegistrationMode;
    registrationStrategy?: OAuthRegistrationStrategy;
    clientId?: string;
    clientSecret?: string;
    hasClientSecret?: boolean;
    clientIdMetadataUrl?: string;
    useRegistryOAuthProxy?: boolean;
    authMode?: OAuthAuthMode;
    discovery?: AuthorizationDiscoverySnapshot;
}
interface AuthorizationPlanCapabilities {
    registrationStrategies: Array<"preregistered" | "dcr" | "cimd">;
    supportsCimd: boolean;
    supportsDcr: boolean;
    authorizationServerMetadataUrl?: string;
    resourceMetadataUrl?: string;
    discoveryError?: string;
}
type AuthorizationPlanBlockerCode = "PREREGISTERED_MISSING_CLIENT_ID" | "PREREGISTERED_MISSING_CLIENT_SECRET" | "CIMD_UNSUPPORTED_PROTOCOL" | "CIMD_UNSUPPORTED_AUTH_MODE" | "CIMD_NOT_ADVERTISED" | "DCR_NOT_ADVERTISED" | "AUTO_INCOMPLETE_PREREGISTERED_CREDENTIALS" | "AUTO_NO_CLIENT_CREDENTIALS_COMPATIBLE_FLOW" | "AUTO_NO_USABLE_REGISTRATION_FLOW";
interface AuthorizationPlanBlocker {
    code: AuthorizationPlanBlockerCode;
    message: string;
}
interface ResolvedAuthorizationPlan {
    protocolMode: OAuthProtocolMode;
    protocolVersion: OAuthProtocolVersion;
    registrationMode: OAuthRegistrationMode;
    registrationStrategy?: OAuthRegistrationStrategy;
    status: "ready" | "discovery_required" | "blocked";
    blockerDetails: AuthorizationPlanBlocker[];
    blockers: string[];
    warnings: string[];
    capabilities: AuthorizationPlanCapabilities;
    canonicalResource?: string;
    clientIdMetadataUrl?: string;
    summary: string;
}
declare function resolveRegistrationStrategies(protocolVersion: OAuthProtocolVersion, authServerMetadata: Record<string, unknown> | undefined): Array<"preregistered" | "dcr" | "cimd">;
declare function resolveAuthorizationPlan(input: AuthorizationPlanInput): ResolvedAuthorizationPlan;

/**
 * Factory for creating protocol-specific OAuth state machines
 *
 * This factory selects the appropriate state machine implementation
 * based on the protocol version specified in the configuration.
 */

/**
 * Configuration for creating an OAuth state machine with protocol version selection
 */
interface OAuthStateMachineFactoryConfig extends BaseOAuthStateMachineConfig {
    protocolVersion: OAuthProtocolVersion;
    registrationStrategy: RegistrationStrategy2025_03_26 | RegistrationStrategy2025_06_18 | RegistrationStrategy2025_11_25;
}
/**
 * Creates an OAuth state machine based on the specified protocol version
 *
 * @param config - Configuration including protocol version and registration strategy
 * @returns An OAuth state machine implementation for the specified protocol version
 *
 * @example
 * ```typescript
 * // Create a 2025-11-25 state machine with CIMD
 * const machine = createOAuthStateMachine({
 *   protocolVersion: "2025-11-25",
 *   registrationStrategy: "cimd",
 *   serverUrl: "https://mcp.example.com",
 *   serverName: "Example MCP Server",
 *   state: EMPTY_OAUTH_FLOW_STATE,
 *   updateState: (updates) => setState(updates),
 * });
 *
 * // Create a 2025-06-18 state machine with DCR
 * const legacyMachine = createOAuthStateMachine({
 *   protocolVersion: "2025-06-18",
 *   registrationStrategy: "dcr",
 *   serverUrl: "https://mcp.example.com",
 *   serverName: "Legacy MCP Server",
 *   state: EMPTY_OAUTH_FLOW_STATE,
 *   updateState: (updates) => setState(updates),
 * });
 * ```
 */
declare function createOAuthStateMachine(config: OAuthStateMachineFactoryConfig): OAuthStateMachine;
/**
 * Gets the default registration strategy for a given protocol version
 */
declare function getDefaultRegistrationStrategy(protocolVersion: OAuthProtocolVersion): string;
/**
 * Gets the supported registration strategies for a given protocol version
 */
declare function getSupportedRegistrationStrategies(protocolVersion: OAuthProtocolVersion): ReadonlyArray<string>;
/**
 * Protocol version metadata for UI display
 */
declare const PROTOCOL_VERSION_INFO: {
    readonly "2025-03-26": {
        readonly label: "2025-03-26 (Legacy)";
        readonly description: "Original MCP OAuth specification with direct discovery";
        readonly features: readonly ["Dynamic Client Registration (DCR) SHOULD be supported", "Direct RFC8414 discovery from MCP server base URL", "Fallback to default endpoints (/authorize, /token, /register)", "PKCE is REQUIRED for all clients", "No Protected Resource Metadata (RFC9728)"];
    };
    readonly "2025-06-18": {
        readonly label: "2025-06-18";
        readonly description: "Current MCP OAuth specification with resource metadata";
        readonly features: readonly ["Dynamic Client Registration (DCR) SHOULD be supported", "Protected Resource Metadata (RFC9728) required", "RFC8414 discovery ONLY (no OIDC) with root fallback", "PKCE recommended but not strictly enforced"];
    };
    readonly "2025-11-25": {
        readonly label: "2025-11-25 (Latest)";
        readonly description: "Proposed MCP OAuth specification with CIMD support";
        readonly features: readonly ["Client ID Metadata Documents (CIMD) SHOULD be supported", "Protected Resource Metadata (RFC9728) required", "RFC8414 OR OIDC discovery without root fallback", "PKCE strictly required and enforced", "Enhanced security with URL-based client IDs"];
    };
};

type OAuthTraceStepStatus = "pending" | "success" | "error";
interface OAuthTraceStepSnapshot {
    step: OAuthFlowStep;
    title: string;
    status: OAuthTraceStepStatus;
    message?: string;
    error?: string;
    details?: Record<string, unknown>;
    recovered?: boolean;
    recoveredAt?: number;
    recoveryMessage?: string;
    startedAt: number;
    completedAt?: number;
}
interface OAuthTraceSnapshot {
    version: 1;
    currentStep: OAuthFlowStep;
    steps: OAuthTraceStepSnapshot[];
    httpHistory: HttpHistoryEntry[];
    error?: string;
}
interface OAuthTraceProjectionContext {
    syntheticStepTimestamps: Partial<Record<OAuthFlowStep, number>>;
    lastSyntheticTimestamp: number;
}
declare function createOAuthTraceProjectionContext(): OAuthTraceProjectionContext;
declare function projectOAuthTraceSnapshot(input: {
    state: OAuthFlowState;
    context?: OAuthTraceProjectionContext;
    /**
     * When true (default), redact tokens/secrets/PII from traces. SDK consumers
     * that are local dev tools may set false to show raw request/response data.
     */
    sanitize?: boolean;
}): OAuthTraceSnapshot;

type OAuthAuthorizationRequestResult = {
    type: "authorization_code";
    authorizationCode: string;
} | {
    type: "redirect";
};
interface OAuthStateMachineRunConfig extends OAuthStateMachineFactoryConfig {
    maxSteps?: number;
    /** When true (default), trace snapshots redact secrets. Set false for local dev tooling. */
    sanitizeTrace?: boolean;
    onAuthorizationRequest?: (input: {
        authorizationUrl: string;
        state: OAuthFlowState;
    }) => MaybePromise<OAuthAuthorizationRequestResult>;
    onTraceUpdate?: (input: {
        trace: OAuthTraceSnapshot;
        state: OAuthFlowState;
        reason: "state_update" | "redirect" | "error" | "complete";
    }) => void;
}
interface OAuthStateMachineRunResult {
    completed: boolean;
    redirected: boolean;
    authorizationUrl?: string;
    state: OAuthFlowState;
    error?: {
        message: string;
    };
}
declare function runOAuthStateMachine(config: OAuthStateMachineRunConfig): Promise<OAuthStateMachineRunResult>;

interface OAuthStepInfo {
    title: string;
    summary: string;
    teachableMoments?: string[];
    tips?: string[];
}
declare function getStepInfo(step: OAuthFlowStep): OAuthStepInfo;
declare function getStepIndex(step: OAuthFlowStep): number;

type ConformanceSuiteId = "protocol" | "apps" | "oauth";
interface ConformanceSupport {
    /** Whether the suite can run against the given server config. */
    supported: boolean;
    /** Human-readable reason surfaced when `supported` is false. */
    reason?: string;
}
/**
 * Narrow an arbitrary MCPServerConfig (or absent config) to the HTTP variant.
 * Accepts `null`/`undefined` so callers can feed values from loading states
 * without pre-checking — those just return `false`.
 */
declare function isHttpServerConfig(config: MCPServerConfig | null | undefined): config is HttpServerConfig;
/**
 * Centralises the "which conformance suite supports which transport" rules so
 * UI guards, server routes, and CLI commands can't drift. The check is pure —
 * it inspects config shape only, not network state. `null`/`undefined` configs
 * are treated as unsupported with a friendly reason instead of throwing.
 */
declare function canRunConformance(suite: ConformanceSuiteId, config: MCPServerConfig | null | undefined): ConformanceSupport;

/**
 * Pure resolver for the host-side sandbox policy applied to UI resources
 * (MCP Apps per SEP-1865, plus any ChatGPT-Apps surface that mounts
 * untrusted UI in a sandbox iframe).
 *
 * Lives in `@mcpjam/sdk` rather than the inspector client so the same
 * resolver is consumed by both:
 *   - `mcp-apps-renderer.tsx` (client-side MCP Apps rendering)
 *   - any ChatGPT-Apps renderer / server-side route that builds CSP
 *     headers for untrusted UI
 *
 * No DOM, no React, no Convex — pure JSON in / JSON out. Trivially unit-
 * testable. If the resolution lives in two places it can be bypassed by
 * mounting through the path that didn't get updated, which is exactly
 * the failure mode this single source of truth prevents.
 *
 * Precedence (mirror SEP-1865 + agreed plan):
 *
 *   1. `mode` picks the starting BASELINE:
 *      - `"declared"`:    baseline = resource's `_meta.ui.csp` declaration
 *      - `"host-default"`: baseline = inspector's default CSP shape
 *      - `"relaxed"`:     baseline = permissive (local/dev). Hosted clamp
 *                         (step 4) still strips dangerous values.
 *   2. `restrictTo` INTERSECTS with the baseline. Never unions —
 *      hosts MAY further restrict but MUST NOT allow undeclared domains.
 *      Applies in EVERY mode, including `"declared"`.
 *   3. `deny` SUBTRACTS from the current effective set. Wins over
 *      `restrictTo`, the baseline, and the resource declaration.
 *      Applies in EVERY mode.
 *   4. HOSTED-MODE HARD CLAMP — strips dangerous values regardless of
 *      profile (wildcards, localhost/private networks, unsafe schemes).
 *      Built-in patterns are NOT configurable from `mcpProfile`. Callers
 *      may pass an additional `hostedClampExtraDeny` set for app-specific
 *      origins they want stripped (e.g. the inspector's own API origin —
 *      this is the only place that protects against a hosted widget
 *      declaring same-origin exfiltration targets in `connectDomains`).
 *
 * Result is a typed `EffectiveSandboxCsp` carrying the four directive
 * lists ready for header-string construction by a downstream helper
 * (e.g. `buildCspHeader` in `widget-helpers.ts`).
 */
/**
 * Host-config sandbox CSP mode. Mirrors
 * `mcpProfile.apps.sandbox.csp.mode` from the backend's
 * `HostConfigMcpProfileV1`.
 */
type SandboxCspMode = "host-default" | "declared" | "relaxed";
/**
 * Host-config permissions mode. Mirrors
 * `mcpProfile.apps.sandbox.permissions.mode`.
 */
type SandboxPermissionsMode = "resource-declared" | "deny-all" | "custom";
/**
 * Four parallel allow/deny lists keyed by CSP directive family.
 * Mirrors `CspDomainSet` in the backend's
 * `convex/lib/hostConfigV2.ts:46`.
 */
interface SandboxCspDomainSet {
    connectDomains?: string[];
    resourceDomains?: string[];
    frameDomains?: string[];
    baseUriDomains?: string[];
}
/**
 * The `apps.sandbox.csp` slice of the host-config mcpProfile envelope.
 * Optional everywhere: undefined fields mean "no host-level override at
 * this layer." Mirrors
 * `mcpProfile.apps.sandbox.csp` in the backend schema.
 */
interface SandboxCspPolicy {
    mode?: SandboxCspMode;
    restrictTo?: SandboxCspDomainSet;
    deny?: SandboxCspDomainSet;
}
/**
 * The `apps.sandbox.permissions` slice. Mirrors
 * `mcpProfile.apps.sandbox.permissions`.
 *
 * **Key shape:** `allow` keys and `deny` entries MUST use the same
 * names as the MCP `_meta.ui.permissions` declaration (SEP-1865
 * §UIResourceMeta — camelCase: `camera`, `microphone`, `geolocation`,
 * `clipboardWrite`). The resolver does plain string-key matching
 * against `resourcePermissions`, so any kebab-case entries (`clipboard-
 * write`) will silently no-op — the spec's kebab form belongs at the
 * iframe `allow=` attribute layer, not here.
 */
interface SandboxPermissionsPolicy {
    mode?: SandboxPermissionsMode;
    allow?: Record<string, boolean>;
    deny?: string[];
}
/**
 * What the resource declared in its `_meta.ui.csp`. Same four directive
 * families. Undefined = the resource declared nothing (the SEP-1865
 * "secure default" applies, which the baseline picker fabricates from
 * mode).
 */
interface ResourceDeclaredCsp {
    connectDomains?: string[];
    resourceDomains?: string[];
    frameDomains?: string[];
    baseUriDomains?: string[];
}
/**
 * Result of the resolver. Caller turns this into a real CSP header
 * string with whatever builder it uses (e.g. `buildCspHeader` for
 * inspector renderers).
 */
interface EffectiveSandboxCsp {
    /** Final effective CSP-directive lists after all 4 precedence steps. */
    connectDomains: string[];
    resourceDomains: string[];
    frameDomains: string[];
    baseUriDomains: string[];
    /** Trace of how the resolver arrived at the result — for debug UI. */
    trace: {
        /** Step 1 — baseline picked by `mode`. */
        baseline: ResourceDeclaredCsp;
        /** Step 2 — after `restrictTo ∩ baseline`. */
        afterRestrictTo: ResourceDeclaredCsp;
        /** Step 3 — after subtracting `deny`. */
        afterDeny: ResourceDeclaredCsp;
        /** Step 4 — values the hosted-mode clamp stripped. Empty when not hosted. */
        hostedClamp: {
            stripped: SandboxCspDomainSet;
        };
        /** Which mode was applied (after default substitution). */
        effectiveMode: SandboxCspMode;
    };
}
/**
 * Sandbox permissions set after resolution. Boolean map keyed by
 * permission name — `true` means granted to the iframe (`allow=`
 * attribute), `false` (or absent) means not granted.
 */
interface EffectiveSandboxPermissions {
    granted: Record<string, boolean>;
    trace: {
        declared: Record<string, boolean>;
        afterMode: Record<string, boolean>;
        deniedByProfile: string[];
        deniedByHostedClamp: string[];
        effectiveMode: SandboxPermissionsMode;
    };
}
interface ResolveSandboxCspArgs {
    /** What the UI resource declared in `_meta.ui.csp`. */
    resourceCsp?: ResourceDeclaredCsp;
    /** Host-config policy from `mcpProfile.apps.sandbox.csp`. */
    policy?: SandboxCspPolicy;
    /**
     * Inspector's renderer default baseline for `mode: "host-default"`. The
     * resolver doesn't fabricate this — the caller supplies it because
     * "what counts as the inspector's default" is a UI concern. Today the
     * inspector uses `buildCspHeader` in `widget-helpers.ts` to compute
     * permissive vs widget-declared baselines; callers can synthesize
     * the resource-list shape from there or pass any shape they want.
     */
    hostDefaultBaseline?: ResourceDeclaredCsp;
    /**
     * SEP-1865 "secure default" applied when the resource omits its CSP
     * declaration AND mode is `"declared"`. Defaults to the empty
     * record (no domains allowed) per the spec. Callers may override if
     * they need to allow specific protocol-mandated sources.
     */
    secureDefault?: ResourceDeclaredCsp;
    /**
     * Whether the inspector is running in hosted mode. Drives the hosted
     * clamp (step 4). Callers detect this however they currently do —
     * the resolver doesn't sniff env or origin.
     */
    hostedMode: boolean;
    /**
     * App-specific origins the hosted clamp MUST strip in addition to the
     * built-in `isHostedDangerousDomain` patterns. Only applied when
     * `hostedMode === true`. Supports the same wildcard-prefix matching as
     * `policy.deny` (`https://*.example.com` matches subdomains).
     *
     * Mirrors `ResolveSandboxPermissionsArgs.hostedClampDeny`. This is the
     * only place that protects against a hosted widget declaring app-
     * sensitive origins (e.g. the inspector's own API origin) in
     * `connectDomains` to exfiltrate data — `policy.deny` is profile-
     * configurable and therefore bypassable; this is not.
     */
    hostedClampExtraDeny?: SandboxCspDomainSet;
}
interface ResolveSandboxPermissionsArgs {
    /**
     * Permissions the resource requested in its `_meta.ui.permissions`.
     * Boolean map keyed by permission name as declared in SEP-1865
     * (camelCase: `camera`, `microphone`, `geolocation`, `clipboardWrite`).
     * The kebab-case forms (`clipboard-write`) are the browser
     * Permission-Policy spelling and belong at the iframe `allow=`
     * attribute layer — not here. The resource declaration is the
     * CEILING: the host can't grant a permission the resource didn't
     * request.
     */
    resourcePermissions?: Record<string, boolean>;
    policy?: SandboxPermissionsPolicy;
    /**
     * Whether the inspector is running in hosted mode. Drives the hosted
     * clamp for sensitive permissions.
     */
    hostedMode: boolean;
    /**
     * Permission names the hosted-mode clamp must strip regardless of
     * profile. Defaults to the SEP-1865-sensitive set
     * (`camera`, `microphone`, `geolocation`). Callers may pass a
     * different list if their hosted-mode policy diverges.
     */
    hostedClampDeny?: string[];
}
/**
 * Resolve the effective sandbox CSP for a UI resource given the host's
 * profile and hosted-mode flag. See module docstring for precedence.
 *
 * @example
 * const csp = resolveSandboxCsp({
 *   resourceCsp: { connectDomains: ["api.example.com", "evil.com"] },
 *   policy: { mode: "declared", deny: { connectDomains: ["evil.com"] } },
 *   hostedMode: false,
 * });
 * // csp.connectDomains === ["api.example.com"]
 */
declare function resolveSandboxCsp(args: ResolveSandboxCspArgs): EffectiveSandboxCsp;
/**
 * Resolve sandbox permissions for a UI resource. Resource declaration is
 * the ceiling; `mode` chooses posture; `deny` wins; hosted clamp strips
 * sensitive permissions regardless.
 */
declare function resolveSandboxPermissions(args: ResolveSandboxPermissionsArgs): EffectiveSandboxPermissions;

export { type AuthorizationDiscoverySnapshot as A, createOAuthTraceProjectionContext as B, type ConformanceSuiteId as C, getDefaultClientCapabilities as D, type EffectiveSandboxCsp as E, getDefaultRegistrationStrategy as F, getStepIndex as G, getStepInfo as H, getSupportedRegistrationStrategies as I, isHttpServerConfig as J, mergeClientCapabilities as K, normalizeClientCapabilities as L, MCP_UI_EXTENSION_ID as M, projectOAuthTraceSnapshot as N, type OAuthAuthorizationRequestResult as O, PROTOCOL_VERSION_INFO as P, resolveAuthorizationPlan as Q, type ResolveSandboxCspArgs as R, type SandboxCspDomainSet as S, resolveRegistrationStrategies as T, resolveSandboxCsp as U, resolveSandboxPermissions as V, runOAuthStateMachine as W, type OAuthStepInfo as X, collectConnectedServerDoctorState as Y, runServerDoctor as Z, type AuthorizationPlanCapabilities as a, type AuthorizationPlanInput as b, type ConformanceSupport as c, type EffectiveSandboxPermissions as d, MCP_UI_RESOURCE_MIME_TYPE as e, type OAuthProtocolMode as f, type OAuthRegistrationMode as g, type OAuthRegistrationStrategy as h, type OAuthStateMachineRunConfig as i, type OAuthStateMachineRunResult as j, type OAuthTraceProjectionContext as k, type OAuthTraceSnapshot as l, type OAuthTraceStepSnapshot as m, type OAuthTraceStepStatus as n, type ResolveSandboxPermissionsArgs as o, type ResolvedAuthorizationPlan as p, type ResourceDeclaredCsp as q, type RunServerDoctorInput as r, type SandboxCspMode as s, type SandboxCspPolicy as t, type SandboxPermissionsMode as u, type SandboxPermissionsPolicy as v, type ServerDoctorDependencies as w, applyRuntimeClientCapabilities as x, canRunConformance as y, createOAuthStateMachine as z };
