import { RetryOptions } from "../retries.js";
import { d as Event, i as MCPTransportOptions, l as TransportType, n as MCPClientConnection, r as MCPConnectionState, t as MCPServerRow, u as Emitter } from "../client-storage-D633wI1S.js";
import { t as MCPObservabilityEvent } from "../mcp-DA0kDE7K.js";
import { AgentMcpOAuthProvider } from "./do-oauth-client-provider.js";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { CallToolRequest, CallToolResultSchema, CompatibilityCallToolResultSchema, GetPromptRequest, Prompt, ReadResourceRequest, Resource, ResourceTemplate, Tool } from "@modelcontextprotocol/sdk/types.js";
import * as ai from "ai";
import { ToolSet } from "ai";
import { RequestOptions } from "@modelcontextprotocol/sdk/shared/protocol.js";

//#region src/mcp/client.d.ts
/**
 * Options that can be stored in the server_options column
 * This is what gets JSON.stringify'd and stored in the database
 */
type MCPServerOptions = {
  client?: ConstructorParameters<typeof Client>[1];
  transport?: {
    headers?: HeadersInit;
    type?: TransportType;
  }; /** Retry options for connection and reconnection attempts */
  retry?: RetryOptions;
};
/**
 * Result of an OAuth callback request
 */
type MCPOAuthCallbackResult = {
  serverId: string;
  authSuccess: true;
  authError?: undefined;
} | {
  serverId?: string;
  authSuccess: false;
  authError: string;
};
/**
 * Options for registering an MCP server
 */
type RegisterServerOptions = {
  url: string;
  name: string;
  callbackUrl: string;
  client?: ConstructorParameters<typeof Client>[1];
  transport?: MCPTransportOptions;
  authUrl?: string;
  clientId?: string; /** Retry options for connection and reconnection attempts */
  retry?: RetryOptions;
};
/**
 * Result of attempting to connect to an MCP server.
 * Discriminated union ensures error is present only on failure.
 */
type MCPConnectionResult = {
  state: typeof MCPConnectionState.FAILED;
  error: string;
} | {
  state: typeof MCPConnectionState.AUTHENTICATING;
  authUrl: string;
  clientId?: string;
} | {
  state: typeof MCPConnectionState.CONNECTED;
};
/**
 * Result of discovering server capabilities.
 * success indicates whether discovery completed successfully.
 * state is the current connection state at time of return.
 * error is present when success is false.
 */
type MCPDiscoverResult = {
  success: boolean;
  state: MCPConnectionState;
  error?: string;
};
type MCPClientOAuthCallbackConfig = {
  successRedirect?: string;
  errorRedirect?: string;
  customHandler?: (result: MCPClientOAuthResult) => Response;
};
type MCPClientOAuthResult = {
  serverId: string;
  authSuccess: true;
  authError?: undefined;
} | {
  serverId?: string;
  authSuccess: false; /** May contain untrusted content from external OAuth providers. Escape appropriately for your output context. */
  authError: string;
};
type MCPClientManagerOptions = {
  storage: DurableObjectStorage;
  createAuthProvider?: (callbackUrl: string) => AgentMcpOAuthProvider;
};
/**
 * Utility class that aggregates multiple MCP clients into one
 */
