mcp-use TypeScript API
    Preparing search index...

    Type Alias UseMcpResult

    Reactive state and operations returned by useMcp.

    type UseMcpResult = {
        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;
        callTool: (
            name: string,
            args?: Record<string, unknown>,
            options?: {
                maxTotalTimeout?: number;
                resetTimeoutOnProgress?: boolean;
                signal?: AbortSignal;
                timeout?: number;
            },
        ) => Promise<any>;
        capabilities?: Record<string, unknown>;
        clearStorage: () => void;
        client: BaseMCPClient | null;
        complete: (params: CompleteRequestParams) => Promise<CompleteResult>;
        disconnect: () => Promise<void>;
        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";
                }[];
            },
        >;
        instructions?: string;
        listPrompts: () => Promise<void>;
        listResources: () => Promise<void>;
        log: {
            level: "debug" | "info" | "warn" | "error";
            message: string;
            timestamp: number;
        }[];
        name: string;
        prompts: Prompt[];
        protocolEra?: ProtocolEra;
        protocolVersion?: string;
        readResource: (
            uri: string,
        ) => Promise<
            {
                contents: {
                    blob?: string;
                    mimeType?: string;
                    text?: string;
                    uri: string;
                }[];
            },
        >;
        refreshAll: () => Promise<void>;
        refreshPrompts: () => Promise<void>;
        refreshResources: () => Promise<void>;
        refreshResourceTemplates: () => Promise<void>;
        refreshTools: () => Promise<void>;
        resources: Resource[];
        resourceTemplates: ResourceTemplate[];
        retry: () => void;
        serverInfo?: {
            description?: string;
            icon?: string;
            icons?: { mimeType?: string; sizes?: string[]; src: string }[];
            name: string;
            title?: string;
            version?: string;
            websiteUrl?: string;
        };
        state: | "discovering"
        | "pending_auth"
        | "authenticating"
        | "ready"
        | "failed";
        tools: Tool[];
    }

    Hierarchy (View Summary)

    Index
    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.

    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.

    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)
    }
    complete: (params: CompleteRequestParams) => Promise<CompleteResult>

    Request completion suggestions for a prompt or resource template argument.

    Type Declaration

      • (params: CompleteRequestParams): Promise<CompleteResult>
      • Parameters

        • params: CompleteRequestParams

          Completion request parameters specifying the ref and argument to complete.

        Returns Promise<CompleteResult>

        A promise that resolves with completion suggestions from the server.

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

    disconnect: () => Promise<void>

    Disconnects the client from the MCP server.

    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.

    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: "debug" | "info" | "warn" | "error";
        message: string;
        timestamp: number;
    }[]

    Array of internal log messages (useful for debugging)

    Type Declaration

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

      Log severity.

    • message: string

      Human-readable log message.

    • timestamp: number

      Unix timestamp in milliseconds when the entry was created.

    name: string

    Name advertised by the connected MCP server.

    prompts: Prompt[]

    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.
    protocolVersion?: string

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

    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.

    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.

    resources: Resource[]

    List of resources available from the connected MCP server

    resourceTemplates: ResourceTemplate[]

    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.

    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.
    tools: Tool[]

    List of tools available from the connected MCP server