import { Transport, ServerCapabilities, Implementation, RequestOptions, ListToolsResult as ListToolsResult$1, CallToolResult, Request, ListResourcesResult, ReadResourceResult, ListResourceTemplatesResult, ListPromptsResult, GetPromptResult, EmptyResult, LoggingLevel, Client, OAuthClientProvider, OAuthClientMetadata, OAuthTokens, ClientOptions, StreamableHTTPClientTransportOptions, SSEClientTransportOptions, StdioServerParameters, ListTasksResult, Task, Tool as Tool$1, ElicitRequest, ElicitResult } from '@modelcontextprotocol/client';
import { M as McpProtocolVersion } from './mcp-protocol-version-cf74324S.js';
import { ToolSet } from 'ai';

/**
 * `ManagedMcpClient` is the surface area `MCPClientManager` calls into for
 * every server connection. It exists so the manager can swap between the
 * legacy upstream `Client` (via `OfficialSdkClientAdapter`) and the
 * stateless 2026-07-28 preview transport
 * (`StatelessMcpHttpPreviewClient`) without per-call branching. Selection
 * is driven by the per-server `mcpProtocolVersion` pin (`McpProtocolVersion`
 * in `./mcp-protocol-version.ts`) — the factory uses
 * `isStatelessProtocolVersion` to route.
 *
 * **Coverage rationale.** The shape below was derived by grepping
 * `MCPClientManager.ts` for every `client.*` call site, plus
 * `elicitation.ts`'s `removeRequestHandler(ElicitRequestMethod)` cleanup
 * and the manager's `subscribeResource` / `unsubscribeResource`
 * passthrough. Omitting any method would crash the manager — there is no
 * `client?.foo()` fallback for unknown surface.
 *
 * **Disposable-by-design.** When upstream `@modelcontextprotocol/client`
 * adds stateless support, replacement is a one-line factory swap to a
 * new `OfficialSdkClientAdapter` configured for the new wire literal.
 * No manager-side churn, no product / UI / config unwind.
 */

/**
 * Connect-time options accepted by both adapters. Mirror of the upstream
 * `ClientOptions.connect` second argument; we don't tighten it to keep
 * the legacy adapter a pure pass-through.
 */
interface ManagedMcpClientConnectOptions {
    timeout?: number;
    resumptionToken?: string;
    onresumptiontoken?: (token: string) => void;
}
/**
 * Notification / request handler signatures mirror upstream
 * `@modelcontextprotocol/client@2.0.0-alpha.2`. Both are method-string
 * keyed (`"sampling/createMessage"`, `"notifications/progress"`, …) —
 * the upstream Client looks up the handler in a `Map<RequestMethod,
 * Handler>` and dispatches based on incoming `jsonrpc.method`. Reusing
 * the upstream parameter types via `Parameters<Client["..."]>[N]` keeps
 * the adapter pass-through honest without re-declaring opaque generics
 * the manager doesn't need (it only ever uses the wide string form via
 * `ElicitRequestMethod` and `*NotificationMethod` constants).
 */
type ManagedMcpClientNotificationMethod = Parameters<Client["setNotificationHandler"]>[0];
type ManagedMcpClientNotificationHandler = Parameters<Client["setNotificationHandler"]>[1];
type ManagedMcpClientRequestMethod = Parameters<Client["setRequestHandler"]>[0];
type ManagedMcpClientRequestHandler = Parameters<Client["setRequestHandler"]>[1];
/**
 * The single surface the manager talks to. Every method here corresponds
 * to a verified call site in the SDK:
 *
 *   - `connect` / `close` / `onerror` / `onclose` — lifecycle, around
 *     `MCPClientManager.ts:1170-1192, 1267, 1362`.
 *   - `getServerCapabilities` / `getServerVersion` / `getInstructions` —
 *     manager state mirror at `:276, :317-319`.
 *   - `listTools` / `callTool` / `request` / `listResources` /
 *     `readResource` / `listResourceTemplates` / `listPrompts` /
 *     `getPrompt` / `ping` — RPC fan-out methods.
 *   - `subscribeResource` / `unsubscribeResource` — manager passthrough
 *     at `:700, :716`.
 *   - `setLoggingLevel` — manager auto-call at `:1225`.
 *   - `setNotificationHandler` / `setRequestHandler` — notification
 *     wiring + `applyToClient` paths.
 *   - `removeRequestHandler` — `elicitation.ts:168` close cleanup.
 *
 * Stateless preview behaviors (`StatelessMcpHttpPreviewClient`) are
 * documented per-method in that file. The interface itself stays
 * behavior-agnostic so it never has to know which adapter is wired.
 */
