MCP Session Management#

Overview#

McpSessionController class is used to manage the entire connection lifecycle with the MCP (Model Context Protocol) server. It is responsible for connection establishment, session management, exception-safe disconnection, and ensuring the correct release of resources through asynchronous context managers. This component can maintain a persistent connection state when necessary.

Core Functions#

  1. Connection Lifecycle Management - Automatically handle the connection/disconnection of the MCP server through an asynchronous context manager.

  2. Session Status Monitoring - Provides the is_connect attribute for real-time monitoring of the connection status.

  3. Persistent Connection Support - Controls whether to disconnect on exit via the persistent_link parameter.

  4. Background Task Management - Maintain asynchronous session threads to implement non-blocking communication

  5. Exception-Safe Disconnect - Automatically performs cleanup operations when handling communication errors.

Create Session Controller#

The following example shows the basic usage of creating the McpSession controller:

from mcp import McpServerLink
from evofabric.core.tool import McpSessionController
from evofabric.core.typing import StdioLink

# Create MCP server link
server_link = StdioLink(
    command="python",
    args=[str(current_dir / "your_mcp_server.py")],
)

# Initialize the session controller
session_controller = McpSessionController(
    server_link=server_link,
    server_name="math_service",
    persistent_link=False  # Disconnect when exiting context
)

# Establish connection using async context manager
async with session_controller:
    print(f"Connected: {session_controller.is_connect}")
    await session_controller.session.list_tools()

# Connection automatically closed when persistent_link=False

Attribute Description#

  • session (read-only): Returns the current active client session object

  • is_connect (read-only): A boolean value indicating the current connection state.

  • persistent_link: A boolean flag that controls whether the connection is maintained when the context exits.

  • server_name: Read-only string identifying the name of the connected MCP server.

Asynchronous Methods Explained#

connect()#

Establish an asynchronous connection to the MCP server: - Safe and repeatable (repeated calls will be ignored) - Create a background maintenance task to wait for the connection to be ready - Set the _connected flag after the connection is fully established

await session_controller.connect()
assert session_controller.is_connect == True

disconnect()#

Disconnect MCP connection and reset internal state. Includes:

  • Cancel background maintenance task

  • Clear connection-related properties

  • Automatically handle cancel and close exceptions.

await session_controller.disconnect()
assert session_controller.is_connect == False

Asynchronous Context Manager#

The controller implements Python’s asynchronous context manager protocol, ensuring automatic resource management:

# Standard usage: auto connect & auto disconnect
async with McpSessionController(...) as controller:
    print(f"Connected: {controller.is_connect}")
    # Perform operations...

# Persistent mode: connection stays open after exiting context
controller = McpSessionController(..., persistent_link=True)
async with controller:
    # Perform operations...
# Connection remains active here

Note

When persistent_link=True is set, the session will not automatically disconnect after exiting the asynchronous context manager. In this mode, the user must explicitly call disconnect() to release the network connection and background tasks. Otherwise, it may lead to resource leaks (such as pending session coroutines, unreleased socket connections, etc.).