From 7d2e993b96595c8c7ab3d4e2729d066fe4df4927 Mon Sep 17 00:00:00 2001 From: Adithya Kamath Date: Wed, 12 Mar 2025 15:18:21 +0530 Subject: [PATCH] Remove the double bang operator and replace it with a null check instead. (#49) 2. add try catch in the block for transport send in acatch block Co-authored-by: Leonid Stashevsky --- .../kotlin/sdk/shared/Protocol.kt | 32 +++++++++++-------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/shared/Protocol.kt b/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/shared/Protocol.kt index 7088953..d9808ff 100644 --- a/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/shared/Protocol.kt +++ b/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/shared/Protocol.kt @@ -209,7 +209,7 @@ public abstract class Protocol( if (handler === null) { LOGGER.trace { "No handler found for request: ${request.method}" } try { - transport!!.send( + transport?.send( JSONRPCResponse( id = request.id, error = JSONRPCError( @@ -229,24 +229,30 @@ public abstract class Protocol( val result = handler(request, RequestHandlerExtra()) LOGGER.trace { "Request handled successfully: ${request.method} (id: ${request.id})" } - val response = JSONRPCResponse( - id = request.id, - result = result + transport?.send( + JSONRPCResponse( + id = request.id, + result = result + ) ) - transport!!.send(response) } catch (cause: Throwable) { LOGGER.error(cause) { "Error handling request: ${request.method} (id: ${request.id})" } - transport!!.send( - JSONRPCResponse( - id = request.id, - error = JSONRPCError( - ErrorCode.Defined.InternalError, - message = cause.message ?: "Internal error", + try { + transport?.send( + JSONRPCResponse( + id = request.id, + error = JSONRPCError( + code = ErrorCode.Defined.InternalError, + message = cause.message ?: "Internal error" + ) ) ) - ) + } catch (sendError: Throwable) { + LOGGER.error(sendError) { "Failed to send error response for request: ${request.method} (id: ${request.id})" } + // Optionally implement fallback behavior here + } } } @@ -385,7 +391,7 @@ public abstract class Protocol( try { withTimeout(timeout) { LOGGER.trace { "Sending request message with id: $messageId" } - this@Protocol.transport!!.send(message) + this@Protocol.transport?.send(message) } return result.await() } catch (cause: TimeoutCancellationException) {