interface ManagedMcpClient {
    connect(transport: Transport, options?: ManagedMcpClientConnectOptions): Promise<void>;
    close(): Promise<void>;
    onerror?: (error: Error) => void;
    onclose?: () => void;
    getServerCapabilities(): ServerCapabilities | undefined;
    getServerVersion(): Implementation | undefined;
    getInstructions(): string | undefined;
    listTools(params?: {
        cursor?: string;
    }, options?: RequestOptions): Promise<ListToolsResult$1>;
    callTool(params: {
        name: string;
        arguments?: Record<string, unknown>;
    }, options?: RequestOptions): Promise<CallToolResult>;
    request<T = unknown>(req: Request, options?: RequestOptions): Promise<T>;
    listResources(params?: {
        cursor?: string;
    }, options?: RequestOptions): Promise<ListResourcesResult>;
    readResource(params: {
        uri: string;
    }, options?: RequestOptions): Promise<ReadResourceResult>;
    listResourceTemplates(params?: {
        cursor?: string;
    }, options?: RequestOptions): Promise<ListResourceTemplatesResult>;
    listPrompts(params?: {
        cursor?: string;
    }, options?: RequestOptions): Promise<ListPromptsResult>;
    getPrompt(params: {
        name: string;
        arguments?: Record<string, string>;
    }, options?: RequestOptions): Promise<GetPromptResult>;
    ping(options?: RequestOptions): Promise<EmptyResult>;
    subscribeResource(params: {
        uri: string;
    }, options?: RequestOptions): Promise<EmptyResult>;
    unsubscribeResource(params: {
        uri: string;
    }, options?: RequestOptions): Promise<EmptyResult>;
    setLoggingLevel(level: LoggingLevel, options?: RequestOptions): Promise<void>;
    setNotificationHandler(method: ManagedMcpClientNotificationMethod, handler: ManagedMcpClientNotificationHandler): void;
    setRequestHandler(method: ManagedMcpClientRequestMethod, handler: ManagedMcpClientRequestHandler): void;
    removeRequestHandler(method: ManagedMcpClientRequestMethod): void;
}

interface RetryPolicy {
    retries: number;
    retryDelayMs: number;
}
declare const DEFAULT_RETRY_POLICY: RetryPolicy;
interface RetryExecutionOptions<T> {
    policy?: RetryPolicy;
    signal?: AbortSignal;
    operation: (attempt: number) => Promise<T>;
    shouldRetryError?: (error: unknown, attempt: number) => boolean;
    shouldRetryResult?: (result: T, attempt: number) => boolean;
    onRetry?: (input: {
        attempt: number;
        error?: unknown;
        result?: T;
    }) => Promise<void> | void;
}
declare function normalizeRetryPolicy(policy?: RetryPolicy): RetryPolicy;
declare function isRetryableTransientError(error: unknown): boolean;
declare function retryWithPolicy<T>({ policy, signal, operation, shouldRetryError, shouldRetryResult, onRetry, }: RetryExecutionOptions<T>): Promise<T>;

