refactor: Harden detekt setup, address some issues (#507)

# Detekt setup hardeing; address some issues

- Address some detekt findings: missing KDocs, formatting, use `check*`
& `orEmpty()``
- Remove unnecessary KDoc comments from deprecated classes in `types.kt`
- Add Detekt baseline XML files for all modules
- Enforce stricter Detekt rules by setting `failOnSeverity` from `None`
to `Error`

## Motivation and Context

Detekt is not actually failing the build on violations. This PR is
enabling Detekt to fail on errors. Baseline fines added for historical
issues. Follow-up for #501

## How Has This Been Tested?
Regressions

## Breaking Changes

No breaking changes.

## Types of changes
<!-- What types of changes does your code introduce? Put an `x` in all
the boxes that apply: -->
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] Refactoring
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update

## Checklist
<!-- Go over all the following points, and put an `x` in all the boxes
that apply. -->
- [x] I have read the [MCP
Documentation](https://modelcontextprotocol.io)
- [x] My code follows the repository's style guidelines
- [x] New and existing tests pass locally
- [ ] I have added appropriate error handling
- [ ] I have added or updated documentation as needed
This commit is contained in:
Konstantin Pavlov 2026-02-13 22:17:27 +02:00 • committed by GitHub
commit ed9ad83290
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 478 additions and 122 deletions

View file

@ -0,0 +1,21 @@
<?xml version='1.0' encoding='UTF-8'?>
<SmellBaseline>
<ManuallySuppressedIssues/>
<CurrentIssues>
<ID>MagicNumber:StdioServerTransport.kt:StdioServerTransport$8192</ID>
<ID>MaxLineLength:SSEServerTransport.kt:SseServerTransport$"SSEServerTransport already started! If using Server class, note that connect() calls start() automatically."</ID>
<ID>MaxLineLength:SSEServerTransport.kt:SseServerTransport$*</ID>
<ID>MaxLineLength:ServerSession.kt:ServerSession$"Client requested unsupported protocol version $requestedVersion, falling back to $LATEST_PROTOCOL_VERSION"</ID>
<ID>MaxLineLength:ServerSession.kt:ServerSession$"Creating message with ${params.params.messages.size} messages, maxTokens=${params.params.maxTokens}, temperature=${params.params.temperature}, systemPrompt=${if (params.params.systemPrompt != null) "present" else "absent"}"</ID>
<ID>ReturnCount:KtorServer.kt:private suspend fun existingStreamableTransport: StreamableHttpServerTransport?</ID>
<ID>ThrowsCount:ServerSession.kt:ServerSession$override fun assertCapabilityForMethod</ID>
<ID>ThrowsCount:ServerSession.kt:ServerSession$override fun assertNotificationCapability</ID>
<ID>ThrowsCount:ServerSession.kt:ServerSession$override fun assertRequestHandlerCapability</ID>
<ID>TooGenericExceptionCaught:SSEServerTransport.kt:SseServerTransport$e: Exception</ID>
<ID>TooGenericExceptionCaught:Server.kt:Server$e: Exception</ID>
<ID>TooGenericExceptionCaught:StdioServerTransport.kt:StdioServerTransport$e: Throwable</ID>
<ID>TooManyFunctions:KtorServer.kt:io.modelcontextprotocol.kotlin.sdk.server.KtorServer.kt</ID>
<ID>TooManyFunctions:Server.kt:Server</ID>
<ID>TooManyFunctions:ServerSession.kt:ServerSession : Protocol</ID>
</CurrentIssues>
</SmellBaseline>

View file

@ -0,0 +1,51 @@
<?xml version='1.0' encoding='UTF-8'?>
<SmellBaseline>
<ManuallySuppressedIssues/>
<CurrentIssues>
<ID>InjectDispatcher:FeatureNotificationService.kt:FeatureNotificationService$Default</ID>
<ID>LongParameterList:KtorServer.kt:private suspend fun RoutingContext.streamableTransport: StreamableHttpServerTransport?</ID>
<ID>LongParameterList:Server.kt:Server$public fun addTool</ID>
<ID>MagicNumber:StdioServerTransport.kt:StdioServerTransport$8192</ID>
<ID>MaxLineLength:SSEServerTransport.kt:SseServerTransport$"SSEServerTransport already started! If using Server class, note that connect() calls start() automatically."</ID>
<ID>MaxLineLength:SSEServerTransport.kt:SseServerTransport$*</ID>
<ID>MaxLineLength:ServerSession.kt:ServerSession$"Client requested unsupported protocol version $requestedVersion, falling back to $LATEST_PROTOCOL_VERSION"</ID>
<ID>MaxLineLength:ServerSession.kt:ServerSession$"Creating message with ${params.params.messages.size} messages, maxTokens=${params.params.maxTokens}, temperature=${params.params.temperature}, systemPrompt=${if (params.params.systemPrompt != null) "present" else "absent"}"</ID>
<ID>NoNameShadowing:FeatureNotificationService.kt:FeatureNotificationService${ it.remove(job) }</ID>
<ID>RedundantSuspendModifier:ServerSession.kt:ServerSession$suspend</ID>
<ID>ReturnCount:KtorServer.kt:private suspend fun existingStreamableTransport: StreamableHttpServerTransport?</ID>
<ID>ThrowsCount:ServerSession.kt:ServerSession$override fun assertCapabilityForMethod</ID>
<ID>ThrowsCount:ServerSession.kt:ServerSession$override fun assertNotificationCapability</ID>
<ID>ThrowsCount:ServerSession.kt:ServerSession$override fun assertRequestHandlerCapability</ID>
<ID>TooGenericExceptionCaught:SSEServerTransport.kt:SseServerTransport$e: Exception</ID>
<ID>TooGenericExceptionCaught:Server.kt:Server$e: Exception</ID>
<ID>TooGenericExceptionCaught:StdioServerTransport.kt:StdioServerTransport$e: Throwable</ID>
<ID>TooManyFunctions:KtorServer.kt:io.modelcontextprotocol.kotlin.sdk.server.KtorServer.kt</ID>
<ID>TooManyFunctions:Server.kt:Server</ID>
<ID>TooManyFunctions:ServerSession.kt:ServerSession : Protocol</ID>
<ID>UnsafeCallOnNullableType:StreamableHttpServerTransport.kt:StreamableHttpServerTransport$responseRequestId!!</ID>
<ID>UseCheckNotNull:Server.kt:Server$check(options.capabilities.prompts != null) { logger.error { "Failed to add prompt '${prompt.name}': Server does not support prompts capability" } "Server does not support prompts capability." }</ID>
<ID>UseCheckNotNull:Server.kt:Server$check(options.capabilities.prompts != null) { logger.error { "Failed to add prompts: Server does not support prompts capability" } "Server does not support prompts capability." }</ID>
<ID>UseCheckNotNull:Server.kt:Server$check(options.capabilities.prompts != null) { logger.error { "Failed to remove prompt '$name': Server does not support prompts capability" } "Server does not support prompts capability." }</ID>
<ID>UseCheckNotNull:Server.kt:Server$check(options.capabilities.prompts != null) { logger.error { "Failed to remove prompts: Server does not support prompts capability" } "Server does not support prompts capability." }</ID>
<ID>UseCheckNotNull:Server.kt:Server$check(options.capabilities.resources != null) { logger.error { "Failed to add resource '$name': Server does not support resources capability" } "Server does not support resources capability." }</ID>
<ID>UseCheckNotNull:Server.kt:Server$check(options.capabilities.resources != null) { logger.error { "Failed to add resources: Server does not support resources capability" } "Server does not support resources capability." }</ID>
<ID>UseCheckNotNull:Server.kt:Server$check(options.capabilities.resources != null) { logger.error { "Failed to remove resource '$uri': Server does not support resources capability" } "Server does not support resources capability." }</ID>
<ID>UseCheckNotNull:Server.kt:Server$check(options.capabilities.resources != null) { logger.error { "Failed to remove resources: Server does not support resources capability" } "Server does not support resources capability." }</ID>
<ID>UseCheckNotNull:Server.kt:Server$check(options.capabilities.tools != null) { logger.error { "Failed to add tool '${tool.name}': Server does not support tools capability" } "Server does not support tools capability. Enable it in ServerOptions." }</ID>
<ID>UseCheckNotNull:Server.kt:Server$check(options.capabilities.tools != null) { logger.error { "Failed to add tools: Server does not support tools capability" } "Server does not support tools capability." }</ID>
<ID>UseCheckNotNull:Server.kt:Server$check(options.capabilities.tools != null) { logger.error { "Failed to remove tool '$name': Server does not support tools capability" } "Server does not support tools capability." }</ID>
<ID>UseCheckNotNull:Server.kt:Server$check(options.capabilities.tools != null) { logger.error { "Failed to remove tools: Server does not support tools capability" } "Server does not support tools capability." }</ID>
<ID>UseCheckOrError:ServerSession.kt:ServerSession$throw IllegalStateException( "Server does not support notifying about resources (required for ${method.value})", )</ID>
<ID>UseCheckOrError:ServerSession.kt:ServerSession$throw IllegalStateException( "Server does not support notifying of prompt list changes (required for ${method.value})", )</ID>
<ID>UseCheckOrError:ServerSession.kt:ServerSession$throw IllegalStateException( "Server does not support notifying of tool list changes (required for ${method.value})", )</ID>
<ID>UseCheckOrError:ServerSession.kt:ServerSession$throw IllegalStateException("Client does not support elicitation (required for ${method.value})")</ID>
<ID>UseCheckOrError:ServerSession.kt:ServerSession$throw IllegalStateException("Client does not support listing roots (required for ${method.value})")</ID>
<ID>UseCheckOrError:ServerSession.kt:ServerSession$throw IllegalStateException("Client does not support sampling (required for ${method.value})")</ID>
<ID>UseCheckOrError:ServerSession.kt:ServerSession$throw IllegalStateException("Server does not support logging (required for $method)")</ID>
<ID>UseCheckOrError:ServerSession.kt:ServerSession$throw IllegalStateException("Server does not support logging (required for ${method.value})")</ID>
<ID>UseCheckOrError:ServerSession.kt:ServerSession$throw IllegalStateException("Server does not support prompts (required for $method)")</ID>
<ID>UseCheckOrError:ServerSession.kt:ServerSession$throw IllegalStateException("Server does not support resources (required for $method)")</ID>
<ID>UseCheckOrError:ServerSession.kt:ServerSession$throw IllegalStateException("Server does not support sampling (required for $method)")</ID>
<ID>UseCheckOrError:ServerSession.kt:ServerSession$throw IllegalStateException("Server does not support tools (required for $method)")</ID>
</CurrentIssues>
</SmellBaseline>

View file

@ -46,6 +46,12 @@ internal class TransportManager(transports: Map<String, AbstractTransport> = emp
}
}
/**
* Registers a server-sent events (SSE) route at the specified path.
*
* @param path the URL path to register the route for SSE.
* @param block the block of code that defines the server's behavior for the SSE session.
*/
@KtorDsl
public fun Routing.mcp(path: String, block: ServerSSESession.() -> Server) {
route(path) {
@ -53,7 +59,7 @@ public fun Routing.mcp(path: String, block: ServerSSESession.() -> Server) {
}
}
/*
/**
* Configures the Ktor Application to handle Model Context Protocol (MCP) over Server-Sent Events (SSE).
*/
@KtorDsl

View file

@ -25,6 +25,7 @@ import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCResponse
import io.modelcontextprotocol.kotlin.sdk.types.McpJson
import io.modelcontextprotocol.kotlin.sdk.types.Method
import io.modelcontextprotocol.kotlin.sdk.types.RPCError
import io.modelcontextprotocol.kotlin.sdk.types.RPCError.ErrorCode.REQUEST_TIMEOUT
import io.modelcontextprotocol.kotlin.sdk.types.RequestId
import io.modelcontextprotocol.kotlin.sdk.types.SUPPORTED_PROTOCOL_VERSIONS
import kotlinx.coroutines.job
@ -66,20 +67,23 @@ private data class SessionContext(val session: ServerSSESession?, val call: Appl
* - No session validation is performed
*
* @param enableJsonResponse If true, the server will return JSON responses instead of starting an SSE stream.
* This can be useful for simple request/response scenarios without streaming.
* Default is false (SSE streams are preferred).
* @param enableDnsRebindingProtection Enable DNS rebinding protection (requires allowedHosts and/or allowedOrigins to be configured).
* Default is false for backwards compatibility.
* This can be useful for simple request/response scenarios without streaming.
* Default is false (SSE streams are preferred).
* @param enableDnsRebindingProtection Enable DNS rebinding protection
* (requires allowedHosts and/or allowedOrigins to be configured).
* Default is false for backwards compatibility.
* @param allowedHosts List of allowed host header values for DNS rebinding protection.
* If not specified, host validation is disabled.
* If not specified, host validation is disabled.
* @param allowedOrigins List of allowed origin header values for DNS rebinding protection.
* If not specified, origin validation is disabled.
* If not specified, origin validation is disabled.
* @param eventStore Event store for resumability support
* If provided, resumability will be enabled, allowing clients to reconnect and resume messages
* @param retryIntervalMillis Retry interval (in milliseconds) advertised via SSE priming events to hint the client when to reconnect.
* Applies only when an [eventStore] is configured. Defaults to `null` (no retry hint).
* If provided, resumability will be enabled, allowing clients to reconnect and resume messages
* @param retryIntervalMillis Retry interval (in milliseconds) advertised via SSE priming events
* to hint the client when to reconnect. Applies only when an [eventStore] is configured.
* Defaults to `null` (no retry hint).
*/
@OptIn(ExperimentalUuidApi::class, ExperimentalAtomicApi::class)
@Suppress("TooManyFunctions")
public class StreamableHttpServerTransport(
private val enableJsonResponse: Boolean = false,
private val enableDnsRebindingProtection: Boolean = false,
@ -145,10 +149,12 @@ public class StreamableHttpServerTransport(
override suspend fun start() {
check(started.compareAndSet(expectedValue = false, newValue = true)) {
"StreamableHttpServerTransport already started! If using Server class, note that connect() calls start() automatically."
"StreamableHttpServerTransport already started! If using Server class, " +
"note that connect() calls start() automatically."
}
}
@Suppress("CyclomaticComplexMethod", "ReturnCount")
override suspend fun send(message: JSONRPCMessage, options: TransportSendOptions?) {
val responseRequestId: RequestId? = when (message) {
is JSONRPCResponse -> message.id
@ -252,6 +258,7 @@ public class StreamableHttpServerTransport(
/**
* Handles POST requests containing JSON-RPC messages
*/
@Suppress("CyclomaticComplexMethod", "LongMethod", "ReturnCount", "TooGenericExceptionCaught")
public suspend fun handlePostRequest(session: ServerSSESession?, call: ApplicationCall) {
try {
if (!enableJsonResponse && session == null) {
@ -344,6 +351,7 @@ public class StreamableHttpServerTransport(
}
}
@Suppress("ReturnCount")
public suspend fun handleGetRequest(session: ServerSSESession?, call: ApplicationCall) {
if (enableJsonResponse) {
call.reject(
@ -403,6 +411,7 @@ public class StreamableHttpServerTransport(
* Closes the SSE stream associated with the given [requestId], prompting the client to reconnect.
* Useful for implementing polling behavior for long-running operations.
*/
@Suppress("ReturnCount", "TooGenericExceptionCaught")
public suspend fun closeSseStream(requestId: RequestId) {
if (enableJsonResponse) return
val streamId = requestToStreamMapping[requestId] ?: return
@ -417,6 +426,7 @@ public class StreamableHttpServerTransport(
}
}
@Suppress("TooGenericExceptionCaught")
private suspend fun replayEvents(store: EventStore, lastEventId: String, session: ServerSSESession) {
val call: ApplicationCall = session.call
@ -479,6 +489,7 @@ public class StreamableHttpServerTransport(
}
}
@Suppress("ReturnCount")
private suspend fun validateSession(call: ApplicationCall): Boolean {
if (sessionIdGenerator == null) return true
@ -519,7 +530,7 @@ public class StreamableHttpServerTransport(
else -> {
call.reject(
HttpStatusCode.NotFound,
-32001,
REQUEST_TIMEOUT,
"Session not found",
)
false
@ -549,6 +560,7 @@ public class StreamableHttpServerTransport(
}
}
@Suppress("ReturnCount")
private fun validateHeaders(call: ApplicationCall): String? {
if (!enableDnsRebindingProtection) return null
@ -573,6 +585,7 @@ public class StreamableHttpServerTransport(
return null
}
@Suppress("TooGenericExceptionCaught")
private suspend fun flushSse(session: ServerSSESession?) {
try {
session?.send(data = "")
@ -581,6 +594,7 @@ public class StreamableHttpServerTransport(
}
}
@Suppress("ReturnCount", "MagicNumber")
private suspend fun parseBody(call: ApplicationCall): List<JSONRPCMessage>? {
val contentLength = call.request.header(HttpHeaders.ContentLength)?.toIntOrNull() ?: 0
if (contentLength > MAXIMUM_MESSAGE_SIZE) {
@ -630,6 +644,7 @@ public class StreamableHttpServerTransport(
}
}
@Suppress("TooGenericExceptionCaught")
private suspend fun maybeSendPrimingEvent(streamId: String, session: ServerSSESession?) {
val store = eventStore ?: return
val sseSession = session ?: return

View file

@ -1,3 +1,5 @@
@file:Suppress("TooManyFunctions")
package io.modelcontextprotocol.kotlin.sdk.server
import io.github.oshai.kotlinlogging.KotlinLogging