Skip to main content

What are Sessions?

Sessions in FastMCP represent a connection between a client and your MCP server. Each session has its own lifecycle, authentication context, and event stream. Understanding sessions is crucial for building stateful MCP servers.

Session Lifecycle

A session goes through several stages:
  1. Connection - Client connects to the server
  2. Ready - Session is initialized and ready to handle requests
  3. Active - Session is processing requests
  4. Disconnect - Client disconnects or connection is lost

Session Events

Listen to session events to track connections and manage state:

Connect Event

Disconnect Event

Ready Event

Error Event

Session Context

The session context is available in tool execution, resource loading, and prompt generation:

In Tools

In Resources

In Prompts

Session IDs

Session IDs help track individual client connections:

HTTP-based Transports

For HTTP Stream and SSE transports, the session ID comes from the Mcp-Session-Id header:

Request IDs

Track individual requests within a session:

Authentication Context

Define custom session authentication types:

Roots Management

Roots allow clients to provide filesystem-like root locations:

Accessing Roots

Using Roots in Tools

Disabling Roots

You can disable roots support:
Disabling roots is useful for better compatibility with clients that don’t support the roots capability.

Session State Management

Track state across multiple requests in a session:

Complete Example

Here’s a complete example showing session management:

API Reference

FastMCPSession Type

Context Type