declare class RefreshTokenOAuthProvider implements OAuthClientProvider {
    private readonly _clientId;
    private readonly _clientSecret?;
    private currentRefreshToken;
    private currentTokens?;
    constructor(_clientId: string, refreshToken: string, _clientSecret?: string | undefined);
    get redirectUrl(): undefined;
    get clientMetadata(): OAuthClientMetadata;
    clientInformation(): {
        client_id: string;
        client_secret: string;
    } | {
        client_id: string;
        client_secret?: undefined;
    };
    tokens(): {
        access_token: string;
        token_type: string;
        id_token?: string | undefined;
        expires_in?: number | undefined;
        scope?: string | undefined;
        refresh_token?: string | undefined;
    } | undefined;
    saveTokens(tokens: OAuthTokens): void;
    prepareTokenRequest(): URLSearchParams;
    redirectToAuthorization(): void;
    saveCodeVerifier(): void;
    codeVerifier(): string;
}

/**
 * Client capability options extracted from MCP SDK ClientOptions
 */
type ClientCapabilityOptions = NonNullable<ClientOptions["capabilities"]>;
/**
 * Base configuration shared by all server types
 */
type BaseServerConfig = {
    /** Legacy merge-style client capabilities to advertise to this server */
    capabilities?: ClientCapabilityOptions;
    /**
     * Exact client capabilities to advertise to this server.
     * When provided, this bypasses manager defaults and legacy capability merging.
     */
    clientCapabilities?: ClientCapabilityOptions;
    /** Request timeout in milliseconds */
    timeout?: number;
    /** Client version to report */
    version?: string;
    /**
     * Per-server override of `clientInfo` sent in MCP `initialize`. When set,
     * takes precedence over the manager's `defaultClientName` /
     * `defaultClientVersion` and the per-server `version`. Extra fields
     * (e.g. `title`) are passed through verbatim so future spec additions
     * land here without an SDK bump.
     *
     * Wired into the inspector via `hostConfig.mcpProfile.initialize.clientInfo`.
     * Leaving this undefined means "use the manager defaults" (which is what
     * historical callers expect).
     */
    clientInfo?: {
        name?: string;
        version?: string;
    } & Record<string, unknown>;
    /**
     * Supported protocol versions accept-list passed into the upstream Client
     * as `ClientOptions.supportedProtocolVersions`. The Client sends
     * `supportedProtocolVersions[0]` as `initialize.params.protocolVersion`
     * and accepts any of the listed versions in the server's response.
     *
     * Wired into the inspector verbatim from
     * `hostConfig.mcpProfile.initialize.supportedProtocolVersions`. Order is
     * semantic — preserve it. A pin like `["2025-11-25", "2025-06-18"]`
     * proposes the newer version but still accepts the older one if the
     * server negotiates it; the prior shape (`proposedProtocolVersion:
     * string`) collapsed this to a singleton and silently broke that case.
     */
    supportedProtocolVersions?: string[];
    /** Error handler for this server */
    onError?: (error: unknown) => void;
    /** Enable simple console logging of JSON-RPC traffic */
    logJsonRpc?: boolean;
    /** Custom logger for JSON-RPC traffic (overrides logJsonRpc) */
    rpcLogger?: RpcLogger;
};
/**
 * Configuration for stdio-based MCP servers (subprocess)
 */
type StdioServerConfig = BaseServerConfig & {
    /** Command to execute */
    command: string;
    /** Command arguments */
    args?: string[];
    /** Environment variables */
    env?: Record<string, string>;
    /** Child process stderr handling. Defaults to inherit when unspecified. */
    stderr?: StdioServerParameters["stderr"];
    /** Working directory for the stdio server process. */
    cwd?: StdioServerParameters["cwd"];
    url?: never;
    accessToken?: never;
    requestInit?: never;
    eventSourceInit?: never;
    authProvider?: never;
    reconnectionOptions?: never;
    sessionId?: never;
    preferSSE?: never;
    refreshToken?: never;
    clientId?: never;
    clientSecret?: never;
    onUnauthorized?: never;
};
type UnauthorizedRefreshResult = {
    accessToken: string;
};
type UnauthorizedRefreshHandler = (args: {
    serverId: string;
    error: unknown;
}) => Promise<UnauthorizedRefreshResult>;
/**
 * Configuration for HTTP-based MCP servers (SSE or Streamable HTTP)
 */
