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
12 changed files with 1106 additions and 507 deletions

View file

@ -33,7 +33,6 @@ private val logger = KotlinLogging.logger {}
* communication through notifications, requests, and other operations.
* This interface defines various methods to facilitate the interaction.
*/
@Suppress("TooManyFunctions")
public interface ClientConnection {
/**
@ -176,7 +175,6 @@ public interface ClientConnection {
public suspend fun sendElicitationComplete(notification: ElicitationCompleteNotification)
}
@Suppress("TooManyFunctions")
internal class ClientConnectionImpl(private val session: ServerSession) : ClientConnection {
override val sessionId: String get() = session.sessionId

View file

@ -64,6 +64,7 @@ public data class RegisteredResource(
* A registered resource template with its associated read handler.
*
* @property resourceTemplate The [ResourceTemplate] definition (RFC 6570 URI template).
* @property matcher Pre-built matcher used to test incoming URIs against [resourceTemplate].
* @property readHandler A suspend function invoked when a client reads a URI that matches
* this template. The second parameter contains the URI variables extracted from the match.
*/

View file

@ -38,6 +38,7 @@ private sealed class NotificationEvent(open val timestamp: Long)
/**
* Represents an event for a notification.
*
* @property timestamp Timestamp at which this event was created.
* @property notification The notification associated with the event.
*/
private class SendEvent(override val timestamp: Long, val notification: Notification) : NotificationEvent(timestamp)
@ -340,7 +341,7 @@ internal class FeatureNotificationService(
emitJobs.getAndUpdate { it.add(job) }
// Register completion
job.invokeOnCompletion {
job.invokeOnCompletion { _ ->
emitJobs.getAndUpdate { it.remove(job) }
}

View file

@ -1,5 +1,3 @@
@file:Suppress("TooManyFunctions")
package io.modelcontextprotocol.kotlin.sdk.server
import io.github.oshai.kotlinlogging.KotlinLogging
@ -172,7 +170,6 @@ private fun Application.mcpStreamableHttp(
* that creates and returns the [Server] to handle the connection.
*/
@KtorDsl
@Suppress("LongParameterList")
public fun Application.mcpStreamableHttp(
path: String = "/mcp",
enableDnsRebindingProtection: Boolean = false,
@ -247,7 +244,6 @@ private fun Application.mcpStatelessStreamableHttp(
* that creates and returns the [Server] to handle the connection.
*/
@KtorDsl
@Suppress("LongParameterList")
public fun Application.mcpStatelessStreamableHttp(
path: String = "/mcp",
enableDnsRebindingProtection: Boolean = false,

View file

@ -27,13 +27,15 @@ internal const val SESSION_ID_PARAM = "sessionId"
*
* Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL identified by `_endpoint`.
*
* @property sessionId unique identifier for this transport session, generated randomly on creation
* @param endpoint relative or absolute URL the client will POST messages to
* @param session active SSE session used to deliver server-to-client events
*/
@OptIn(ExperimentalAtomicApi::class)
public class SseServerTransport(private val endpoint: String, private val session: ServerSSESession) :
AbstractTransport() {
private val initialized: AtomicBoolean = AtomicBoolean(false)
/** Unique identifier for this transport session, generated randomly on creation. */
@OptIn(ExperimentalUuidApi::class)
public val sessionId: String = Uuid.random().toString()

View file

@ -64,7 +64,8 @@ private val logger = KotlinLogging.logger {}
* Configuration options for the MCP server.
*
* @property capabilities The capabilities this server supports.
* @property enforceStrictCapabilities Whether to strictly enforce capabilities when interacting with clients.
* @param enforceStrictCapabilities Whether to strictly enforce capabilities when interacting with clients.
* Forwarded to [ProtocolOptions.enforceStrictCapabilities].
* @property resourceTemplateMatcherFactory The factory used to create [ResourceTemplateMatcher] instances
* for matching resource URIs against registered templates. Defaults to [PathSegmentTemplateMatcher.factory].
*/
@ -92,13 +93,12 @@ public class ServerOptions(
* Currently, after subscription to a resource, the server will NOT send the subscription confirmation
* as this response schema is not defined in the protocol.
*
* @param serverInfo Information about this server implementation (name, version).
* @param options Configuration options for the server.
* @param instructionsProvider Optional provider for instructions from the server to the client about how to use
* @property serverInfo Information about this server implementation (name, version).
* @property options Configuration options for the server.
* @property instructionsProvider Optional provider for instructions from the server to the client about how to use
* this server. The provider is called each time a new session is started to support dynamic instructions.
* @param block A block to configure the mcp server.
*/
@Suppress("TooManyFunctions")
public open class Server(
protected val serverInfo: Implementation,
protected val options: ServerOptions,
@ -312,9 +312,9 @@ public open class Server(
* Registers a single tool. The client can then call this tool.
*
* @param name The name of the tool.
* @param title An optional human-readable name of the tool for display purposes.
* @param description A human-readable description of what the tool does.
* @param inputSchema The expected input schema for the tool.
* @param title An optional human-readable name of the tool for display purposes.
* @param outputSchema The optional expected output schema for the tool.
* @param toolAnnotations Optional additional tool information.
* @param execution Optional execution-related properties, such as task-augmented execution support.
@ -322,7 +322,6 @@ public open class Server(
* @param handler A suspend function that handles executing the tool when called by the client.
* @throws IllegalStateException If the server does not support tools.
*/
@Suppress("LongParameterList")
public fun addTool(
name: String,
description: String,
@ -645,7 +644,6 @@ public open class Server(
}
// Execute the tool handler and catch any errors
@Suppress("TooGenericExceptionCaught")
return try {
logger.trace { "Executing tool ${requestParams.name} with input: ${requestParams.arguments}" }
tool.run {

View file

@ -39,17 +39,28 @@ import kotlin.uuid.Uuid
private val logger = KotlinLogging.logger {}
/**
* Represents a server session.
* Represents an active server-side session in the Model Context Protocol.
*
* @property sessionId unique identifier for this session, generated randomly on creation
* Owns the server side of a single client connection on top of [Protocol]. Drives the
* initialize/initialized handshake, tracks the negotiated client capabilities and version,
* asserts capability requirements before dispatching requests and notifications, and exposes
* server-to-client operations such as sampling, root listing, elicitation, logging, and
* list-change notifications.
*
* Equality and hashing are based on [sessionId], so a session can be used as a key in
* routing structures.
*
* @property serverInfo server name and version reported to the client during initialization
* @param options server capabilities and protocol options used by [Protocol]
* @property instructions optional human-readable instructions for the client, sent in the initialize result
*/
@Suppress("TooManyFunctions")
public open class ServerSession(
protected val serverInfo: Implementation,
options: ServerOptions,
protected val instructions: String?,
) : Protocol(options) {
/** Unique identifier for this session, generated on creation. */
@OptIn(ExperimentalUuidApi::class)
public val sessionId: String = Uuid.random().toString()
@ -60,14 +71,10 @@ public open class ServerSession(
private val _clientCapabilities: AtomicRef<ClientCapabilities?> = atomic(null)
private val _clientVersion: AtomicRef<Implementation?> = atomic(null)
/**
* The client's reported capabilities after initialization.
*/
/** Capabilities reported by the client during initialization, or `null` before the handshake completes. */
public val clientCapabilities: ClientCapabilities? get() = _clientCapabilities.value
/**
* The client's version information after initialization.
*/
/** Client implementation information reported during initialization, or `null` before the handshake completes. */
public val clientVersion: Implementation? get() = _clientVersion.value
/**

View file

@ -72,7 +72,6 @@ public class StdioServerTransport(private val inputStream: Source, outputStream:
private fun launchReadingJob(): Job {
val job = scope.launch {
val buf = Buffer()
@Suppress("TooGenericExceptionCaught")
try {
while (isActive) {
val bytesRead = inputStream.readAtMostTo(buf, READ_BUFFER_SIZE)
@ -103,7 +102,6 @@ public class StdioServerTransport(private val inputStream: Source, outputStream:
private fun launchProcessingJob(): Job {
val job = scope.launch {
@Suppress("TooGenericExceptionCaught")
try {
for (chunk in readChannel) {
readBuffer.append(chunk)
@ -123,7 +121,6 @@ public class StdioServerTransport(private val inputStream: Source, outputStream:
private fun launchSendingJob(): Job {
val job = scope.launch {
@Suppress("TooGenericExceptionCaught")
try {
for (message in writeChannel) {
val json = serializeMessage(message)
@ -147,7 +144,6 @@ public class StdioServerTransport(private val inputStream: Source, outputStream:
}
private suspend fun processReadBuffer() {
@Suppress("TooGenericExceptionCaught")
while (true) {
val message = try {
readBuffer.readMessage()

View file

@ -74,10 +74,8 @@ private data class SessionContext(val session: ServerSSESession?, val call: Appl
* - No session validation is performed
*
* @param configuration Transport configuration. See [Configuration] for available options.
* @property sessionId session identifier assigned after initialization, or `null` in stateless mode
*/
@OptIn(ExperimentalUuidApi::class, ExperimentalAtomicApi::class)
@Suppress("TooManyFunctions")
public class StreamableHttpServerTransport(private val configuration: Configuration) : AbstractTransport() {
@Deprecated("Use default constructor with explicit Configuration()")
@ -100,7 +98,6 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
* @param retryIntervalMillis Retry interval in milliseconds for event handling or reconnection attempts.
* Defaults to `null`.
*/
@Suppress("MaxLineLength")
@Deprecated(
"Use constructor with Configuration: StreamableHttpServerTransport(Configuration(enableJsonResponse = ...))",
replaceWith = ReplaceWith(
@ -153,6 +150,7 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
}
}
/** Session identifier assigned after initialization in stateful mode, or `null` in stateless mode. */
public var sessionId: String? = null
private set
@ -215,7 +213,6 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
}
}
@Suppress("CyclomaticComplexMethod", "ReturnCount")
override suspend fun send(message: JSONRPCMessage, options: TransportSendOptions?) {
val responseRequestId: RequestId? = when (message) {
is JSONRPCResponse -> message.id
@ -329,7 +326,6 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
/**
* Handles POST requests containing JSON-RPC messages
*/
@Suppress("CyclomaticComplexMethod", "LongMethod", "ReturnCount", "TooGenericExceptionCaught")
public suspend fun handlePostRequest(session: ServerSSESession?, call: ApplicationCall) {
try {
if (!configuration.enableJsonResponse && session == null) {
@ -438,7 +434,6 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
}
/** Handles an HTTP GET request by establishing a standalone SSE stream for server-initiated notifications. */
@Suppress("ReturnCount")
public suspend fun handleGetRequest(session: ServerSSESession?, call: ApplicationCall) {
// NOTE: enableJsonResponse only controls how POST responses are delivered (JSON vs. SSE).
// The standalone GET SSE stream is always supported — it is the only channel available
@ -512,7 +507,6 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
* 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 (configuration.enableJsonResponse) return
val streamId = requestToStreamMapping[requestId] ?: return
@ -529,7 +523,6 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
}
}
@Suppress("TooGenericExceptionCaught")
private suspend fun replayEvents(store: EventStore, lastEventId: String, session: ServerSSESession) {
val call: ApplicationCall = session.call
@ -596,7 +589,6 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
}
}
@Suppress("ReturnCount")
private suspend fun validateSession(call: ApplicationCall): Boolean {
if (sessionIdGenerator == null) return true
@ -655,7 +647,6 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
}
}
@Suppress("ReturnCount")
private fun validateHeaders(call: ApplicationCall): String? {
if (!configuration.enableDnsRebindingProtection) return null
@ -680,7 +671,6 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
return null
}
@Suppress("TooGenericExceptionCaught")
private suspend fun flushSse(session: ServerSSESession?) {
try {
session?.send(data = "")
@ -691,7 +681,6 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
}
}
@Suppress("ReturnCount")
private suspend fun parseBody(call: ApplicationCall): List<JSONRPCMessage>? {
val maxSize = configuration.maxRequestBodySize
val contentLength = call.request.header(HttpHeaders.ContentLength)?.toLongOrNull() ?: 0L
@ -752,7 +741,6 @@ public class StreamableHttpServerTransport(private val configuration: Configurat
}
}
@Suppress("TooGenericExceptionCaught")
private suspend fun maybeSendPrimingEvent(
streamId: String,
session: ServerSSESession?,

View file

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

View file

@ -14,7 +14,6 @@ import io.ktor.utils.io.readUTF8Line
import io.modelcontextprotocol.kotlin.sdk.types.Implementation
import io.modelcontextprotocol.kotlin.sdk.types.ServerCapabilities
@Suppress("AbstractClassCanBeConcreteClass")
abstract class AbstractKtorExtensionsTest {
protected val sseContentType = ContentType("text", "event-stream")

View file

@ -299,21 +299,18 @@ class StdioServerTransportTest {
server.close()
}
@Suppress("unused")
private fun inputErrors() = listOf(
IOException("simulated read failure"),
RuntimeException("unexpected read exception"),
OutOfMemoryError("unexpected read error"),
)
@Suppress("unused")
private fun outputErrors() = listOf(
IOException("simulated write failure"),
RuntimeException("unexpected write exception"),
OutOfMemoryError("unexpected write error"),
)
@Suppress("unused")
private fun handlerErrors() = listOf(
RuntimeException("handler failure"),
IOException("handler IO failure"),