Interface LifecycleObserver
Lifecycle-transition callbacks (willStart*, didStart*,
didFailToStart*, willStop*, and didStop*) are purely
observational. Soklet contains their failures; they cannot veto, delay, or
change startup, shutdown, or the published lifecycle result. Other callbacks
retain the inline behavior documented on their individual methods.
Transition callbacks are delivered serially by a daemon observer worker;
returning from Soklet.awaitShutdown() does
not join their delivery. They may be lost when the JVM exits. Essential
application cleanup belongs in bounded ShutdownCleanup, with an
application-owned delivery barrier if it depends on observer state.
Soklet may invoke callbacks concurrently from lifecycle, transport, and
request-handling threads. Implementations must therefore be thread-safe.
HTTP/SSE connection-acceptance, request-acceptance, request-read and transport-failure
callbacks can run inline on selector threads. Transport-failure and handler-queue
rejection log events can run there too. These callbacks must return promptly;
copy any required data into a bounded application queue before doing blocking work.
TCP acceptance and later SSE handshake rejection are distinct observations: one
connection can produce both didAcceptConnection and
didFailToAcceptConnection, so their counts are not mutually exclusive.
A
standard implementation can be acquired via the defaultInstance()
factory method.
Full documentation is available at https://www.soklet.com/docs/request-lifecycle.
- Author:
- Mark Allen
-
Method Summary
Modifier and TypeMethodDescriptionstatic @NonNull LifecycleObserverAcquires a threadsafeLifecycleObserverinstance with sensible defaults.default voiddidAcceptConnection(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress) Called after a server accepts a new TCP connection.default voiddidAcceptRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget) Called after a request is accepted for application-level handling.default voiddidEstablishSseConnection(@NonNull SseConnection sseConnection) Called after an SSE connection is established.default voiddidFailToAcceptConnection(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @NonNull ConnectionRejectionReason reason, @Nullable Throwable throwable) Called after a server fails to accept a new TCP connection.default voiddidFailToAcceptRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget, @NonNull RequestRejectionReason reason, @Nullable Throwable throwable) Called when a request fails to be accepted before application-level handling begins.default voiddidFailToEstablishSseConnection(@NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull SseConnection.HandshakeFailureReason connectionHandshakeFailureReason, @Nullable Throwable throwable) Called if an SSE connection fails to establish before an accepted response has been written.default voiddidFailToReadRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget, @NonNull RequestReadFailureReason reason, @Nullable Throwable throwable) Called when a request could not be read or parsed into a validRequest.default voiddidFailToStartHttpServer(@NonNull HttpServer httpServer, @NonNull Throwable throwable) Called after anHttpServerinstance was asked to start but did not reach readiness because startup failed, timed out, or was canceled.default voiddidFailToStartMcpServer(@NonNull McpServer mcpServer, @NonNull Throwable throwable) Called after anMcpServerinstance was asked to start but did not reach readiness because startup failed, timed out, or was canceled.default voiddidFailToStartSoklet(@NonNull Throwable throwable) Called after aSokletinstance was asked to start but did not reach readiness because startup failed, timed out, or was canceled.default voiddidFailToStartSseServer(@NonNull SseServer sseServer, @NonNull Throwable throwable) Called after anSseServerinstance was asked to start but did not reach readiness because startup failed, timed out, or was canceled.default voiddidFailToWriteResponse(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull MarshaledResponse marshaledResponse, @NonNull Duration responseWriteDuration, @NonNull Throwable throwable) Called after response data fails to write.default voiddidFailToWriteSseComment(@NonNull SseConnection sseConnection, @NonNull SseComment sseComment, @NonNull Duration writeDuration, @NonNull Throwable throwable) Called after an SSE comment fails to write.default voiddidFailToWriteSseEvent(@NonNull SseConnection sseConnection, @NonNull SseEvent sseEvent, @NonNull Duration writeDuration, @NonNull Throwable throwable) Called after an SSE event fails to write.default voiddidFinishMcpRequestHandling(@NonNull McpRequestContext requestContext, @NonNull McpRequestOutcome requestOutcome, @Nullable McpJsonRpcError jsonRpcError, @NonNull Duration requestDuration, @NonNull List<@NonNull Throwable> throwables) Called exactly once when an admitted semantic MCP request or notification reaches its client-visible terminal outcome.default voiddidFinishRequestHandling(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull MarshaledResponse marshaledResponse, @NonNull Duration duration, @NonNull List<@NonNull Throwable> throwables) Called after a request finishes processing.default voiddidReadRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget) Called when a request was successfully read or parsed into a validRequest.default voiddidReceiveLogEvent(@NonNull LogEvent logEvent) Called when Soklet emits a log event.default voidCalled when a server exposes an input rejection that occurred before a validRequestcould be constructed.default voiddidStartHttpServer(@NonNull HttpServer httpServer) Called after the server starts.default voiddidStartMcpRequestHandling(@NonNull McpRequestContext requestContext) Called when handling begins for an admitted semantic MCP request or notification.default voiddidStartMcpServer(@NonNull McpServer mcpServer) Called after the MCP server starts.default voiddidStartRequestHandling(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod) Called as soon as a request is received and a Resource Method has been resolved to handle it.default voidCalled after aSokletinstance starts.default voiddidStartSseServer(@NonNull SseServer sseServer) Called after the SSE server starts.default voiddidStopHttpServer(@NonNull HttpServer httpServer, @NonNull ShutdownComponentResult shutdownComponentResult) Called after the server publishes terminal evidence.default voiddidStopMcpServer(@NonNull McpServer mcpServer, @NonNull ShutdownComponentResult shutdownComponentResult) Called after the MCP server stops.default voiddidStopSoklet(@NonNull ShutdownResult shutdownResult) Called after aSokletinstance publishes its immutable result.default voiddidStopSseServer(@NonNull SseServer sseServer, @NonNull ShutdownComponentResult shutdownComponentResult) Called after the SSE server publishes terminal evidence.default voiddidTerminateResponseStream(@NonNull StreamingResponseHandle streamingResponseHandle, @NonNull StreamTermination streamTermination) Called after a streaming response terminates.default voiddidTerminateSseConnection(@NonNull SseConnection sseConnection, @NonNull StreamTermination streamTermination) Called after an SSE connection is terminated.default voiddidWriteResponse(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull MarshaledResponse marshaledResponse, @NonNull Duration responseWriteDuration) Called after a response is handed to the transport for writing.default voiddidWriteSseComment(@NonNull SseConnection sseConnection, @NonNull SseComment sseComment, @NonNull Duration writeDuration) Called after an SSE comment is written.default voiddidWriteSseEvent(@NonNull SseConnection sseConnection, @NonNull SseEvent sseEvent, @NonNull Duration writeDuration) Called after an SSE event is written.default voidwillAcceptConnection(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress) Called when a server is about to accept a new TCP connection.default voidwillAcceptRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget) Called when a request is about to be accepted for application-level handling.default voidwillEstablishSseConnection(@NonNull Request request, @Nullable ResourceMethod resourceMethod) Called before an SSE connection is established.default voidwillReadRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget) Called when Soklet is about to read or parse a request into a validRequest.default voidwillStartHttpServer(@NonNull HttpServer httpServer) Called before the server starts.default voidwillStartMcpServer(@NonNull McpServer mcpServer) Called before the MCP server starts.default voidCalled before aSokletinstance starts.default voidwillStartSseServer(@NonNull SseServer sseServer) Called before the SSE server starts.default voidwillStopHttpServer(@NonNull HttpServer httpServer) Called before the server stops.default voidwillStopMcpServer(@NonNull McpServer mcpServer) Called before the MCP server stops.default voidCalled before aSokletinstance stops.default voidwillStopSseServer(@NonNull SseServer sseServer) Called before the SSE server stops.default voidwillTerminateResponseStream(@NonNull StreamingResponseHandle streamingResponseHandle, @NonNull StreamTermination streamTermination) Called before a streaming response termination is reported as complete.default voidwillTerminateSseConnection(@NonNull SseConnection sseConnection, @NonNull StreamTermination streamTermination) Called before an SSE connection is terminated.default voidwillWriteResponse(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull MarshaledResponse marshaledResponse) Called before response data is written.default voidwillWriteResponseStream(@NonNull StreamingResponseHandle streamingResponseHandle) Called once before an admitted HTTP response stream is offered for writing and before its producer starts and beforedidFinishRequestHandling(ServerType, Request, ResourceMethod, MarshaledResponse, Duration, List).default voidwillWriteSseComment(@NonNull SseConnection sseConnection, @NonNull SseComment sseComment) Called before an SSE comment is written.default voidwillWriteSseEvent(@NonNull SseConnection sseConnection, @NonNull SseEvent sseEvent) Called before an SSE event is written.
-
Method Details
-
willStartSoklet
Called before aSokletinstance starts. This lifecycle-transition callback is observational; exceptions are contained. -
didStartSoklet
Called after aSokletinstance starts. This lifecycle-transition callback is observational; exceptions are contained. -
didFailToStartSoklet
Called after aSokletinstance was asked to start but did not reach readiness because startup failed, timed out, or was canceled. Thethrowableis the same cause exposed byShutdownResult.getStartupFailureCause()andThrowable.getCause(). The subsequentdidStopSoklet(ShutdownResult)callback supplies the structuredStartupDisposition. This lifecycle-transition callback is observational; exceptions are contained.- Parameters:
throwable- failed, timed-out, or canceled startup cause
-
willStopSoklet
Called before aSokletinstance stops. This lifecycle-transition callback is observational; exceptions are contained. -
didStopSoklet
Called after aSokletinstance publishes its immutable result. This lifecycle-transition callback is observational; exceptions are contained.- Parameters:
shutdownResult- aggregate lifecycle result
-
willStartHttpServer
Called before the server starts. This lifecycle-transition callback is observational; exceptions are contained. -
didStartHttpServer
Called after the server starts. This lifecycle-transition callback is observational; exceptions are contained. -
didFailToStartHttpServer
Called after anHttpServerinstance was asked to start but did not reach readiness because startup failed, timed out, or was canceled. The subsequentdidStopHttpServer(HttpServer, ShutdownComponentResult)callback supplies its structured terminal evidence. This lifecycle-transition callback is observational; exceptions are contained.- Parameters:
httpServer- HTTP server whose startup did not reach readinessthrowable- failed, timed-out, or canceled startup cause
-
willStopHttpServer
Called before the server stops. Also called for a configured server that never started, for example after a startup failure, so a precedingdidStartHttpServer(HttpServer)call is not guaranteed. This lifecycle-transition callback is observational; exceptions are contained. -
didStopHttpServer
default void didStopHttpServer(@NonNull HttpServer httpServer, @NonNull ShutdownComponentResult shutdownComponentResult) Called after the server publishes terminal evidence. Also called for a configured server that never started, for example after a startup failure, so a precedingdidStartHttpServer(HttpServer)call is not guaranteed. This lifecycle-transition callback is observational; exceptions are contained.- Parameters:
httpServer- stopped HTTP servershutdownComponentResult- lifecycle component shutdown result
-
willAcceptConnection
default void willAcceptConnection(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress) Called when a server is about to accept a new TCP connection.- Parameters:
serverType- the server type that is accepting the connectionremoteAddress- the best-effort remote address, ornullif unavailable
-
didAcceptConnection
default void didAcceptConnection(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress) Called after a server accepts a new TCP connection.- Parameters:
serverType- the server type that accepted the connectionremoteAddress- the best-effort remote address, ornullif unavailable
-
didFailToAcceptConnection
default void didFailToAcceptConnection(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @NonNull ConnectionRejectionReason reason, @Nullable Throwable throwable) Called after a server fails to accept a new TCP connection.- Parameters:
serverType- the server type that failed to accept the connectionremoteAddress- the best-effort remote address, ornullif unavailablereason- the failure reasonthrowable- an optional underlying cause, ornullif not applicable
-
willAcceptRequest
default void willAcceptRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget) Called when a request is about to be accepted for application-level handling.- Parameters:
serverType- the server type that received the requestremoteAddress- the best-effort remote address, ornullif unavailablerequestTarget- the raw request target (path + query) if known, ornullif unavailable
-
didAcceptRequest
default void didAcceptRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget) Called after a request is accepted for application-level handling.- Parameters:
serverType- the server type that received the requestremoteAddress- the best-effort remote address, ornullif unavailablerequestTarget- the raw request target (path + query) if known, ornullif unavailable
-
didFailToAcceptRequest
default void didFailToAcceptRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget, @NonNull RequestRejectionReason reason, @Nullable Throwable throwable) Called when a request fails to be accepted before application-level handling begins.- Parameters:
serverType- the server type that received the requestremoteAddress- the best-effort remote address, ornullif unavailablerequestTarget- the raw request target (path + query) if known, ornullif unavailablereason- the rejection reasonthrowable- an optional underlying cause, ornullif not applicable
-
willReadRequest
default void willReadRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget) Called when Soklet is about to read or parse a request into a validRequest.- Parameters:
serverType- the server type that received the requestremoteAddress- the best-effort remote address, ornullif unavailablerequestTarget- the raw request target (path + query) if known, ornullif unavailable
-
didReadRequest
default void didReadRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget) Called when a request was successfully read or parsed into a validRequest.- Parameters:
serverType- the server type that received the requestremoteAddress- the best-effort remote address, ornullif unavailablerequestTarget- the raw request target (path + query) if known, ornullif unavailable
-
didFailToReadRequest
default void didFailToReadRequest(@NonNull ServerType serverType, @Nullable InetSocketAddress remoteAddress, @Nullable String requestTarget, @NonNull RequestReadFailureReason reason, @Nullable Throwable throwable) Called when a request could not be read or parsed into a validRequest.- Parameters:
serverType- the server type that received the requestremoteAddress- the best-effort remote address, ornullif unavailablerequestTarget- the raw request target (path + query) if known, ornullif unavailablereason- the failure reasonthrowable- an optional underlying cause, ornullif not applicable
-
didRejectUnparsedRequest
Called when a server exposes an input rejection that occurred before a validRequestcould be constructed.Captured bytes are untrusted and may contain credentials or other sensitive values. Implementations should apply appropriate redaction and retention policies before logging or storing them.
The built-in HTTP and SSE transports use this callback for malformed requests, overlong request targets, unsupported expectations, oversized request headers, partial-request read timeouts and early aggregate-size violations. HTTP construction failures such as invalid URI encoding, unsupported content coding and malformed compressed bodies also use this callback; those later failures provide an observed wire count with an empty, truncated capture. Idle timeouts and EOF before complete headers close quietly. Admission, shutdown and broken-socket failsafes do not use this callback.
The transport invokes this callback at most once for a rejected request whose detail task is accepted. It dispatches the callback to the configured request-handler executor and never invokes it inline on the selector thread. The framework-managed default executor has bounded concurrency and queue capacity; a custom executor controls its own capacity. If timeout budget remains afterward, the transport invokes
ResponseMarshaler.forUnparsedRequest(UnparsedRequest). The callback should perform bounded work and must not block. The request-handler timeout bounds how long the transport waits, using the remaining budget for later HTTP validation failures and SSE rejections; cancellation interrupts the worker but is cooperative if application code ignores interruption. If application capacity is unavailable, both callbacks may be skipped and the transport writes its built-in bodyless response instead. Exceptions are contained and reported asLogEventType.LIFECYCLE_OBSERVER_DID_REJECT_UNPARSED_REQUEST_FAILED; they do not alter the rejection response.- Parameters:
request- immutable snapshot of the rejected unparsed request
-
didStartRequestHandling
default void didStartRequestHandling(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod) Called as soon as a request is received and a Resource Method has been resolved to handle it.- Parameters:
serverType- the server type that received the request
-
didFinishRequestHandling
default void didFinishRequestHandling(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull MarshaledResponse marshaledResponse, @NonNull Duration duration, @NonNull List<@NonNull Throwable> throwables) Called after a request finishes processing. -
willWriteResponse
default void willWriteResponse(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull MarshaledResponse marshaledResponse) Called before response data is written.This callback sees the logical response before transport preparation. The built-in HTTP transport may subsequently replace it (for example, an HTTP/1.0 streaming response with a finite 505 rejection).
didWriteResponse(ServerType, Request, ResourceMethod, MarshaledResponse, Duration)anddidFinishRequestHandling(ServerType, Request, ResourceMethod, MarshaledResponse, Duration, List)receive the replacement; the stream termination handle retains the original streaming response. -
didWriteResponse
default void didWriteResponse(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull MarshaledResponse marshaledResponse, @NonNull Duration responseWriteDuration) Called after a response is handed to the transport for writing. For an HTTP stream, this does not mean that its body has finished; usedidTerminateResponseStream(StreamingResponseHandle, StreamTermination)for stream termination. When the built-in HTTP transport replaces a response before commitment, this callback receives the finite response actually offered, including its status and headers. -
didFailToWriteResponse
default void didFailToWriteResponse(@NonNull ServerType serverType, @NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull MarshaledResponse marshaledResponse, @NonNull Duration responseWriteDuration, @NonNull Throwable throwable) Called after response data fails to write. -
willWriteResponseStream
Called once before an admitted HTTP response stream is offered for writing and before its producer starts and beforedidFinishRequestHandling(ServerType, Request, ResourceMethod, MarshaledResponse, Duration, List). The handle retains the original dispatchedRequestobject by identity. Preparation does not mean headers or body bytes reached the client. Finite replacements and suppressed bodies do not invoke this callback. It is paired with stream termination, including failures before production starts. Implementations must return promptly; their failures are contained and do not cancel the stream. Custom transports own the corresponding preparation and terminal notifications using the exact same handle instance and original dispatched request. Stream termination notifications may arrive before handling finish; observers that combine those events must retain the pending outcome and return without waiting. Delegating observers must forward this preparation callback and the terminal callbacks to preserve stream lifetime accounting.- Parameters:
streamingResponseHandle- the admitted HTTP response stream
-
willTerminateResponseStream
default void willTerminateResponseStream(@NonNull StreamingResponseHandle streamingResponseHandle, @NonNull StreamTermination streamTermination) Called before a streaming response termination is reported as complete.This is paired with
didTerminateResponseStream(StreamingResponseHandle, StreamTermination). Admitted HTTP stream notifications follow metrics handling finish and terminal metrics delivery, and may precede lifecycle handling finish. Earlier handling/write callbacks must return to allow this ordering to advance. For standard HTTP response streams, the two callbacks are normally invoked back-to-back because there is no broadcaster or session registry cleanup phase between them.- Parameters:
streamingResponseHandle- the stream that is terminatingstreamTermination- why and when the stream terminated
-
didTerminateResponseStream
default void didTerminateResponseStream(@NonNull StreamingResponseHandle streamingResponseHandle, @NonNull StreamTermination streamTermination) Called after a streaming response terminates.If a stream is rejected before body bytes are written,
StreamingResponseHandle.getMarshaledResponse()returns the original application-provided streaming response. For example, an HTTP/1.0 request for a streaming response is rejected on the wire with505 HTTP Version Not Supported, while this callback still receives the original streaming response that was rejected. Admission and producer-executor rejection likewise offer one notification retaining the original stream. The finite failsafe response and synchronous request-handling finish do not wait for it. Unadmitted-stream observation uses a separate bounded allowance on the managed callback executor. Capacity exhaustion while accepting omits that observation and logsLogEventType.RESPONSE_STREAM_CANCELED; omissions during graceful drain or forced shutdown are not logged. Admitted streams retain their reserved callback jobs.Admitted HTTP streaming notifications have independent worker capacity, bounded by
HttpServer.Builder.streamingLifecycleCapacity(Integer). They can run more concurrently thanHttpServer.Builder.streamingCallbackConcurrency(Integer), which bounds cancelation batches and unadmitted rejection observers. A blocked admitted observer retains its own lifetime through physical exit, while other admitted streams can report termination and retire. Cleanup diagnostics use another independently bounded executor. The built-in simulator waits for its own termination observer, without holding up other streams' observers. Implementations must support concurrent delivery and return promptly.- Parameters:
streamingResponseHandle- the stream that terminatedstreamTermination- why and when the stream terminated
-
willStartSseServer
Called before the SSE server starts. This lifecycle-transition callback is observational; exceptions are contained. -
didStartSseServer
Called after the SSE server starts. This lifecycle-transition callback is observational; exceptions are contained. -
didFailToStartSseServer
Called after anSseServerinstance was asked to start but did not reach readiness because startup failed, timed out, or was canceled. The subsequentdidStopSseServer(SseServer, ShutdownComponentResult)callback supplies its structured terminal evidence. This lifecycle-transition callback is observational; exceptions are contained.- Parameters:
sseServer- SSE server whose startup did not reach readinessthrowable- failed, timed-out, or canceled startup cause
-
willStopSseServer
Called before the SSE server stops. Also called for a configured server that never started, for example after a startup failure, so a precedingdidStartSseServer(SseServer)call is not guaranteed. This lifecycle-transition callback is observational; exceptions are contained. -
didStopSseServer
default void didStopSseServer(@NonNull SseServer sseServer, @NonNull ShutdownComponentResult shutdownComponentResult) Called after the SSE server publishes terminal evidence. Also called for a configured server that never started, for example after a startup failure, so a precedingdidStartSseServer(SseServer)call is not guaranteed. This lifecycle-transition callback is observational; exceptions are contained.- Parameters:
sseServer- stopped SSE servershutdownComponentResult- lifecycle component shutdown result
-
willStartMcpServer
Called before the MCP server starts. This lifecycle-transition callback is observational; exceptions are contained.- Parameters:
mcpServer- the MCP server that will start
-
didStartMcpServer
Called after the MCP server starts. This lifecycle-transition callback is observational; exceptions are contained.- Parameters:
mcpServer- the MCP server that started
-
didFailToStartMcpServer
Called after anMcpServerinstance was asked to start but did not reach readiness because startup failed, timed out, or was canceled. The subsequentdidStopMcpServer(McpServer, ShutdownComponentResult)callback supplies its structured terminal evidence. This lifecycle-transition callback is observational; exceptions are contained.- Parameters:
mcpServer- MCP server whose startup did not reach readinessthrowable- failed, timed-out, or canceled startup cause
-
willStopMcpServer
Called before the MCP server stops. Also called for a configured server that never started, for example after a startup failure, so a precedingdidStartMcpServer(McpServer)call is not guaranteed. This lifecycle-transition callback is observational; exceptions are contained.- Parameters:
mcpServer- the MCP server that will stop
-
didStopMcpServer
default void didStopMcpServer(@NonNull McpServer mcpServer, @NonNull ShutdownComponentResult shutdownComponentResult) Called after the MCP server stops. Also called for a configured server that never started, for example after a startup failure, so a precedingdidStartMcpServer(McpServer)call is not guaranteed. This lifecycle-transition callback is observational; exceptions are contained.- Parameters:
mcpServer- the MCP server that stoppedshutdownComponentResult- lifecycle component shutdown result
-
didStartMcpRequestHandling
Called when handling begins for an admitted semantic MCP request or notification.This callback runs after request admission and before request or tool rate limiting, handler queue admission, framework response generation, application interception, typed-input validation, or handler entry. Framework-owned discovery and static catalog operations also invoke this callback. Soklet may invoke this callback concurrently for independent MCP requests. Implementations must be safe for the server's configured request concurrency, and the corresponding finish callback is not guaranteed to run on the same thread. Exceptions are contained and do not alter the wire result. The built-in MCP transport invokes this callback on its protocol pool, shared with admission, rate limiting, CORS authorization and request-state opening. Configure that pool separately through
McpServer.Builder.protocolExecutorConcurrency(Integer)andMcpServer.Builder.protocolExecutorQueueCapacity(Integer)(defaults 32 workers and 128 queued jobs). Handler-executor settings do not resize it. Keep this callback bounded and nonblocking.- Parameters:
requestContext- immutable admitted-request context
-
didFinishMcpRequestHandling
default void didFinishMcpRequestHandling(@NonNull McpRequestContext requestContext, @NonNull McpRequestOutcome requestOutcome, @Nullable McpJsonRpcError jsonRpcError, @NonNull Duration requestDuration, @NonNull List<@NonNull Throwable> throwables) Called exactly once when an admitted semantic MCP request or notification reaches its client-visible terminal outcome.This is a request-finish callback, not a handler-exit callback: application code that does not cooperate with cancelation may continue after this method runs. The supplied context is the same instance passed to
didStartMcpRequestHandling(McpRequestContext). Soklet may invoke this callback concurrently for independent MCP requests, and it is not guaranteed to run on the same thread as the corresponding start callback. Implementations must be safe for the server's configured request concurrency. Exceptions are contained and do not alter the wire result. The built-in MCP transport delivers this callback and associated trace/failure logs through separately bounded daemon platform workers, away from connection event loops and the protocol/handler executors. It reserves delivery capacity before start observation. When that capacity is unavailable, both callbacks and their semantic request metrics are omitted; request processing continues and a fixed diagnostic reports omissions at most once per minute. Each reserved finish follows the corresponding start callback. A blocked observer retains physical shutdown work, so keep it bounded and do not wait for the same Soklet lifecycle to stop from inside this callback.- Parameters:
requestContext- immutable admitted-request contextrequestOutcome- fixed client-visible terminal outcomejsonRpcError- exact client-visible JSON-RPC error, ornullwhen the terminal outcome has no JSON-RPC errorrequestDuration- total admitted-request durationthrowables- immutable failures observed while handling the request
-
willEstablishSseConnection
default void willEstablishSseConnection(@NonNull Request request, @Nullable ResourceMethod resourceMethod) Called before an SSE connection is established. -
didEstablishSseConnection
Called after an SSE connection is established.If client initialization fails after the accepted response has been written, the built-in SSE server invokes this callback immediately before the paired termination callbacks. Such a connection never becomes available to a broadcaster. The termination retains its elected reason and cause.
-
didFailToEstablishSseConnection
default void didFailToEstablishSseConnection(@NonNull Request request, @Nullable ResourceMethod resourceMethod, @NonNull SseConnection.HandshakeFailureReason connectionHandshakeFailureReason, @Nullable Throwable throwable) Called if an SSE connection fails to establish before an accepted response has been written.Capacity rejection is
SseConnection.HandshakeFailureReason.CAPACITY_EXCEEDED; request processing, response preparation and accepted-handshake response writing failures useSseConnection.HandshakeFailureReason.INTERNAL_ERRORwith their cause. A routine peer disconnect while writing a rejection retains its rejection reason and records the write cause.SseConnection.HandshakeFailureReason.HANDSHAKE_REJECTEDalso covers finite route/method mismatch responses on the SSE listener, including HEAD and OPTIONS; an event-source method need not have run. Failure during client initialization after acceptance uses the stream-termination callbacks.- Parameters:
connectionHandshakeFailureReason- the handshake failure reasonthrowable- an optional underlying cause, ornullif not applicable
-
willTerminateSseConnection
default void willTerminateSseConnection(@NonNull SseConnection sseConnection, @NonNull StreamTermination streamTermination) Called before an SSE connection is terminated. -
didTerminateSseConnection
default void didTerminateSseConnection(@NonNull SseConnection sseConnection, @NonNull StreamTermination streamTermination) Called after an SSE connection is terminated. -
willWriteSseEvent
Called before an SSE event is written. -
didWriteSseEvent
default void didWriteSseEvent(@NonNull SseConnection sseConnection, @NonNull SseEvent sseEvent, @NonNull Duration writeDuration) Called after an SSE event is written. -
didFailToWriteSseEvent
default void didFailToWriteSseEvent(@NonNull SseConnection sseConnection, @NonNull SseEvent sseEvent, @NonNull Duration writeDuration, @NonNull Throwable throwable) Called after an SSE event fails to write. -
willWriteSseComment
default void willWriteSseComment(@NonNull SseConnection sseConnection, @NonNull SseComment sseComment) Called before an SSE comment is written. -
didWriteSseComment
default void didWriteSseComment(@NonNull SseConnection sseConnection, @NonNull SseComment sseComment, @NonNull Duration writeDuration) Called after an SSE comment is written. -
didFailToWriteSseComment
default void didFailToWriteSseComment(@NonNull SseConnection sseConnection, @NonNull SseComment sseComment, @NonNull Duration writeDuration, @NonNull Throwable throwable) Called after an SSE comment fails to write. -
didReceiveLogEvent
Called when Soklet emits a log event. The interface default is a no-op. Override this method to route events through application logging, or explicitly configuredefaultInstance()for stderr logging. Custom observers do not inherit an implicit stderr logger. Log delivery follows the emitting thread;LogEventType.MCP_TRACE_CORRELATIONand finish-observer failure events use the bounded MCP observation worker. Transport-failure and overload events can arrive on HTTP/SSE selector threads. Do not block those threads. The default stderr observer hands formatting and output to one daemon worker with a queue of 128 records, shared with failed-observer fallback logging. The worker retires after one idle second and restarts on demand. This timeout does not interrupt active formatting or output; a blocked sink can retain its worker and class loader until the write returns. It captures the current stderr destination and caps event messages at 4,096 UTF-16 characters without splitting surrogate pairs. Delivery is best effort: records are discarded when the queue is full or its worker cannot start, and pending records are not flushed by application shutdown or JVM exit. The record count is bounded; attached Throwable graphs are not byte-bounded. The worker prints routine executor shedding, request interruption and socket close/timeout conditions as single lines without rendering stacks; the line retains a sanitized failure message capped at 512 characters. Unexpected failures and nested diagnostics retain their stack diagnostics. Custom observers still receive the original event and Throwable. -
defaultInstance
Acquires a threadsafeLifecycleObserverinstance with sensible defaults. This instance queues log events for asynchronous, best-effort stderr delivery as described bydidReceiveLogEvent(LogEvent), with full attached Throwable stacks for unexpected failures and terse lines for routine interruption, socket close/timeout and known executor-shedding conditions.SokletConfigselects it when no lifecycle-observer configuration is supplied. Configuring custom observers replaces that default; include this instance explicitly to retain stderr logging.- Returns:
- a
LifecycleObserverwith default settings
-