refactor: explicit locked detekt config (#729)

Migrate detekt to a convention plugin in `buildSrc`, switch the project
to a fully explicit YAML config (`buildUponDefaultConfig = false`), fix
the real findings that this stricter setup revealed, and remove
`@Suppress` annotations that became unnecessary after the rule changes.

## Motivation and Context
- Explicit visibility into the rule set
- Lock against detekt version upgrades

## Breaking Changes
None

## Types of changes
- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update

## Checklist
- [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
- [x] I have added appropriate error handling
- [x] I have added or updated documentation as needed
This commit is contained in:
Pavel Gorgulov 2026-04-29 12:31:49 +02:00 • committed by GitHub
commit 64804a05c2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 1106 additions and 507 deletions

View file

@ -4,6 +4,7 @@ import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
plugins {
id("mcp.multiplatform")
id("mcp.detekt")
id("mcp.publishing")
id("mcp.dokka")
alias(libs.plugins.kotlinx.binary.compatibility.validator)

View file

@ -1,14 +0,0 @@
<?xml version='1.0' encoding='UTF-8'?>
<SmellBaseline>
<ManuallySuppressedIssues/>
<CurrentIssues>
<ID>CyclomaticComplexMethod:StdioClientTransport.kt:StdioClientTransport$override suspend fun initialize</ID>
<ID>LongMethod:StdioClientTransport.kt:StdioClientTransport$override suspend fun initialize</ID>
<ID>MaxLineLength:StdioClientTransport.kt:StdioClientTransport$*</ID>
<ID>ThrowsCount:SseClientTransport.kt:SseClientTransport$private suspend fun CoroutineScope.collectMessages</ID>
<ID>ThrowsCount:StreamableHttpClientTransport.kt:StreamableHttpClientTransport$@Suppress("ReturnCount", "CyclomaticComplexMethod") override suspend fun performSend</ID>
<ID>TooGenericExceptionCaught:Client.kt:Client$error: Throwable</ID>
<ID>TooGenericExceptionCaught:SseClientTransport.kt:SseClientTransport$e: Throwable</ID>
<ID>TooGenericExceptionCaught:StdioClientTransport.kt:StdioClientTransport$e: Throwable</ID>
</CurrentIssues>
</SmellBaseline>

View file

@ -1,8 +0,0 @@
<?xml version='1.0' encoding='UTF-8'?>
<SmellBaseline>
<ManuallySuppressedIssues/>
<CurrentIssues>
<ID>MaxLineLength:StreamableHttpClientTransportTest.kt:StreamableHttpClientTransportTest$"""data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"upload-123","progress":50,"total":100}}"""</ID>
<ID>MaxLineLength:StreamableHttpClientTransportTest.kt:StreamableHttpClientTransportTest$"""data: {"jsonrpc":"2.0","method":"notifications/resumed","params":{"fromToken":"$lastEventIdSent"}}"""</ID>
</CurrentIssues>
</SmellBaseline>

View file

@ -2,18 +2,6 @@
<SmellBaseline>
<ManuallySuppressedIssues/>
<CurrentIssues>
<ID>CyclomaticComplexMethod:StdioClientTransport.kt:StdioClientTransport$override suspend fun initialize</ID>
<ID>InjectDispatcher:StdioClientTransport.kt:StdioClientTransport$Default</ID>
<ID>InjectDispatcher:StreamableHttpClientTransport.kt:StreamableHttpClientTransport$Default</ID>
<ID>LongMethod:StdioClientTransport.kt:StdioClientTransport$override suspend fun initialize</ID>
<ID>MaxLineLength:StdioClientTransport.kt:StdioClientTransport$*</ID>
<ID>NoNameShadowing:StdioClientTransport.kt:StdioClientTransport$source</ID>
<ID>ThrowsCount:SseClientTransport.kt:SseClientTransport$private suspend fun CoroutineScope.collectMessages</ID>
<ID>ThrowsCount:StreamableHttpClientTransport.kt:StreamableHttpClientTransport$@Suppress("ReturnCount", "CyclomaticComplexMethod") override suspend fun performSend</ID>
<ID>TooGenericExceptionCaught:Client.kt:Client$error: Throwable</ID>
<ID>TooGenericExceptionCaught:SseClientTransport.kt:SseClientTransport$e: Throwable</ID>
<ID>TooGenericExceptionCaught:StdioClientTransport.kt:StdioClientTransport$e: Throwable</ID>
<ID>UseCheckOrError:Client.kt:Client$throw IllegalStateException( "Server does not support resource subscriptions (required for $method)", )</ID>
<ID>UseCheckOrError:Client.kt:Client$throw IllegalStateException("Client does not support roots capability.")</ID>
<ID>LoopWithTooManyJumpStatements:StreamableHttpClientTransport.kt:StreamableHttpClientTransport$while</ID>
</CurrentIssues>
</SmellBaseline>

View file

@ -1,14 +0,0 @@
<?xml version='1.0' encoding='UTF-8'?>
<SmellBaseline>
<ManuallySuppressedIssues/>
<CurrentIssues>
<ID>AbstractClassCanBeConcreteClass:AbstractStreamableHttpClientTest.kt:AbstractStreamableHttpClientTest$AbstractStreamableHttpClientTest</ID>
<ID>ForbiddenComment:StreamableHttpClientTest.kt:StreamableHttpClientTest$// TODO: how to get notifications via Client API?</ID>
<ID>LongParameterList:MockMcp.kt:MockMcp$fun handleJSONRPCRequest</ID>
<ID>LongParameterList:MockMcp.kt:MockMcp$fun handleWithResult</ID>
<ID>LongParameterList:MockMcp.kt:MockMcp$fun onInitialize</ID>
<ID>MaxLineLength:StreamableHttpClientTransportTest.kt:StreamableHttpClientTransportTest$"""data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"upload-123","progress":50,"total":100}}"""</ID>
<ID>MaxLineLength:StreamableHttpClientTransportTest.kt:StreamableHttpClientTransportTest$"""data: {"jsonrpc":"2.0","method":"notifications/resumed","params":{"fromToken":"$lastEventIdSent"}}"""</ID>
<ID>UseOrEmpty:ClientMetaParameterTest.kt:ClientMetaParameterTest$exception.message ?: ""</ID>
</CurrentIssues>
</SmellBaseline>

View file

@ -83,7 +83,7 @@ private val logger = KotlinLogging.logger {}
* Options for configuring the MCP client.
*
* @property capabilities The capabilities this client supports.
* @property enforceStrictCapabilities Whether to strictly enforce capabilities when interacting with the server.
* @param enforceStrictCapabilities Whether to strictly enforce capabilities when interacting with the server.
*/
public class ClientOptions(
public val capabilities: ClientCapabilities = ClientCapabilities(),
@ -125,7 +125,6 @@ public suspend fun mcpClient(
* @param clientInfo Information about the client implementation (name, version).
* @param options Configuration options for this client.
*/
@Suppress("TooManyFunctions")
public open class Client(private val clientInfo: Implementation, options: ClientOptions = ClientOptions()) :
Protocol(options) {
@ -242,7 +241,7 @@ public open class Client(private val clientInfo: Implementation, options: Client
Method.Defined.CompletionComplete,
-> {
checkNotNull(serverCapabilities?.prompts) {
throw IllegalStateException("Server does not support prompts (required for $method)")
"Server does not support prompts (required for $method)"
}
}
@ -255,10 +254,10 @@ public open class Client(private val clientInfo: Implementation, options: Client
val resCaps = serverCapabilities?.resources
?: error("Server does not support resources (required for $method)")
if (method == Method.Defined.ResourcesSubscribe && resCaps.subscribe != true) {
throw IllegalStateException(
"Server does not support resource subscriptions (required for $method)",
)
if (method == Method.Defined.ResourcesSubscribe) {
check(resCaps.subscribe == true) {
"Server does not support resource subscriptions (required for $method)"
}
}
}
@ -556,9 +555,8 @@ public open class Client(private val clientInfo: Implementation, options: Client
* @throws IllegalStateException If the client does not support roots.
*/
public fun removeRoot(uri: String): Boolean {
if (capabilities.roots == null) {
logger.error { "Failed to remove root '$uri': Client does not support roots capability" }
throw IllegalStateException("Client does not support roots capability.")
checkNotNull(capabilities.roots) {
"Client does not support roots capability."
}
logger.info { "Removing root: $uri" }
val oldMap = roots.getAndUpdate { current -> current.remove(uri) }
@ -636,7 +634,6 @@ public open class Client(private val clientInfo: Implementation, options: Client
// --- Internal Handlers ---
@Suppress("ReturnCount")
private fun applyElicitationDefaults(request: ElicitRequest, result: ElicitResult): ElicitResult {
if (result.action != ElicitResult.Action.Accept) return result
val formParams = request.params as? ElicitRequestFormParams ?: return result

View file

@ -227,7 +227,6 @@ public class StdioClientTransport @JvmOverloads public constructor(
}
override suspend fun performSend(message: JSONRPCMessage, options: TransportSendOptions?) {
@Suppress("SwallowedException")
try {
sendChannel.send(message)
} catch (e: CancellationException) {
@ -290,7 +289,7 @@ public class StdioClientTransport @JvmOverloads public constructor(
) {
val buffer = Buffer()
try {
source.use { source ->
source.use {
while (isActive) {
val bytesRead = source.readAtMostTo(buffer, BUFFER_SIZE)
if (bytesRead == -1L) {

View file

@ -54,6 +54,7 @@ private const val MCP_RESUMPTION_TOKEN_HEADER = "Last-Event-ID"
* Represents an error from the Streamable HTTP transport.
*
* @property code HTTP status code associated with the error, or `null` if unavailable
* @param message detailed error description appended to the exception message
*/
public class StreamableHttpError(public val code: Int? = null, message: String? = null) :
Exception("Streamable HTTP error: $message")
@ -65,14 +66,17 @@ private sealed interface ConnectResult {
}
/**
* Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.
* It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events
* for receiving messages.
* Client transport implementing the MCP Streamable HTTP transport specification.
*
* @property sessionId session identifier assigned by the server after initialization, or `null` before connection
* @property protocolVersion MCP protocol version negotiated with the server, or `null` before connection
* Sends messages via HTTP POST and receives messages via HTTP GET with Server-Sent Events.
* Supports automatic SSE reconnection with exponential backoff, stream resumption via the
* `Last-Event-ID` header, and explicit session termination.
*
* @param client Ktor HTTP client used for all requests
* @param url MCP endpoint URL
* @param reconnectionOptions reconnection backoff and retry-limit settings for the SSE stream
* @param requestBuilder builder applied to every outgoing HTTP request, e.g. for adding auth headers
*/
@Suppress("TooManyFunctions")
public class StreamableHttpClientTransport(
private val client: HttpClient,
private val url: String,
@ -98,8 +102,11 @@ public class StreamableHttpClientTransport(
override val logger: KLogger = KotlinLogging.logger {}
/** Session identifier assigned by the server after initialization, or `null` before connection. */
public var sessionId: String? = null
private set
/** MCP protocol version negotiated with the server, or `null` before connection. */
public var protocolVersion: String? = null
private var sseJob: Job? = null
@ -121,7 +128,6 @@ public class StreamableHttpClientTransport(
/**
* Sends a single message with optional resumption support
*/
@Suppress("ReturnCount", "CyclomaticComplexMethod", "LongMethod", "TooGenericExceptionCaught", "ThrowsCount")
override suspend fun performSend(message: JSONRPCMessage, options: TransportSendOptions?) {
logger.debug { "Client sending message via POST to $url: ${McpJson.encodeToString(message)}" }
@ -260,7 +266,6 @@ public class StreamableHttpClientTransport(
var attempt = 0
var needsDelay = initialServerRetryDelay != null
@Suppress("LoopWithTooManyJumpStatements")
while (isActive) {
// Delay before (re)connection: skip only for first fresh SSE connection
if (needsDelay) {
@ -296,7 +301,6 @@ public class StreamableHttpClientTransport(
}
}
@Suppress("TooGenericExceptionCaught")
private suspend fun connectSse(lastEventId: String?): ConnectResult {
logger.debug { "Client attempting to start SSE session at url: $url" }
return try {
@ -363,7 +367,6 @@ public class StreamableHttpClientTransport(
}
}
@Suppress("TooGenericExceptionCaught")
private suspend fun collectSse(
session: ClientSSESession,
replayMessageId: RequestId?,
@ -408,7 +411,6 @@ public class StreamableHttpClientTransport(
return SseStreamResult(hasPrimingEvent, receivedResponse, localLastEventId, localServerRetryDelay)
}
@Suppress("CyclomaticComplexMethod")
private suspend fun handleInlineSse(
response: HttpResponse,
replayMessageId: RequestId?,
@ -455,7 +457,6 @@ public class StreamableHttpClientTransport(
}
}
@Suppress("LoopWithTooManyJumpStatements")
while (!channel.isClosedForRead) {
val line = channel.readUTF8Line() ?: break
if (line.isEmpty()) {

View file

@ -834,7 +834,6 @@ class StreamableHttpClientTransportTest {
transport.close()
}
@Suppress("DEPRECATION")
@Test
fun testDeprecatedConstructorStillWorks() = runTest {
val mockEngine = MockEngine { _ ->

View file

@ -39,7 +39,6 @@ internal class MockMcp(verbose: Boolean = false) : AutoCloseable {
val url = "${mokksy.baseUrl()}/mcp"
@Suppress("LongParameterList")
fun onInitialize(
clientName: String? = null,
sessionId: String,
@ -117,7 +116,6 @@ internal class MockMcp(verbose: Boolean = false) : AutoCloseable {
}
}
@Suppress("LongParameterList")
fun handleWithResult(
httpMethod: HttpMethod = HttpMethod.Post,
jsonRpcMethod: String,
@ -153,7 +151,6 @@ internal class MockMcp(verbose: Boolean = false) : AutoCloseable {
}
}
@Suppress("LongParameterList")
fun handleWithResult(
httpMethod: HttpMethod = HttpMethod.Post,
jsonRpcMethod: String,
@ -178,7 +175,6 @@ internal class MockMcp(verbose: Boolean = false) : AutoCloseable {
)
}
@Suppress("LongParameterList")
fun handleJSONRPCRequest(
httpMethod: HttpMethod = HttpMethod.Post,
jsonRpcMethod: String,

View file

@ -118,16 +118,16 @@ internal class StreamableHttpClientTest : AbstractStreamableHttpClientTest() {
ServerSentEvent(
event = "message",
id = "1",
data = @Suppress("MaxLineLength")
//language=json
data =
"""{"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"upload-123","progress":50,"total":100}}""",
),
)
delay(200.milliseconds)
emit(
ServerSentEvent(
data = @Suppress("MaxLineLength")
//language=json
data =
"""{"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"upload-123","progress":50,"total":100}}""",
),
)