type HttpServerConfig = BaseServerConfig & {
    /** Server URL */
    url: string;
    /**
     * Access token for Bearer authentication.
     * If provided, adds `Authorization: Bearer <accessToken>` header to requests.
     */
    accessToken?: string;
    /** Additional request initialization options */
    requestInit?: StreamableHTTPClientTransportOptions["requestInit"];
    /** SSE-specific event source options */
    eventSourceInit?: SSEClientTransportOptions["eventSourceInit"];
    /** OAuth auth provider */
    authProvider?: StreamableHTTPClientTransportOptions["authProvider"];
    /** Refresh token for OAuth token exchange. Mutually exclusive with accessToken and authProvider. */
    refreshToken?: string;
    /** OAuth client ID. Required when refreshToken is set. */
    clientId?: string;
    /** OAuth client secret. Optional, used with refreshToken. */
    clientSecret?: string;
    /**
     * Optional 401 recovery hook. When provided for access-token based HTTP
     * configs, MCPClientManager calls it once after an operation fails with a
     * strict HTTP 401, then rebuilds the transport with the returned token.
     */
    onUnauthorized?: UnauthorizedRefreshHandler;
    /** Reconnection options for Streamable HTTP */
    reconnectionOptions?: StreamableHTTPClientTransportOptions["reconnectionOptions"];
    /** Session ID for Streamable HTTP */
    sessionId?: StreamableHTTPClientTransportOptions["sessionId"];
    /** Prefer SSE transport over Streamable HTTP */
    preferSSE?: boolean;
    /**
     * Pinned MCP protocol version (wire literal that lands in `_meta` +
     * `MCP-Protocol-Version` header). Absent → SDK default at request
     * time. Stateful values (per `isStatelessProtocolVersion`) use the
     * legacy upstream Client + initialize handshake; stateless values
     * select the preview Streamable HTTP POST transport
     * (`StatelessMcpHttpPreviewClient`) and are incompatible with
     * `preferSSE`. Already validated by `isKnownProtocolVersion` at the
     * trust boundary (`local-server-resolver.ts` + Convex validator);
     * the manager does not re-validate. Resolved upstream (per-server
     * override > host default > undefined) and stamped onto the config
     * passed to `MCPClientManager`.
     */
    mcpProtocolVersion?: McpProtocolVersion;
    command?: never;
    args?: never;
    env?: never;
    stderr?: never;
    cwd?: never;
};
/**
 * Union type for all server configurations
 */
type MCPServerConfig = StdioServerConfig | HttpServerConfig;
/**
 * Configuration map for multiple servers (serverId -> config)
 */
type MCPClientManagerConfig = Record<string, MCPServerConfig>;
/**
 * Connection status for a server
 */
type MCPConnectionStatus = "connected" | "connecting" | "disconnected";
/**
 * Summary information for a server
 */
type ServerSummary = {
    id: string;
    status: MCPConnectionStatus;
    config?: MCPServerConfig;
};
/**
 * Shared state for managed client connections.
 *
 * `client` is typed as the `ManagedMcpClient` interface so the manager
 * can swap between the legacy upstream `Client` (via
 * `OfficialSdkClientAdapter`) and the stateless preview
 * (`StatelessMcpHttpPreviewClient`) without per-call branching.
 * `transport` is `undefined` for the stateless preview path — the
 * preview owns its own fetch and has no separate Transport object.
 */
interface BaseClientState {
    client?: ManagedMcpClient;
    transport?: Transport;
    authProvider?: RefreshTokenOAuthProvider;
}
/**
 * Persistent server registration/configuration state.
 */
interface RegisteredServerState {
    config: MCPServerConfig;
    timeout: number;
}
/**
 * Live connection state for a registered server.
 */