declare class MCPClientManager {
  private _name;
  private _version;
  mcpConnections: Record<string, MCPClientConnection>;
  private _didWarnAboutUnstableGetAITools;
  private _oauthCallbackConfig?;
  private _connectionDisposables;
  private _storage;
  private _createAuthProviderFn?;
  private _isRestored;
  /** @internal Protected for testing purposes. */
  protected readonly _onObservabilityEvent: Emitter<MCPObservabilityEvent>;
  readonly onObservabilityEvent: Event<MCPObservabilityEvent>;
  private readonly _onServerStateChanged;
  /**
   * Event that fires whenever any MCP server state changes (registered, connected, removed, etc.)
   * This is useful for broadcasting server state to clients.
   */
  readonly onServerStateChanged: Event<void>;
  /**
   * @param _name Name of the MCP client
   * @param _version Version of the MCP Client
   * @param options Storage adapter for persisting MCP server state
   */
  constructor(_name: string, _version: string, options: MCPClientManagerOptions);
  private sql;
  private saveServerToStorage;
  private removeServerFromStorage;
  private getServersFromStorage;
  /**
   * Get the retry options for a server from stored server_options
   */
  private getServerRetryOptions;
  private clearServerAuthUrl;
  private failConnection;
  jsonSchema: typeof ai.jsonSchema | undefined;
  /**
   * Create an auth provider for a server
   * @internal
   */
  private createAuthProvider;
  /**
   * Restore MCP server connections from storage
   * This method is called on Agent initialization to restore previously connected servers
   *
   * @param clientName Name to use for OAuth client (typically the agent instance name)
   */
  restoreConnectionsFromStorage(clientName: string): Promise<void>;
  /**
   * Internal method to restore a single server connection and discovery
   */
  private _restoreServer;
  /**
   * Connect to and register an MCP server
   *
   * @deprecated This method is maintained for backward compatibility.
   * For new code, use registerServer() and connectToServer() separately.
   *
   * @param url Server URL
   * @param options Connection options
   * @returns Object with server ID, auth URL (if OAuth), and client ID (if OAuth)
   */
  connect(url: string, options?: {
    reconnect?: {
      id: string;
      oauthClientId?: string;
      oauthCode?: string;
    };
    transport?: MCPTransportOptions;
    client?: ConstructorParameters<typeof Client>[1];
  }): Promise<{
    id: string;
    authUrl?: string;
    clientId?: string;
  }>;
  /**
   * Create an in-memory connection object and set up observability
   * Does NOT save to storage - use registerServer() for that
   * @returns The connection object (existing or newly created)
   */
  private createConnection;
  /**
   * Register an MCP server connection without connecting
   * Creates the connection object, sets up observability, and saves to storage
   *
   * @param id Server ID
   * @param options Registration options including URL, name, callback URL, and connection config
   * @returns Server ID
   */
  registerServer(id: string, options: RegisterServerOptions): Promise<string>;
  /**
   * Connect to an already registered MCP server and initialize the connection.
   *
   * For OAuth servers, returns `{ state: "authenticating", authUrl, clientId? }`.
   * The user must complete the OAuth flow via the authUrl, which triggers a
   * callback handled by `handleCallbackRequest()`.
   *
   * For non-OAuth servers, establishes the transport connection and returns
   * `{ state: "connected" }`. Call `discoverIfConnected()` afterwards to
   * discover capabilities and transition to "ready" state.
   *
   * @param id Server ID (must be registered first via registerServer())
   * @returns Connection result with current state and OAuth info (if applicable)
   */
  connectToServer(id: string): Promise<MCPConnectionResult>;
  private extractServerIdFromState;
  isCallbackRequest(req: Request): boolean;
  private validateCallbackRequest;
  handleCallbackRequest(req: Request): Promise<MCPOAuthCallbackResult>;
  /**
   * Discover server capabilities if connection is in CONNECTED or READY state.
   * Transitions to DISCOVERING then READY (or CONNECTED on error).
   * Can be called to refresh server capabilities (e.g., from a UI refresh button).
   *
   * If called while a previous discovery is in-flight for the same server,
   * the previous discovery will be aborted.
   *
   * @param serverId The server ID to discover
   * @param options Optional configuration
   * @param options.timeoutMs Timeout in milliseconds (default: 30000)
   * @returns Result with current state and optional error, or undefined if connection not found
   */
  discoverIfConnected(serverId: string, options?: {
    timeoutMs?: number;
  }): Promise<MCPDiscoverResult | undefined>;
  /**
   * Establish connection in the background after OAuth completion
   * This method connects to the server and discovers its capabilities
   * @param serverId The server ID to establish connection for
   */
  establishConnection(serverId: string): Promise<void>;
  /**
   * Configure OAuth callback handling
   * @param config OAuth callback configuration
   */
  configureOAuthCallback(config: MCPClientOAuthCallbackConfig): void;
  /**
   * Get the current OAuth callback configuration
   * @returns The current OAuth callback configuration
   */
  getOAuthCallbackConfig(): MCPClientOAuthCallbackConfig | undefined;
  /**
   * @returns namespaced list of tools
   */
  listTools(): NamespacedData["tools"];
  /**
   * Lazy-loads the jsonSchema function from the AI SDK.
   *
   * This defers importing the "ai" package until it's actually needed, which helps reduce
   * initial bundle size and startup time. The jsonSchema function is required for converting
   * MCP tools into AI SDK tool definitions via getAITools().
   *
   * @internal This method is for internal use only. It's automatically called before operations
   * that need jsonSchema (like getAITools() or OAuth flows). External consumers should not need
   * to call this directly.
   */
  ensureJsonSchema(): Promise<void>;
  /**
   * @returns a set of tools that you can use with the AI SDK
   */
  getAITools(): ToolSet;
  /**
   * @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version
   * @returns a set of tools that you can use with the AI SDK
   */
  unstable_getAITools(): ToolSet;
  /**
   * Closes all active in-memory connections to MCP servers.
   *
   * Note: This only closes the transport connections - it does NOT remove
   * servers from storage. Servers will still be listed and their callback
   * URLs will still match incoming OAuth requests.
   *
   * Use removeServer() instead if you want to fully clean up a server
   * (closes connection AND removes from storage).
   */
  closeAllConnections(): Promise<void>;
  /**
   * Closes a connection to an MCP server
   * @param id The id of the connection to close
   */
  closeConnection(id: string): Promise<void>;
  /**
   * Remove an MCP server - closes connection if active and removes from storage.
   */
  removeServer(serverId: string): Promise<void>;
  /**
   * List all MCP servers from storage
   */
  listServers(): MCPServerRow[];
  /**
   * Dispose the manager and all resources.
   */
  dispose(): Promise<void>;
  /**
   * @returns namespaced list of prompts
   */
  listPrompts(): NamespacedData["prompts"];
  /**
   * @returns namespaced list of tools
   */
  listResources(): NamespacedData["resources"];
  /**
   * @returns namespaced list of resource templates
   */
  listResourceTemplates(): NamespacedData["resourceTemplates"];
  /**
   * Namespaced version of callTool
   */
  callTool(params: CallToolRequest["params"] & {
    serverId: string;
  }, resultSchema?: typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema, options?: RequestOptions): Promise<{
    [x: string]: unknown;
    content: ({
      type: "text";
      text: string;
      annotations?: {
        audience?: ("user" | "assistant")[] | undefined;
        priority?: number | undefined;
        lastModified?: string | undefined;
      } | undefined;
      _meta?: Record<string, unknown> | undefined;
    } | {
      type: "image";
      data: string;
      mimeType: string;
      annotations?: {
        audience?: ("user" | "assistant")[] | undefined;
        priority?: number | undefined;
        lastModified?: string | undefined;
      } | undefined;
      _meta?: Record<string, unknown> | undefined;
    } | {
      type: "audio";
      data: string;
      mimeType: string;
      annotations?: {
        audience?: ("user" | "assistant")[] | undefined;
        priority?: number | undefined;
        lastModified?: string | undefined;
      } | undefined;
      _meta?: Record<string, unknown> | undefined;
    } | {
      type: "resource";
      resource: {
        uri: string;
        text: string;
        mimeType?: string | undefined;
        _meta?: Record<string, unknown> | undefined;
      } | {
        uri: string;
        blob: string;
        mimeType?: string | undefined;
        _meta?: Record<string, unknown> | undefined;
      };
      annotations?: {
        audience?: ("user" | "assistant")[] | undefined;
        priority?: number | undefined;
        lastModified?: string | undefined;
      } | undefined;
      _meta?: Record<string, unknown> | undefined;
    } | {
      uri: string;
      name: string;
      type: "resource_link";
      description?: string | undefined;
      mimeType?: string | undefined;
      annotations?: {
        audience?: ("user" | "assistant")[] | undefined;
        priority?: number | undefined;
        lastModified?: string | undefined;
      } | undefined;
      _meta?: {
        [x: string]: unknown;
      } | undefined;
      icons?: {
        src: string;
        mimeType?: string | undefined;
        sizes?: string[] | undefined;
        theme?: "light" | "dark" | undefined;
      }[] | undefined;
      title?: string | undefined;
    })[];
    _meta?: {
      [x: string]: unknown;
      progressToken?: string | number | undefined;
      "io.modelcontextprotocol/related-task"?: {
        taskId: string;
      } | undefined;
    } | undefined;
    structuredContent?: Record<string, unknown> | undefined;
    isError?: boolean | undefined;
  } | {
    [x: string]: unknown;
    toolResult: unknown;
    _meta?: {
      [x: string]: unknown;
      progressToken?: string | number | undefined;
      "io.modelcontextprotocol/related-task"?: {
        taskId: string;
      } | undefined;
    } | undefined;
  }>;
  /**
   * Namespaced version of readResource
   */
  readResource(params: ReadResourceRequest["params"] & {
    serverId: string;
  }, options: RequestOptions): Promise<{
    [x: string]: unknown;
    contents: ({
      uri: string;
      text: string;
      mimeType?: string | undefined;
      _meta?: Record<string, unknown> | undefined;
    } | {
      uri: string;
      blob: string;
      mimeType?: string | undefined;
      _meta?: Record<string, unknown> | undefined;
    })[];
    _meta?: {
      [x: string]: unknown;
      progressToken?: string | number | undefined;
      "io.modelcontextprotocol/related-task"?: {
        taskId: string;
      } | undefined;
    } | undefined;
  }>;
  /**
   * Namespaced version of getPrompt
   */
  getPrompt(params: GetPromptRequest["params"] & {
    serverId: string;
  }, options: RequestOptions): Promise<{
    [x: string]: unknown;
    messages: {
      role: "user" | "assistant";
      content: {
        type: "text";
        text: string;
        annotations?: {
          audience?: ("user" | "assistant")[] | undefined;
          priority?: number | undefined;
          lastModified?: string | undefined;
        } | undefined;
        _meta?: Record<string, unknown> | undefined;
      } | {
        type: "image";
        data: string;
        mimeType: string;
        annotations?: {
          audience?: ("user" | "assistant")[] | undefined;
          priority?: number | undefined;
          lastModified?: string | undefined;
        } | undefined;
        _meta?: Record<string, unknown> | undefined;
      } | {
        type: "audio";
        data: string;
        mimeType: string;
        annotations?: {
          audience?: ("user" | "assistant")[] | undefined;
          priority?: number | undefined;
          lastModified?: string | undefined;
        } | undefined;
        _meta?: Record<string, unknown> | undefined;
      } | {
        type: "resource";
        resource: {
          uri: string;
          text: string;
          mimeType?: string | undefined;
          _meta?: Record<string, unknown> | undefined;
        } | {
          uri: string;
          blob: string;
          mimeType?: string | undefined;
          _meta?: Record<string, unknown> | undefined;
        };
        annotations?: {
          audience?: ("user" | "assistant")[] | undefined;
          priority?: number | undefined;
          lastModified?: string | undefined;
        } | undefined;
        _meta?: Record<string, unknown> | undefined;
      } | {
        uri: string;
        name: string;
        type: "resource_link";
        description?: string | undefined;
        mimeType?: string | undefined;
        annotations?: {
          audience?: ("user" | "assistant")[] | undefined;
          priority?: number | undefined;
          lastModified?: string | undefined;
        } | undefined;
        _meta?: {
          [x: string]: unknown;
        } | undefined;
        icons?: {
          src: string;
          mimeType?: string | undefined;
          sizes?: string[] | undefined;
          theme?: "light" | "dark" | undefined;
        }[] | undefined;
        title?: string | undefined;
      };
    }[];
    _meta?: {
      [x: string]: unknown;
      progressToken?: string | number | undefined;
      "io.modelcontextprotocol/related-task"?: {
        taskId: string;
      } | undefined;
    } | undefined;
    description?: string | undefined;
  }>;
}
type NamespacedData = {
  tools: (Tool & {
    serverId: string;
  })[];
  prompts: (Prompt & {
    serverId: string;
  })[];
  resources: (Resource & {
    serverId: string;
  })[];
  resourceTemplates: (ResourceTemplate & {
    serverId: string;
  })[];
};
declare function getNamespacedData<T extends keyof NamespacedData>(mcpClients: Record<string, MCPClientConnection>, type: T): NamespacedData[T];
//#endregion
export { MCPClientManager, MCPClientManagerOptions, MCPClientOAuthCallbackConfig, MCPClientOAuthResult, MCPConnectionResult, MCPDiscoverResult, MCPOAuthCallbackResult, MCPServerOptions, RegisterServerOptions, getNamespacedData };
//# sourceMappingURL=client.d.ts.map