mcp-use TypeScript API
    Preparing search index...

    Class MCPConnection

    A ready connection to an MCP server.

    The connection has the same public API for legacy, sessionful MCP servers and modern, sessionless MCP servers. The underlying SDK owns the lifecycle distinction and protocol negotiation.

    Sessions handle:

    • Connection lifecycle (connect, disconnect, initialize)
    • Tool invocation
    • Resource access
    • Prompt retrieval
    • Notification handling
    • Root directory management

    Sessions are typically created by MCPClient.createSession() rather than being instantiated directly.

    // Create via client
    const client = new MCPClient('./config.json');
    const session = await client.createSession('my-server');

    // Use the session
    const tools = await session.listTools();
    const result = await session.callTool('my-tool', { arg: 'value' });
    // Manual creation (advanced)
    import { StdioConnector } from "@mcp-use/client";

    const connector = new StdioConnector({
    command: 'node',
    args: ['server.js']
    });
    const session = new MCPSession(connector);
    await session.initialize();

    BaseConnector for connector implementations

    Index
    • Creates a new MCP session.

      Parameters

      • connector: BaseConnector

        The connector to use for communication (Stdio, HTTP, WebSocket)

      • autoConnect: boolean = true

        Whether to automatically connect during initialization (default: true)

      Returns MCPConnection

      const connector = new HttpConnector({ url: 'http://localhost:3000/mcp' });
      const session = new MCPSession(connector);
      await session.initialize(); // Auto-connects and initializes
      // Manual connection control
      const session = new MCPSession(connector, false);
      await session.connect();
      await session.initialize();
    connector: BaseConnector

    The underlying connector managing the transport layer. This is the Stdio, HTTP, or WebSocket connector handling actual communication.

    • get info(): MCPConnectionInfo

      Normalized server metadata for this ready connection.

      Returns MCPConnectionInfo

      When called before protocol negotiation completes.

    • get isConnected(): boolean

      Checks if the session is currently connected to the server.

      Returns boolean

      True if connected, false otherwise

      if (session.isConnected) {
      const tools = await session.listTools();
      }
    • get negotiatedProtocolVersion(): string | undefined

      The negotiated protocol version string for this session's connection.

      Returns string | undefined

    • get protocolEra(): ProtocolEra | undefined

      The negotiated protocol era for this session's connection: "legacy" (2025-era) or "modern" (2026-07-28-era). undefined before the connection has negotiated.

      Returns ProtocolEra | undefined

    • get serverCapabilities(): Record<string, unknown>

      Get the server capabilities advertised during initialization.

      Returns Record<string, unknown>

      Server capabilities object

    • get serverInfo(): MCPServerInfo | null

      Get the server information (name and version).

      Returns MCPServerInfo | null

      Server info object or null if not available

    • get tools(): {}[]

      Get the cached list of tools from the server.

      Returns {}[]

      Array of available tools

      const tools = session.tools;
      console.log(`Available tools: ${tools.map(t => t.name).join(", ")}`);
    • Call a tool on the server.

      Parameters

      • name: string

        Name of the tool to call

      • args: Record<string, any> = {}

        Arguments to pass to the tool (defaults to empty object)

      • Optionaloptions: RequestOptions

        Optional request options (timeout, progress handlers, etc.)

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

      Result from the tool execution

      const result = await session.callTool("add", { a: 5, b: 3 });
      console.log(`Result: ${result.content[0].text}`);
    • Request completion suggestions for a prompt or resource template argument.

      Parameters

      • params: {}

        Completion request parameters

      • Optionaloptions: RequestOptions

        Request options

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

      Completion suggestions from the server

      // Complete a prompt argument
      const result = await session.complete({
      ref: { type: "ref/prompt", name: "my-prompt" },
      argument: { name: "language", value: "py" }
      });
      console.log(result.completion.values); // ["python"]
    • Establishes the connection to the MCP server.

      This method starts the underlying transport (spawns process for Stdio, opens WebSocket, etc.) but does not perform the MCP initialization handshake. Call initialize after connecting.

      Returns Promise<void>

      Promise that resolves when connected

      await session.connect();
      await session.initialize();
    • Closes the connection to the MCP server.

      This method gracefully shuts down the transport and cleans up resources. After disconnecting, the session cannot be used until reconnected.

      Returns Promise<void>

      Promise that resolves when disconnected

      await session.disconnect();
      console.log('Session closed');

      connect for establishing connections

    • Get a specific prompt with arguments.

      Parameters

      • name: string

        Name of the prompt to get

      • args: Record<string, any>

        Arguments for the prompt

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

      Prompt result

      const prompt = await session.getPrompt("greeting", { name: "Alice" });
      console.log(prompt.messages);
    • Gets the current roots advertised to the server.

      Roots represent directories or files that the client has provided access to. The server may use this information to scope its operations.

      Returns {}[]

      Array of Root objects

      const roots = session.getRoots();
      console.log(`Current roots: ${roots.map(r => r.uri).join(', ')}`);

      setRoots for updating roots

    • Initializes the MCP session with the server.

      This method performs the MCP initialization handshake, exchanging capabilities and metadata with the server. If autoConnect is true and the session is not yet connected, it will connect first.

      After initialization, you can list and call tools, read resources, etc.

      Returns Promise<void>

      Promise that resolves when initialized

      const session = await client.createSession('my-server', false);
      await session.connect();
      await session.initialize();
      // Now ready to use
      const tools = await session.listTools();

      connect for establishing the connection first

    • List all resources from the server, automatically handling pagination.

      Parameters

      • Optionaloptions: RequestOptions

        Request options

      Returns Promise<{ resources: any[] }>

      Complete list of all resources

      const result = await session.listAllResources();
      console.log(`Total resources: ${result.resources.length}`);
    • List available prompts from the server.

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

      List of available prompts

      const result = await session.listPrompts();
      console.log(`Available prompts: ${result.prompts.length}`);
    • List resources from the server with optional pagination.

      Parameters

      • Optionalcursor: string

        Optional cursor for pagination

      • Optionaloptions: RequestOptions

        Request options

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

      Resource list with optional nextCursor for pagination

      const result = await session.listResources();
      console.log(`Found ${result.resources.length} resources`);
    • List resource templates from the server.

      Parameters

      • Optionaloptions: RequestOptions

        Request options

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

      List of available resource templates

      const result = await session.listResourceTemplates();
      console.log(`Available templates: ${result.resourceTemplates.length}`);
    • List all available tools from the MCP server. This method fetches fresh tools from the server, unlike the tools getter which returns cached tools.

      Parameters

      • Optionaloptions: RequestOptions

        Optional request options

      Returns Promise<{}[]>

      Array of available tools

      const tools = await session.listTools();
      console.log(`Available tools: ${tools.map(t => t.name).join(", ")}`);
    • Register an event handler for session events

      Parameters

      • event: "notification"

        The event type to listen for

      • handler: NotificationHandler

        The handler function to call when the event occurs

      Returns void

      session.on("notification", async (notification) => {
      console.log(`Received: ${notification.method}`, notification.params);

      if (notification.method === "notifications/tools/list_changed") {
      // Refresh tools list
      }
      });
    • Read a resource by URI.

      Parameters

      • uri: string

        URI of the resource to read

      • Optionaloptions: RequestOptions

        Request options

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

      Resource content

      const resource = await session.readResource("file:///path/to/file.txt");
      console.log(resource.contents);
    • Send a raw request through the client.

      Parameters

      • method: string

        MCP method name

      • params: Record<string, any> | null = null

        Request parameters

      • Optionaloptions: RequestOptions

        Request options

      Returns Promise<unknown>

      Response from the server

      const result = await session.request("custom/method", { key: "value" });
      
    • Set roots and notify the server. Roots represent directories or files that the client has access to.

      Parameters

      • roots: {}[]

        Array of Root objects with uri (must start with "file://") and optional name

      Returns Promise<void>

      Roots are a v1 compatibility feature and are not part of the sessionless v2 protocol.

      await session.setRoots([
      { uri: "file:///home/user/project", name: "My Project" },
      { uri: "file:///home/user/data" }
      ]);
    • Subscribe to resource updates.

      Parameters

      • uri: string

        URI of the resource to subscribe to

      • Optionaloptions: RequestOptions

        Request options

      Returns Promise<{}>

      await session.subscribeToResource("file:///path/to/file.txt");
      // Now you'll receive notifications when this resource changes
    • Whether the server advertised a named MCP capability.

      Parameters

      • capability: string

        A top-level capability name such as "tools" or "resources".

      Returns boolean

    • Unsubscribe from resource updates.

      Parameters

      • uri: string

        URI of the resource to unsubscribe from

      • Optionaloptions: RequestOptions

        Request options

      Returns Promise<{}>

      await session.unsubscribeFromResource("file:///path/to/file.txt");