interface LiveClientState extends BaseClientState {
    stdioStderrCleanup?: () => void;
    connectPromise?: Promise<ManagedMcpClient>;
    retryPromise?: Promise<ManagedMcpClient>;
    initializedClientCapabilities?: ClientCapabilityOptions;
}
/**
 * Event passed to RPC loggers
 */
type RpcLogEvent = {
    direction: "send" | "receive";
    message: unknown;
    serverId: string;
};
/**
 * Function type for JSON-RPC logging
 */
type RpcLogger = (event: RpcLogEvent) => void;
/**
 * Progress event from server operations
 */
type ProgressEvent = {
    serverId: string;
    progressToken: string | number;
    progress: number;
    total?: number;
    message?: string;
};
/**
 * Function type for progress handling
 */
type ProgressHandler = (event: ProgressEvent) => void;
/**
 * Options for MCPClientManager constructor
 */
interface MCPClientManagerOptions {
    /** Default client name to report to servers */
    defaultClientName?: string;
    /** Default client version to report */
    defaultClientVersion?: string;
    /**
     * Default `clientInfo` extra fields (e.g. `title`) to advertise to servers.
     * Per-server `clientInfo.name` / `clientInfo.version` override this. Extra
     * keys here are merged into the per-server clientInfo at connect time so
     * future MCP spec additions don't require an SDK bump.
     */
    defaultClientInfoExtras?: Record<string, unknown>;
    /**
     * Default supported protocol versions accept-list. Per-server
     * `supportedProtocolVersions` overrides this. When neither is set, the
     * upstream Client's built-in `SUPPORTED_PROTOCOL_VERSIONS` default is
     * used and historical behavior is preserved verbatim.
     */
    defaultSupportedProtocolVersions?: string[];
    /** Default capabilities to advertise */
    defaultCapabilities?: ClientCapabilityOptions;
    /** Default request timeout in milliseconds */
    defaultTimeout?: number;
    /** Enable JSON-RPC logging for all servers by default */
    defaultLogJsonRpc?: boolean;
    /** Global JSON-RPC logger */
    rpcLogger?: RpcLogger;
    /** Global progress handler */
    progressHandler?: ProgressHandler;
    /** Default retry policy for retryable manager operations */
    retryPolicy?: RetryPolicy;
    /**
     * When true, do not connect in the constructor; callers must use connectToServer
     * (e.g. connectReplayManagerServers) to avoid racing eager connects.
     */
    lazyConnect?: boolean;
}
/**
 * Arguments passed to tool execution
 */
type ExecuteToolArguments = Record<string, unknown>;
/**
 * Options for task-augmented tool calls
 */
type TaskOptions = {
    /** Time-to-live for the task in milliseconds */
    ttl?: number;
};
/**
 * Preferred executeTool options shape.
 */
interface ExecuteToolRequest {
    /** Request options for the tool call */
    request?: ClientRequestOptions;
    /** Task options for task-augmented tool calls */
    task?: TaskOptions;
    /** Explicit retry policy for tool execution */
    retry?: RetryPolicy;
}
/**
 * Handler for server-specific elicitation requests
 */
type ElicitationHandler = (params: ElicitRequest["params"]) => Promise<ElicitResult> | ElicitResult;
/**
 * Request passed to global elicitation callback
 */
type ElicitationCallbackRequest = {
    requestId: string;
    message: string;
    schema: unknown;
    /** Task ID if this elicitation is related to a task (MCP Tasks spec 2025-11-25) */
    relatedTaskId?: string;
};
/**
 * Global callback for handling elicitation requests
 */
type ElicitationCallback = (request: ElicitationCallbackRequest) => Promise<ElicitResult> | ElicitResult;
/**
 * Task status values
 */
type MCPTaskStatus = Task["status"];
/**
 * MCP Task object
 */
type MCPTask = Task;
/**
 * Result from listing tasks
 */
