OptionalonCalled when a client connects to the server. Use for session initialization or connection tracking.
Important: This hook is invoked asynchronously (fire-and-forget) during session creation. It is NOT awaited — the session is returned to the transport before this hook completes. For async setup that must finish before the session handles requests, use the tool/resource handlers themselves.
During session close, onClientDisconnected IS awaited.
OptionalonCalled when a client disconnects from the server. Use for session cleanup or connection tracking.
OptionalonCalled when an unhandled error occurs. Use for error reporting/logging.
OptionalonCalled after server is fully started and accepting connections. Use for logging, metrics, or notifying external systems.
OptionalonCalled before server starts accepting connections. Use for initialization tasks (database, cache, external services).
OptionalonCalled after server has fully stopped. Use for final cleanup (close file handles, database connections).
OptionalonCalled when server begins shutdown process. Use for graceful cleanup (flush buffers, notify clients).
Lifecycle hooks for MCP servers.
Implement these hooks to execute code at specific points in the server lifecycle. All hooks are optional and async-friendly.
Example