fastmcp.server.sessions
Stateless session state: server-side per-user and per-session storage.
Modern (2026-07-28) MCP connections are stateless by construction — every
request builds a fresh connection whose in-memory state is discarded when the
request returns. This module gives tools two explicit ways to keep state across
calls, both backed by the server’s existing state store and both isolated by the
authenticated principal rather than by any client-declared identifier.
Session: asyncget/set/delete/clearover a single dict stored under one key, scoped to a(principal, session_id)pair. This is the state-accessor object a handler works with — the value the standaloneget_session(id)returns and the value injected for aUserSessionparameter.session: UserSession(injected): a per-user bucket, dependency-injected likectx: Contextand keyed by the request’s authenticated principal. Requires auth.UserSessionis the injection annotation; the injected value is aSession. It is always available under auth — nocreate_session, no provider, no validation.session_id: SessionId(argument): a required string the agent supplies, resolved with the standaloneawait get_session(session_id). The id is minted bycreate_session; an id that was never created (or was created under a different principal) is rejected. This validation is the whole guarantee — an unminted id never resolves, so nothing enforces provider registration.SessionProvider: aProvidercontributingcreate_session/end_sessiontools. Register it withmcp.add_provider(SessionProvider())so a tool that takessession_idhas a way to mint ids; without it, no id can be created, so those tools simply cannot resolve a session.
(principal, session_id) means a request under principal B can never address
principal A’s keys, no matter what session_id it passes; the id only organizes
sessions within a principal. Without auth there is no principal wall — a session
id is a bearer capability and sessions are not a boundary between clients.
Functions
current_principal
(client_id, issuer, subject) triple encoded as compact JSON, or
None on an unauthenticated request. Two users of one OAuth client are
distinct principals whenever the token verifier supplies a subject.
session_storage_key
(principal, session_id): the principal is the isolation wall, the
id organizes sessions within it. A session’s whole state lives under this one
key as a dict, so one key means one store TTL per session and end is a
single delete.
session_id_parameter_names
SessionId.
Scans resolved type hints for Annotated[str, _SessionIdMarker()] metadata.
Returns an empty tuple when the hints cannot be resolved (the function then
simply carries no auto-populated session-id description).
functools.partial is unwrapped first, since get_type_hints rejects a
partial object — FastMCP supports registering a partial as a tool, and its
schema is still built from the underlying function, so its SessionId
parameters must be detected here too. Parameters the partial has already
bound — positionally or by keyword — are dropped, matching the tool’s actual
argument surface (the partial’s own signature already reflects this).
CurrentSession
Session for the current authenticated principal.
Rarely written explicitly — a session: UserSession parameter is rewritten
to this. Provided for parity with CurrentContext() when an explicit default
is preferred.
OptionalCurrentSession
Session, or None when the request is unauthenticated.
Rarely written explicitly — a session: UserSession | None = None parameter
is rewritten to this. Provided for parity with OptionalCurrentContext().
create_session
uuid4, records an initial session owned by the current
principal, and returns the id as a string. Store it and pass it back as a
session_id argument on later calls to persist state across a session — only
an id created this way resolves. State is keyed by the authenticated
principal, so the id organizes sessions within a user; on an unauthenticated
connection the id is the only thing standing between callers, which is why it
is unguessable.
end_session
Classes
SessionAuthError
An injected session: UserSession was requested with no authenticated principal.
Per-user session injection keys off the request’s authenticated principal, so
it is only meaningful under auth. A tool that needs cross-call state without
auth should take a session_id: SessionId argument instead.
InvalidSession
A session id did not resolve to a session created under the current principal.
Raised by get_session(session_id) when the id was never created, or was
created under a different principal. The public message is deliberately
generic — the specific reason (which id, which principal) is logged at debug
level, not returned to the caller, so an attacker cannot distinguish “unknown
id” from “belongs to someone else”.
Session
Async accessors over one (principal, session_id) bucket of state.
A session’s state is a single dict stored under one key. That dict holds user
state in a state sub-dict and a small creation marker alongside it, so a
created-but-empty session is still distinguishable from a missing one.
get/set/delete read-modify-write the sub-dict; clear empties the
sub-dict but keeps the session valid; end deletes the whole key. Writes
never impose a TTL — retention is entirely the server store’s (configure it on
the store you pass to FastMCP(session_state_store=...)).
Concurrent writes to one session race on the read-modify-write; session state
is small and typically driven serially by one agent, so this is acceptable.
Methods:
id
None for an injected per-user session.
For a session resolved from a session_id argument (or minted by
create_session) this is that id. An injected UserSession has no
distinct id — its bucket is the authenticated user — so it is None; the
internal principal-derived key is deliberately not exposed here.
get
key, or default when it is not set.
set
value under key in this session (read-modify-write).
Preserves the creation marker: only the user-state sub-dict is touched.
delete
key from this session, if present (preserves the marker).
clear
get_session.
To invalidate a session entirely, use end (what end_session calls).
end
get_session. This is
what end_session calls; clear only empties state and keeps the session.
UserSession
Annotation marker for the injected per-user session.
A session: UserSession parameter is dependency-injected like
ctx: Context: keyed by the request’s authenticated principal, excluded from
the input schema, and requiring auth (it raises SessionAuthError with no
principal). It doubles as the injection annotation and the injected
type — the value a handler receives is a UserSession, which subclasses
Session, so await session.get(...), .set, .delete, and .clear all
work exactly as on any other Session.
Unlike session_id: SessionId, the per-user bucket needs no create_session,
no SessionProvider, and no validation — it is always available under auth,
keyed directly by the caller’s identity.
Session only so the framework’s type-based injection detector can
key off it; it adds no behavior of its own.
SessionProvider
Provider contributing the session lifecycle tools.
Register it whenever a tool declares a session_id: SessionId argument:
create_session()mints an unguessableuuid4, records the session, and returns the id.end_session(session_id)invalidates that session and deletes its state.
session_state_store) and imposes no TTL (retention is the store’s). It
exists to mint and end owned session ids. Registration is not enforced: with
no provider, no id can be created, so every get_session(...) rejects —
a session_id tool without a provider simply cannot resolve a session.
