mcp-use TypeScript API
    Preparing search index...

    Interface McpServer

    React entry point for the MCP connection console.

    Provides the useMcp hook, the multi-server McpClientProvider, and the supporting storage / logging utilities for connecting to MCP servers from a React app. MCP Apps host rendering lives in ViewRenderer.

    interface McpServer {
        approveElicitation: (
            requestId: string,
            result: { [key: string]: unknown },
        ) => void;
        approveSampling: (
            requestId: string,
            result: { [key: string]: unknown } | { [key: string]: unknown },
        ) => void;
        authenticate: () => Promise<void>;
        authTokens?: {
            access_token: string;
            client_id?: string;
            client_secret?: string;
            expires_at?: number;
            refresh_token?: string;
            resource?: string;
            scope?: string;
            token_endpoint?: string;
            token_type: string;
        };
        authUrl?: string;
        autoProxyFallback?: boolean
        | { enabled?: boolean; proxyAddress?: string };
        autoReconnect?:
            | number
            | boolean
            | {
                enabled?: boolean;
                healthCheckInterval?: number
                | false;
                healthCheckTimeout?: number;
                initialDelay?: number;
            };
        autoRetry?: number
        | boolean;
        callbackUrl?: string;
        callTool: (
            name: string,
            args?: Record<string, unknown>,
            options?: {
                maxTotalTimeout?: number;
                resetTimeoutOnProgress?: boolean;
                signal?: AbortSignal;
                timeout?: number;
            },
        ) => Promise<any>;
        capabilities?: Record<string, unknown>;
        clearNotifications: () => void;
        clearStorage: () => void;
        client: BaseMCPClient | null;
        clientInfo?: {
            description?: string;
            icons?: { mimeType?: string; sizes?: string[]; src: string }[];
            name: string;
            title?: string;
            version: string;
            websiteUrl?: string;
        };
        clientOptions?: Omit<ClientOptions, "capabilities"> & {
            capabilities?: {} & { views?: boolean };
        };
        complete: (params: {}) => Promise<{ [key: string]: unknown }>;
        connectionMode?: "auto" | "direct" | "proxy";
        disconnect: () => Promise<void>;
        displayName?: string;
        enabled?: boolean;
        ensureIconLoaded: () => Promise<string | null>;
        error?: string;
        extensions: Record<string, unknown>;
        getPrompt: (
            name: string,
            args?: Record<string, string>,
        ) => Promise<
            {
                messages: {
                    content: { text?: string; type: string; [key: string]: any };
                    role: "user" | "assistant";
                }[];
            },
        >;
        headers?: Record<string, string>;
        id: string;
        instructions?: string;
        listPrompts: () => Promise<void>;
        listResources: () => Promise<void>;
        log: {
            level: "error" | "warn" | "info" | "debug";
            message: string;
            timestamp: number;
        }[];
        logLevel?: | "silent"
        | "error"
        | "warn"
        | "info"
        | "http"
        | "verbose"
        | "debug"
        | "silly";
        markAllNotificationsRead: () => void;
        markNotificationRead: (id: string) => void;
        name: string;
        notifications: McpNotification[];
        oauth?: { clientId?: string; clientMetadataUrl?: string; scope?: string };
        oauthProxyUrl?: string;
        pendingElicitationRequests: PendingElicitationRequest[];
        pendingSamplingRequests: PendingSamplingRequest[];
        popupFeatures?: string;
        preventAutoAuth?: boolean;
        prompts: {}[];
        protocolEra?: ProtocolEra;
        protocolNegotiation?: VersionNegotiationMode;
        protocolVersion?: string;
        proxyConfig?: ProxyConfig;
        readResource: (
            uri: string,
        ) => Promise<
            {
                contents: {
                    blob?: string;
                    mimeType?: string;
                    text?: string;
                    uri: string;
                }[];
            },
        >;
        reconnect: () => Promise<void>;
        reconnectionOptions?: ReconnectionOptions;
        refreshAll: () => Promise<void>;
        refreshPrompts: () => Promise<void>;
        refreshResources: () => Promise<void>;
        refreshResourceTemplates: () => Promise<void>;
        refreshTools: () => Promise<void>;
        rejectElicitation: (requestId: string, error?: string) => void;
        rejectSampling: (requestId: string, error?: string) => void;
        resources: {}[];
        resourceTemplates: {}[];
        retry: () => void;
        serverInfo?: {
            description?: string;
            icon?: string;
            icons?: { mimeType?: string; sizes?: string[]; src: string }[];
            name: string;
            title?: string;
            version?: string;
            websiteUrl?: string;
        };
        setDisplayName: (displayName: string) => Promise<void>;
        setHeaders: (headers: Record<string, string> | undefined) => Promise<void>;
        state:
            | "discovering"
            | "pending_auth"
            | "authenticating"
            | "ready"
            | "failed";
        storageKeyPrefix?: string;
        timeout?: number;
        tools: {}[];
        unreadNotificationCount: number;
        updateConfig: (config: Partial<McpServerConfig>) => Promise<void>;
        url?: string;
        useRedirectFlow?: boolean;
    }

    Hierarchy (View Summary)

    Index
    approveElicitation: (
        requestId: string,
        result: { [key: string]: unknown },
    ) => void

    Approves a pending elicitation request with a result.

    approveSampling: (
        requestId: string,
        result: { [key: string]: unknown } | { [key: string]: unknown },
    ) => void

    Approves a pending sampling request with a result.

    authenticate: () => Promise<void>

    Manually triggers the authentication process. Useful if the initial attempt failed due to a blocked popup, allowing the user to initiate it via a button click.

    Type Declaration

      • (): Promise<void>
      • Returns Promise<void>

        A promise that resolves with the authorization URL opened (or intended to be opened), or undefined if auth cannot be started.

    authTokens?: {
        access_token: string;
        client_id?: string;
        client_secret?: string;
        expires_at?: number;
        refresh_token?: string;
        resource?: string;
        scope?: string;
        token_endpoint?: string;
        token_type: string;
    }

    OAuth tokens if authentication was completed Available when state is 'ready' and OAuth was used

    Type Declaration

    • access_token: string

      OAuth access token.

    • Optionalclient_id?: string

      OAuth client id (from Dynamic Client Registration or a static client). Most token endpoints require it on refresh, so consumers can persist it for server-side proactive refresh.

    • Optionalclient_secret?: string

      OAuth client secret, when the provider issued a confidential client.

    • Optionalexpires_at?: number

      Unix timestamp in seconds when the access token expires.

    • Optionalrefresh_token?: string

      OAuth refresh token, when issued.

    • Optionalresource?: string

      Canonical protected-resource URL required by some token refresh flows.

    • Optionalscope?: string

      Space-delimited OAuth scopes granted to the token.

    • Optionaltoken_endpoint?: string

      OAuth token endpoint resolved during discovery (when available). Lets consumers persist it so a backend can proactively refresh the token.

    • token_type: string

      OAuth token type, commonly "Bearer".

    authUrl?: string

    If authentication requires user interaction (e.g., popup was blocked), this URL can be presented to the user to complete authentication manually in a new tab.

    autoProxyFallback?: boolean | { enabled?: boolean; proxyAddress?: string }

    Enable automatic proxy fallback when direct connection fails When enabled, if a direct connection fails with FastMCP or CORS errors, automatically retries using the proxy configuration

    Can be:

    • true: Enable with proxyConfig.proxyAddress
    • false: Disable automatic fallback (default)
    • { enabled: boolean, proxyAddress?: string }: Custom configuration

    Type Declaration

    • boolean
    • { enabled?: boolean; proxyAddress?: string }
      • Optionalenabled?: boolean

        Whether fallback is enabled.

      • OptionalproxyAddress?: string

        Proxy endpoint used after a qualifying direct failure.

    false
    
    // Use default proxy
    useMcp({ url: '...', autoProxyFallback: true })

    // Use custom proxy
    useMcp({
    url: '...',
    autoProxyFallback: {
    enabled: true,
    proxyAddress: 'https://my-proxy.com/api/proxy'
    }
    })
    autoReconnect?:
        | number
        | boolean
        | {
            enabled?: boolean;
            healthCheckInterval?: number
            | false;
            healthCheckTimeout?: number;
            initialDelay?: number;
        }

    Auto reconnect if an established connection is lost.

    Can be:

    • boolean: Enable/disable with default 3000ms delay and 10s health check
    • number: Reconnect delay in ms (enables health checks with defaults)
    • object: Full configuration for reconnection and health checks

    Type Declaration

    • number
    • boolean
    • {
          enabled?: boolean;
          healthCheckInterval?: number | false;
          healthCheckTimeout?: number;
          initialDelay?: number;
      }
      • Optionalenabled?: boolean

        Whether to enable automatic reconnection (default: true)

      • OptionalhealthCheckInterval?: number | false

        Interval in ms for health check polling via HEAD requests. Set to false to disable health checks entirely.

        10000

      • OptionalhealthCheckTimeout?: number

        Time in ms without a successful health check before triggering reconnect.

        30000

      • OptionalinitialDelay?: number

        Delay in ms before reconnection attempt (default: 3000)

    true with a 3000 ms initial delay

    autoRetry?: number | boolean

    Auto retry connection if initial connection fails, with delay in ms (default: false)

    callbackUrl?: string

    Custom callback URL for OAuth redirect (defaults to /oauth/callback on the current origin)

    callTool: (
        name: string,
        args?: Record<string, unknown>,
        options?: {
            maxTotalTimeout?: number;
            resetTimeoutOnProgress?: boolean;
            signal?: AbortSignal;
            timeout?: number;
        },
    ) => Promise<any>

    Function to call a tool on the MCP server.

    Type Declaration

      • (
            name: string,
            args?: Record<string, unknown>,
            options?: {
                maxTotalTimeout?: number;
                resetTimeoutOnProgress?: boolean;
                signal?: AbortSignal;
                timeout?: number;
            },
        ): Promise<any>
      • Parameters

        • name: string

          The name of the tool to call.

        • Optionalargs: Record<string, unknown>

          Optional arguments for the tool.

        • Optionaloptions: {
              maxTotalTimeout?: number;
              resetTimeoutOnProgress?: boolean;
              signal?: AbortSignal;
              timeout?: number;
          }

          Optional request options including timeout configuration.

          • OptionalmaxTotalTimeout?: number

            Maximum total timeout in milliseconds, even with progress resets

          • OptionalresetTimeoutOnProgress?: boolean

            Reset the timeout when progress notifications are received (default: false)

          • Optionalsignal?: AbortSignal

            AbortSignal to cancel the request

          • Optionaltimeout?: number

            Timeout in milliseconds for this tool call (default: 60000 / 60 seconds)

        Returns Promise<any>

        A promise that resolves with the tool's result.

    If the client is not in the 'ready' state or the call fails.

    // Simple tool call
    const result = await mcp.callTool('my-tool', { arg: 'value' })

    // Tool call with extended timeout (e.g., for tools that trigger sampling)
    const result = await mcp.callTool('analyze-sentiment', { text: 'Hello' }, {
    timeout: 300000, // 5 minutes
    resetTimeoutOnProgress: true // Reset timeout when progress notifications are received
    })
    capabilities?: Record<string, unknown>

    Server capabilities normalized for the active connection.

    clearNotifications: () => void

    Removes every notification from local state.

    clearStorage: () => void

    Clears all stored authentication data (tokens, client info, etc.) for this server URL from localStorage.

    client: BaseMCPClient | null

    The underlying runtime-neutral MCP client instance. Use this to create an MCPAgent for AI chat functionality.

    import { MCPAgent } from "@mcp-use/agent"
    import { ChatOpenAI } from '@langchain/openai'

    const mcp = useMcp({ url: 'http://localhost:3000/mcp' })
    const llm = new ChatOpenAI({ model: 'gpt-4' })

    const agent = new MCPAgent({ llm, client: mcp.client })
    await agent.initialize()

    for await (const event of agent.streamEvents('Hello')) {
    console.log(event)
    }
    clientInfo?: {
        description?: string;
        icons?: { mimeType?: string; sizes?: string[]; src: string }[];
        name: string;
        title?: string;
        version: string;
        websiteUrl?: string;
    }

    Client information advertised while establishing the MCP connection.

    Type Declaration

    • Optionaldescription?: string

      Optional human-readable client description.

    • Optionalicons?: { mimeType?: string; sizes?: string[]; src: string }[]

      Icons representing the client.

    • name: string

      Stable programmatic client name.

    • Optionaltitle?: string

      Optional human-readable client title.

    • version: string

      Client version.

    • OptionalwebsiteUrl?: string

      Public website describing the client.

    clientOptions?: Omit<ClientOptions, "capabilities"> & {
        capabilities?: {} & { views?: boolean };
    }

    SDK client options used by the active connection.

    Type Declaration

    • Optionalcapabilities?: {} & { views?: boolean }

      MCP capabilities advertised by the underlying SDK client.

    complete: (params: {}) => Promise<{ [key: string]: unknown }>

    Request completion suggestions for a prompt or resource template argument.

    Type Declaration

      • (params: {}): Promise<{ [key: string]: unknown }>
      • Parameters

        • params: {}

          Completion request parameters specifying the ref and argument to complete.

        Returns Promise<{ [key: string]: unknown }>

        A promise that resolves with completion suggestions from the server.

    If the client is not in the 'ready' state or the completion request fails.

    connectionMode?: "auto" | "direct" | "proxy"

    Connection policy for proxy routing.

    • auto: start direct and use autoProxyFallback after a qualifying failure
    • direct: never use proxyConfig and never fall back
    • proxy: use proxyConfig immediately and never fall back

    When omitted, proxyConfig retains its legacy immediate-proxy behavior, except when autoProxyFallback explicitly requests a direct-first attempt.

    disconnect: () => Promise<void>

    Disconnects the client from the MCP server.

    displayName?: string

    Optional user-facing alias. server.name always comes from MCP server metadata.

    enabled?: boolean

    Enable/disable the connection (similar to TanStack Query). When false, no connection will be attempted (default: true)

    ensureIconLoaded: () => Promise<string | null>

    Ensure the server icon is loaded and available in serverInfo Returns a promise that resolves when the icon is ready Use this before server creation to guarantee the icon is available

    Type Declaration

      • (): Promise<string | null>
      • Returns Promise<string | null>

        Promise that resolves with the base64 icon or null if not available

    // Wait for icon before creating server
    const icon = await mcp.ensureIconLoaded();
    // Now mcp.serverInfo.icon is guaranteed to be set (if icon exists)
    error?: string

    If the state is 'failed', this provides the error message

    extensions: Record<string, unknown>

    Protocol extension metadata normalized from the server capabilities.

    getPrompt: (
        name: string,
        args?: Record<string, string>,
    ) => Promise<
        {
            messages: {
                content: { text?: string; type: string; [key: string]: any };
                role: "user" | "assistant";
            }[];
        },
    >

    Function to get a specific prompt from the MCP server.

    Type Declaration

      • (
            name: string,
            args?: Record<string, string>,
        ): Promise<
            {
                messages: {
                    content: { text?: string; type: string; [key: string]: any };
                    role: "user" | "assistant";
                }[];
            },
        >
      • Parameters

        • name: string

          The name of the prompt to get.

        • Optionalargs: Record<string, string>

          Optional arguments for the prompt.

        Returns Promise<
            {
                messages: {
                    content: { text?: string; type: string; [key: string]: any };
                    role: "user" | "assistant";
                }[];
            },
        >

        A promise that resolves with the prompt messages.

    If the client is not in the 'ready' state or the get fails.

    headers?: Record<string, string>

    Runtime HTTP headers. These values are never persisted.

    id: string

    Stable provider-managed server identifier.

    instructions?: string

    Optional server instructions advertised for the active connection.

    listPrompts: () => Promise<void>

    Function to list prompts from the MCP server.

    Type Declaration

      • (): Promise<void>
      • Returns Promise<void>

        A promise that resolves when prompts are refreshed.

    If the client is not in the 'ready' state.

    listResources: () => Promise<void>

    Function to list resources from the MCP server.

    Type Declaration

      • (): Promise<void>
      • Returns Promise<void>

        A promise that resolves when resources are refreshed.

    If the client is not in the 'ready' state.

    log: {
        level: "error" | "warn" | "info" | "debug";
        message: string;
        timestamp: number;
    }[]

    Array of internal log messages (useful for debugging)

    Type Declaration

    • level: "error" | "warn" | "info" | "debug"

      Log severity.

    • message: string

      Human-readable log message.

    • timestamp: number

      Unix timestamp in milliseconds when the entry was created.

    logLevel?:
        | "silent"
        | "error"
        | "warn"
        | "info"
        | "http"
        | "verbose"
        | "debug"
        | "silly"

    Log level for console output. Set to 'silent' to suppress ALL console logging (the mcp.log state array is still populated).

    "silent"

    markAllNotificationsRead: () => void

    Marks every notification as read.

    markNotificationRead: (id: string) => void

    Marks one notification as read.

    name: string

    Name advertised by the connected MCP server.

    notifications: McpNotification[]

    Notifications received from this server.

    oauth?: { clientId?: string; clientMetadataUrl?: string; scope?: string }

    Public OAuth registration settings only.

    Type Declaration

    • OptionalclientId?: string

      Pre-registered public OAuth client identifier.

    • OptionalclientMetadataUrl?: string

      Public OAuth Client ID Metadata Document URL.

    • Optionalscope?: string

      Space-delimited OAuth scopes.

    oauthProxyUrl?: string

    OAuth proxy base URL (e.g. https://inspector.example.com/inspector/api/oauth) used to route OAuth requests (.well-known discovery, DCR, token exchange) through a transparent server-side proxy — bypassing browser CORS against third-party identity providers — WITHOUT proxying MCP traffic itself.

    The proxy is transparent: it forwards requests and responses unmodified, so the SDK's authorization-server issuer validation (RFC 8414 §3.3) still passes. When omitted, the OAuth proxy URL is derived from proxyConfig.proxyAddress (replacing a trailing /proxy with /oauth), preserving the existing behavior for fully-proxied connections.

    pendingElicitationRequests: PendingElicitationRequest[]

    Elicitation requests awaiting an application decision.

    pendingSamplingRequests: PendingSamplingRequest[]

    Sampling requests awaiting an application decision.

    popupFeatures?: string

    Popup window features string (dimensions and behavior) for OAuth

    preventAutoAuth?: boolean

    Prevent automatic authentication popup/redirect on initial connection (default: true) When true, the connection will enter 'pending_auth' state and wait for user to call authenticate() Set to true to show a modal/button before triggering OAuth instead of auto-redirecting

    prompts: {}[]

    List of prompts available from the connected MCP server

    protocolEra?: ProtocolEra

    Negotiated MCP protocol era for the active connection:

    • 'legacy': 2025-era server; lifecycle is managed internally.
    • 'modern': 2026-07-28-era server, stateless per-request. undefined until a connection has negotiated.
    protocolNegotiation?: VersionNegotiationMode

    Protocol version negotiation mode passed to the underlying SDK Client.

    • "auto" (default): probe with server/discover to detect modern (2026-07-28) servers, falling back to the 2025 handshake against legacy servers.
    • "legacy": classic 2025 initialize handshake, no probe.
    • { pin: "2026-07-28" }: modern era only, no fallback.
    protocolVersion?: string

    Negotiated MCP protocol version string (e.g. '2025-06-18', '2026-07-28').

    proxyConfig?: ProxyConfig

    Live proxy configuration, including runtime-only headers.

    readResource: (
        uri: string,
    ) => Promise<
        {
            contents: {
                blob?: string;
                mimeType?: string;
                text?: string;
                uri: string;
            }[];
        },
    >

    Function to read a resource from the MCP server.

    Type Declaration

      • (
            uri: string,
        ): Promise<
            {
                contents: {
                    blob?: string;
                    mimeType?: string;
                    text?: string;
                    uri: string;
                }[];
            },
        >
      • Parameters

        • uri: string

          The URI of the resource to read.

        Returns Promise<
            {
                contents: {
                    blob?: string;
                    mimeType?: string;
                    text?: string;
                    uri: string;
                }[];
            },
        >

        A promise that resolves with the resource contents.

    If the client is not in the 'ready' state or the read fails.

    reconnect: () => Promise<void>

    Disconnect and reconnect with the current config.

    reconnectionOptions?: ReconnectionOptions

    SDK-level reconnection options for the streamable HTTP transport

    refreshAll: () => Promise<void>

    Refresh all lists (tools, resources, resource templates, prompts) from the server. Useful after reconnection or for manual refresh.

    refreshPrompts: () => Promise<void>

    Refresh the prompts list from the server. Called automatically when notifications/prompts/list_changed is received. Can also be called manually for explicit refresh.

    refreshResources: () => Promise<void>

    Refresh the resources list from the server. Called automatically when notifications/resources/list_changed is received. Can also be called manually for explicit refresh.

    refreshResourceTemplates: () => Promise<void>

    Refresh the resource templates list from the server. Can be called manually for explicit refresh.

    refreshTools: () => Promise<void>

    Refresh the tools list from the server. Called automatically when notifications/tools/list_changed is received. Can also be called manually for explicit refresh.

    rejectElicitation: (requestId: string, error?: string) => void

    Rejects a pending elicitation request.

    rejectSampling: (requestId: string, error?: string) => void

    Rejects a pending sampling request.

    resources: {}[]

    List of resources available from the connected MCP server

    resourceTemplates: {}[]

    List of resource templates available from the connected MCP server

    retry: () => void

    Manually attempts to reconnect if the state is 'failed'.

    serverInfo?: {
        description?: string;
        icon?: string;
        icons?: { mimeType?: string; sizes?: string[]; src: string }[];
        name: string;
        title?: string;
        version?: string;
        websiteUrl?: string;
    }

    Server information normalized for the active connection.

    Type Declaration

    • Optionaldescription?: string

      Optional human-readable server description.

    • Optionalicon?: string

      Base64-encoded favicon auto-detected from server domain

    • Optionalicons?: { mimeType?: string; sizes?: string[]; src: string }[]

      Icons advertised by the server.

    • name: string

      Stable server name.

    • Optionaltitle?: string

      Optional human-readable server title.

    • Optionalversion?: string

      Server version.

    • OptionalwebsiteUrl?: string

      Public website describing the server.

    setDisplayName: (displayName: string) => Promise<void>

    Rename the server without disconnecting.

    setHeaders: (headers: Record<string, string> | undefined) => Promise<void>

    Set HTTP headers on the connection config and reconnect.

    state: "discovering" | "pending_auth" | "authenticating" | "ready" | "failed"

    The current state of the MCP connection:

    • 'discovering': Checking server existence and capabilities (including auth requirements).
    • 'pending_auth': Authentication is required but auto-popup was prevented. User action needed.
    • 'authenticating': Authentication is required and the process (e.g., popup) has been initiated.
    • 'ready': Connected and ready for tool calls.
    • 'failed': Connection or authentication failed. Check the error property.
    storageKeyPrefix?: string

    Storage key prefix for OAuth data in localStorage (defaults to "mcp:auth")

    timeout?: number

    Connection timeout in milliseconds for establishing initial connection (default: 30000 / 30 seconds)

    tools: {}[]

    List of tools available from the connected MCP server

    unreadNotificationCount: number

    Number of notifications not yet marked as read.

    updateConfig: (config: Partial<McpServerConfig>) => Promise<void>

    Merge connection-affecting config and reconnect when it changed. Prefer this over context updateServer(id, …) when you already hold the server.

    url?: string

    The /sse URL of your remote MCP server

    useRedirectFlow?: boolean

    Use full-page redirect for OAuth instead of popup window (default: false) Redirect flow avoids popup blockers and provides better UX on mobile. Set to true to use redirect flow instead of popup.