type MCPListTasksResult = ListTasksResult;
type ClientRequestOptions = RequestOptions;
type ListResourcesParams = Parameters<Client["listResources"]>[0];
type ListResourceTemplatesParams = Parameters<Client["listResourceTemplates"]>[0];
type ReadResourceParams = Parameters<Client["readResource"]>[0];
type SubscribeResourceParams = Parameters<Client["subscribeResource"]>[0];
type UnsubscribeResourceParams = Parameters<Client["unsubscribeResource"]>[0];
type ListPromptsParams = Parameters<Client["listPrompts"]>[0];
type GetPromptParams = Parameters<Client["getPrompt"]>[0];
type ListToolsResult = Awaited<ReturnType<Client["listTools"]>>;
type MCPPromptListResult = Awaited<ReturnType<Client["listPrompts"]>>;
type MCPPrompt = MCPPromptListResult["prompts"][number];
type MCPGetPromptResult = Awaited<ReturnType<Client["getPrompt"]>>;
type MCPResourceListResult = Awaited<ReturnType<Client["listResources"]>>;
type MCPResource = MCPResourceListResult["resources"][number];
type MCPReadResourceResult = Awaited<ReturnType<Client["readResource"]>>;
type MCPResourceTemplateListResult = Awaited<ReturnType<Client["listResourceTemplates"]>>;
type MCPResourceTemplate = MCPResourceTemplateListResult["resourceTemplates"][number];
type MCPServerSummary = ServerSummary;
/**
 * An MCP tool with an execute function pre-wired to call the manager.
 * Extends the official MCP SDK Tool type.
 * Returned by MCPClientManager.getTools().
 */
/** Options for tool execution */
interface ToolExecuteOptions {
    /** Abort signal for cancellation */
    signal?: AbortSignal;
}
interface Tool extends Tool$1 {
    /** Execute the tool with the given arguments */
    execute: (args: Record<string, unknown>, options?: ToolExecuteOptions) => Promise<CallToolResult>;
    _meta?: {
        _serverId: string;
        [key: string]: unknown;
    };
}

/**
 * AI SDK compatible tool set (Record<string, CoreTool>).
 * Returned by MCPClientManager.getToolsForAiSdk().
 * Can be passed directly to AI SDK's generateText().
 */
type AiSdkTool = ToolSet;

export { type AiSdkTool as A, type BaseServerConfig as B, type ClientCapabilityOptions as C, type ElicitationCallback as D, type ExecuteToolArguments as E, DEFAULT_RETRY_POLICY as F, type GetPromptParams as G, type HttpServerConfig as H, type ElicitationCallbackRequest as I, type LiveClientState as J, type MCPServerSummary as K, type ListToolsResult as L, type MCPServerConfig as M, type ProgressHandler as N, type RegisteredServerState as O, type ProgressEvent as P, type RpcLogEvent as Q, type RpcLogger as R, type ServerSummary as S, type TaskOptions as T, type UnsubscribeResourceParams as U, type ToolExecuteOptions as V, type UnauthorizedRefreshHandler as W, type UnauthorizedRefreshResult as X, isRetryableTransientError as Y, normalizeRetryPolicy as Z, retryWithPolicy as _, type RetryPolicy as a, type MCPPrompt as b, type MCPResourceTemplate as c, type MCPResource as d, type MCPClientManagerConfig as e, type MCPConnectionStatus as f, type MCPGetPromptResult as g, type MCPListTasksResult as h, type MCPPromptListResult as i, type MCPReadResourceResult as j, type MCPResourceListResult as k, type MCPResourceTemplateListResult as l, type MCPTask as m, type MCPTaskStatus as n, type StdioServerConfig as o, type MCPClientManagerOptions as p, type ManagedMcpClient as q, type ClientRequestOptions as r, type Tool as s, type ExecuteToolRequest as t, type ListResourcesParams as u, type ReadResourceParams as v, type SubscribeResourceParams as w, type ListResourceTemplatesParams as x, type ListPromptsParams as y, type ElicitationHandler as z };
