View the source code for this module on GitHub: https://github.com/mcp-use/mcp-use/blob/main/libraries/typescript/packages/mcp-use/src/server/sessions/index.ts
SessionStore persists serializable session metadata (client capabilities, log level, timestamps), while a StreamManager tracks active SSE connections that cannot be serialized (the ReadableStreamDefaultController for each stream). You pass an instance of each to the MCPServer constructor through the sessionStore and streamManager options. Everything on this page is exported from mcp-use/server.
- Single instance, sessions can reset on restart:
InMemorySessionStore+InMemoryStreamManager(the production defaults). - Single instance with hot reload, sessions should survive a restart:
FileSystemSessionStore(the default whenNODE_ENV !== "production"). - Distributed or load-balanced deployment:
RedisSessionStore+RedisStreamManager.
InMemorySessionStore
Default session storage backed by a JavaScriptMap. Sessions live in memory and are lost on server restart. Suitable for development, single-instance deployments, and apps where losing sessions on restart is acceptable. Not suitable for distributed or horizontally scaled deployments. Implements SessionStore.
get
Retrieve session metadata by ID. Returnsnull when the session is not present.
Parameters
ReturnsThe unique session identifier.
Signature
set
Store or update session metadata under a session ID. ParametersReturnsThe unique session identifier.Serializable session metadata to store.
Signature
delete
Remove session metadata for a session ID. ParametersReturnsThe unique session identifier.
Signature
has
Check whether session metadata exists for a session ID. ParametersReturnsThe unique session identifier.
Signature
keys
List all stored session IDs. ReturnsSignature
setWithTTL
Store session metadata that auto-expires afterttlMs milliseconds. The in-memory implementation schedules deletion with setTimeout, so the timer is lost on restart. For production TTL backed by the storage engine, use RedisSessionStore.
Parameters
ReturnsThe unique session identifier.Serializable session metadata to store.Time to live in milliseconds before the session is removed.
Signature
size
The current number of active sessions. Read-only getter, useful for monitoring and debugging. ReturnsSignature
clear
Remove all sessions from the store. Useful for testing and manual cleanup. ReturnsSignature
FileSystemSessionStore
Session storage that persists metadata to a JSON file on disk, so sessions survive server hot reloads (tsx, nodemon) without forcing clients to re-initialize. Writes use a debounced, write-to-temp-then-rename atomic pattern to avoid corruption. Designed for development with hot reload and single-instance deployments that need persistence. Not suitable for production or distributed deployments (useInMemorySessionStore or RedisSessionStore). Implements SessionStore.
path, skipping sessions older than maxAgeMs. A missing file or corrupted JSON is handled gracefully and the store starts fresh.
Parameters
SignatureStore configuration. SeeFileSystemSessionStoreConfigfor fields and defaults.
get
Retrieve session metadata by ID. Returnsnull when the session is not present.
Parameters
ReturnsThe unique session identifier.
Signature
set
Store or update session metadata, then schedule a debounced save to disk. ParametersReturnsThe unique session identifier.Serializable session metadata to store.
Signature
delete
Remove session metadata, then schedule a debounced save to disk. ParametersReturnsThe unique session identifier.
Signature
has
Check whether session metadata exists for a session ID. ParametersReturnsThe unique session identifier.
Signature
keys
List all stored session IDs. ReturnsSignature
setWithTTL
Store session metadata with a TTL. This implementation resetslastAccessedAt to the current time, schedules a debounced save, and registers a setTimeout to delete the session after ttlMs. TTL is also enforced on load via maxAgeMs, so expired sessions are dropped when the file is read on the next start.
Parameters
ReturnsThe unique session identifier.Serializable session metadata to store.Time to live in milliseconds before the session is removed.
Signature
size
The current number of active sessions held in memory. Read-only getter. ReturnsSignature
clear
Remove all sessions and schedule a debounced save to disk. ReturnsSignature
flush
Force an immediate save to disk, bypassing the debounce timer. Useful for guaranteeing persistence before process exit. ReturnsSignature
RedisSessionStore
Production-ready session storage that persists metadata in Redis, so sessions survive restarts and can be shared across distributed, load-balanced instances. Stores only serializable metadata. For active SSE streams in a distributed setup, pair it withRedisStreamManager. Redis is an optional dependency: install it with npm install redis (or pnpm add redis). You pass an already-connected client through the config. Implements SessionStore.
RedisClient. The prefix defaults to "mcp:session:" and defaultTTL defaults to 3600 seconds (1 hour).
Parameters
SignatureStore configuration. SeeRedisSessionStoreConfigfor fields and defaults.
get
Retrieve and JSON-parse session metadata by ID. Returnsnull when the key is absent, and also returns null (after logging) if the read or parse fails, so a transient Redis error never throws here.
Parameters
ReturnsThe unique session identifier.
Signature
set
JSON-serialize and store session metadata with the configureddefaultTTL. Uses setEx (node-redis v5+), falls back to setex (ioredis), or finally set(key, value, { EX }). Re-throws on Redis errors.
Parameters
ReturnsThe unique session identifier.Serializable session metadata to store.
Signature
delete
Delete the Redis key for a session. Re-throws on Redis errors. ParametersReturnsThe unique session identifier.
Signature
has
Check whether a session key exists. Returnsfalse (after logging) on a Redis error rather than throwing.
Parameters
ReturnsThe unique session identifier.
Signature
keys
List all session IDs, returned with the key prefix stripped. Returns[] on a Redis error. Uses the Redis KEYS command, which blocks Redis. For production with many sessions, prefer SCAN or maintain a separate SET of active IDs.
Returns
Signature
setWithTTL
Store session metadata with a custom TTL.ttlMs is converted to seconds with Math.ceil(ttlMs / 1000) and applied via setEx, setex, or set(key, value, { EX }). Re-throws on Redis errors.
Parameters
ReturnsThe unique session identifier.Serializable session metadata to store.Time to live in milliseconds.
Signature
close
Close the underlying Redis connection by callingquit(). Call this on server shutdown. Re-throws on Redis errors.
Returns
Signature
clear
Delete every session key matching the configured prefix. Re-throws on Redis errors. Uses the blockingKEYS command, so it is intended for testing rather than production with large datasets.
Returns
Signature
InMemoryStreamManager
Default stream manager. It holds activeReadableStreamDefaultController instances in a Map so the server can push notifications and sampling responses to connected clients. Suitable for single-instance and non-distributed deployments. Not suitable for load-balanced deployments, where a stream may live on a different server (use RedisStreamManager). Implements StreamManager.
create
Register an active SSE stream controller for a session. ParametersReturnsThe unique session identifier.The controller for the SSE connection.
Signature
send
Encodedata and enqueue it directly to the in-memory controllers. When sessionIds is undefined the message is broadcast to every active stream; otherwise it is sent to the listed sessions. If a controller throws on enqueue (client disconnected or stream closed), that stale entry is removed.
Parameters
ReturnsSessions to send to, orundefinedto broadcast to all.SSE-formatted payload (for exampleevent: message\ndata: {...}\n\n).
Signature
delete
Close and remove the active stream for a session. A controller that is already closed is ignored. ParametersReturnsThe unique session identifier.
Signature
has
Check whether an active stream exists for a session. ParametersReturnsThe unique session identifier.
Signature
close
Close every active stream and clear the map. Call this on server shutdown. ReturnsSignature
size
The current number of active streams. Read-only getter, useful for monitoring. ReturnsSignature
RedisStreamManager
Distributed stream manager built on Redis Pub/Sub. Each server keeps its local controllers in memory and subscribes to a per-session Redis channel, so a notification published from any instance reaches the instance that actually holds the client’s SSE stream. It also implements the optional request/response routing methods so server-to-client requests (sampling, elicitation, roots) resolve correctly when the client’s response lands on a different instance. Redis is an optional dependency: install it withnpm install redis. Pub/Sub requires two clients, so pass a dedicated pubSubClient alongside the regular client. Implements StreamManager.
prefix defaults to "mcp:stream:" and heartbeatInterval defaults to 10 seconds; Redis keys expire after heartbeatInterval * 2.
Parameters
SignatureManager configuration. SeeRedisStreamManagerConfigfor fields and defaults.
create
Register an active SSE stream and subscribe to its Redis channel. Idempotent: an existing subscription for the same session is torn down first (handy on SSE reconnect). It stores the controller locally, marks the session available in Redis with an expiry ofheartbeatInterval * 2, adds the ID to an active-sessions SET, starts a heartbeat that refreshes those expiries, and subscribes to both the session channel and its delete: channel. Throws if the Pub/Sub client has no subscribe method, and re-throws other Redis errors.
Parameters
ReturnsThe unique session identifier.The controller for the SSE connection.
Signature
send
Publishdata to session channels via Redis Pub/Sub, so any instance holding the matching SSE stream forwards it to the client. With sessionIds set, it publishes to those sessions; when undefined, it broadcasts to all sessions in the active-sessions SET (falling back to a KEYS scan if SET operations are unavailable). Publishing uses the regular client, not pubSubClient, because a node-redis v5+ client in subscriber mode cannot publish. Throws if the client has no publish method, and re-throws other Redis errors.
Parameters
ReturnsSessions to publish to, orundefinedto broadcast to all active sessions.SSE-formatted payload.
Signature
delete
Tear down a session’s stream: stop its heartbeat, unsubscribe from the session and delete channels, publish a delete message so other servers clean up, remove the availability key, remove the ID from the active-sessions SET, and close the local controller if present. Throws if the client lacksunsubscribe or publish, and re-throws other Redis errors.
Parameters
ReturnsThe unique session identifier.
Signature
has
Check whether a session has an active stream on any server, by testing the availability key in Redis. Returnsfalse (after logging) on a Redis error.
Parameters
ReturnsThe unique session identifier.
Signature
close
Clear all heartbeats, then remove the availability keys and active-set entries only for sessions owned by this instance (important when several servers share one Redis), close every local controller, and clear local state. Re-throws on Redis errors. ReturnsSignature
localSize
The number of active local streams on this server instance. Read-only getter. ReturnsSignature
registerOutboundRequest
Record a pending outbound server-to-client request in Redis (keyed by session and request ID, with a 5-minute TTL) so its response can be routed back to this instance from any other instance. ParametersReturnsThe JSON-RPC request ID.The session the request belongs to.
Signature
forwardInboundResponse
Decide whether an inbound JSON-RPC response belongs to another instance. If a routing record exists for a differentserverId, publish the response to that server’s channel, delete the routing key, and return true. Returns false when there is no record, the record is unparseable, or the request originated locally (the local SDK Protocol handles it). Throws if the client has no publish method.
Parameters
ReturnsThe JSON-RPC response message; must have anid.The session the response belongs to.
Signature
onForwardedResponse
Register a handler invoked when a response is forwarded from another instance, and subscribe (once) to this server’s dedicated Pub/Sub channel. The handler should feed the response into the local transport so the SDK Protocol can resolve the pending request. If the Pub/Sub client has nosubscribe method, response forwarding is disabled with a warning rather than throwing.
Parameters
ReturnsCalled with the forwarded JSON-RPC response and its session ID.
Signature
Types
SessionStore
The pluggable contract for session metadata storage. It stores only serializableSessionMetadata (client capabilities, log level, timestamps), never runtime objects like transports, server instances, or stream controllers. For active SSE connections, use a StreamManager instead. All methods are async to support external backends such as Redis or Postgres. Implement this interface to back sessions with a custom store.
get, set, delete, has, and keys. setWithTTL is optional. get resolves to null when the session is missing.
Properties
SignatureRetrieve session metadata by ID, ornullif not found.Store or update session metadata.Delete session metadata.Check whether session metadata exists.List all session IDs, used for cleanup and monitoring.Optional. Store session metadata with automatic expiration afterttlMsmilliseconds.
SessionData
The complete in-memory session record. It extendsSessionMetadata with non-serializable runtime objects (transport, server, Hono context, the notification sender). Full SessionData exists only in memory on the server handling the session, never in a SessionStore.
SessionMetadata and adds the runtime references below. The notification callback receives an object shaped { method: string; params: Record<string, unknown> }.
Properties
SignatureThis session’s transport instance (not serializable).This session’s server instance (not serializable).Hono context for the session’s current request (not serializable).sendNotification(notification: { method: string; params: Record<string, unknown> }) => Promise<void>Function to send a notification to the client (not serializable).Express-like response object for notifications (not serializable).Hono context for direct response access (not serializable).
SessionMetadata
The serializable subset of a session that aSessionStore persists. It deliberately excludes runtime objects so it can be written to Redis, Postgres, or a JSON file. Only lastAccessedAt is required; the remaining fields capture negotiation state from initialization.
lastAccessedAt drives idle-timeout tracking and is the only required field.
Properties
SignatureTimestamp of last activity, used for idle-timeout tracking.Minimum log level for filtering log messages (RFC 5424 levels).Client capabilities advertised during initialization.Client info (name, version).Protocol version negotiated during initialization.Progress token for the current tool call, if any.
FileSystemSessionStoreConfig
Constructor options forFileSystemSessionStore. Every field is optional and has a default.
path defaults to .mcp-use/sessions.json resolved against process.cwd(). debounceMs defaults to 100. maxAgeMs defaults to 86400000 (24 hours).
Properties
SignaturePath to the session file, resolved against the project root.Debounce delay in milliseconds for write operations, batching rapid consecutive writes.Maximum session age in milliseconds. Sessions older than this are cleaned up on load (default: 24 hours).
RedisSessionStoreConfig
Constructor options forRedisSessionStore. Only client is required and must already be connected.
prefix defaults to "mcp:session:" and defaultTTL defaults to 3600 seconds.
Properties
SignatureRedis client instance (node-redis or ioredis). Must already be connected.Key prefix for session storage.Default TTL in seconds for sessions (default: 1 hour).Whether to serialize and deserialize session data.
RedisClient
The minimal Redis client contract used byRedisSessionStore and RedisStreamManager. It is compatible with node-redis v5+ and ioredis. Several methods are optional because the stores probe for whichever variant the underlying client provides (for example setEx versus setex, or the Pub/Sub and SET methods that only RedisStreamManager needs).
createClient) and ioredis both qualify.
Properties
SignatureGet a string value by key.Set a string value, with optional options (e.g.{ EX }).Set with expiry, node-redis v5+ variant.Set with expiry, ioredis variant.Delete one or more keys.Check existence of one or more keys.List keys matching a pattern.Set a key’s expiry, node-redis v5+ variant.Add members to a SET.Remove members from a SET.List members of a SET.Publish a message to a Pub/Sub channel.Subscribe to a Pub/Sub channel.Unsubscribe from a Pub/Sub channel.Close the connection.
StreamManager
The pluggable contract for managing active SSE stream connections, kept separate fromSessionStore because controllers cannot be serialized. It enables server-to-client push (notifications, sampling responses) and, through its optional methods, distributed request/response routing across load-balanced servers. create, send, delete, and has are required. close, registerOutboundRequest, forwardInboundResponse, and onForwardedResponse are optional and implemented by RedisStreamManager for distributed deployments.
SignatureRegister an active SSE stream controller for a session.Send data to specific streams, or broadcast whensessionIdsisundefined.Remove an active SSE stream.Check whether an active stream exists for a session.Optional. Close all connections and clean up on shutdown.Optional. Register a pending outbound server-to-client request for cross-instance routing.forwardInboundResponse(message: { id: string | number; [key: string]: unknown }, sessionId: string) => Promise<boolean>Optional. Forward an inbound response to its originating instance; returnstrueif forwarded.Optional. Register a handler for responses forwarded from other instances.
RedisStreamManagerConfig
Constructor options forRedisStreamManager. Pub/Sub needs a dedicated subscriber connection, so both pubSubClient and client are required and should be separate connections.
pubSubClient is used for subscriptions and client for availability checks and publishing. prefix defaults to "mcp:stream:" and heartbeatInterval defaults to 10 seconds, with Redis keys expiring after heartbeatInterval * 2.
Properties
SignatureRedis client for Pub/Sub subscriptions. Should be a separate connection fromclient.Redis client for checking session availability and publishing. Can be shared with theSessionStore.Channel prefix for Pub/Sub.Heartbeat interval in seconds to keep sessions alive. Redis keys expire after this interval times two.
Example: Redis-backed sessions
A complete server usingRedisSessionStore for persistent session metadata. With a connected client passed in, sessions survive restarts and deploys, so reconnecting clients keep the same session ID without re-initializing.