-
Notifications
You must be signed in to change notification settings - Fork 213
fix: handle messages concurrently to prevent deadlock (issue #176) #764
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
MichielDean
wants to merge
6
commits into
modelcontextprotocol:main
Choose a base branch
from
MichielDean:fix/concurrent-message-handling
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
0740243
ko-5so7v: fix concurrent message handling to prevent deadlock in Prot…
a4a00d7
ko-5so7v: add KDoc for ProtocolOptions.dispatcher and document concur…
70d0f25
fix: address review feedback — opt-in concurrentMessageHandling, inli…
abddfb0
fix: address Copilot review — use TimeSource.Monotonic, remove unused…
990061c
fix: move ConcurrencyTest to jvmTest and fix @property KDoc tag
3f4c373
fix: make concurrency test deterministic and move to jvmTest
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
158 changes: 158 additions & 0 deletions
158
...test/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/integration/ConcurrencyTest.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,158 @@ | ||
| package io.modelcontextprotocol.kotlin.sdk.integration | ||
|
|
||
| import io.modelcontextprotocol.kotlin.sdk.client.Client | ||
| import io.modelcontextprotocol.kotlin.sdk.client.ClientOptions | ||
| import io.modelcontextprotocol.kotlin.sdk.server.Server | ||
| import io.modelcontextprotocol.kotlin.sdk.server.ServerOptions | ||
| import io.modelcontextprotocol.kotlin.sdk.server.ServerSession | ||
| import io.modelcontextprotocol.kotlin.sdk.shared.AbstractTransport | ||
| import io.modelcontextprotocol.kotlin.sdk.shared.TransportSendOptions | ||
| import io.modelcontextprotocol.kotlin.sdk.types.CallToolResult | ||
| import io.modelcontextprotocol.kotlin.sdk.types.Implementation | ||
| import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCMessage | ||
| import io.modelcontextprotocol.kotlin.sdk.types.ServerCapabilities | ||
| import io.modelcontextprotocol.kotlin.sdk.types.TextContent | ||
| import kotlinx.coroutines.CompletableDeferred | ||
| import kotlinx.coroutines.CoroutineScope | ||
| import kotlinx.coroutines.Dispatchers | ||
| import kotlinx.coroutines.SupervisorJob | ||
| import kotlinx.coroutines.cancel | ||
| import kotlinx.coroutines.channels.Channel | ||
| import kotlinx.coroutines.joinAll | ||
| import kotlinx.coroutines.launch | ||
| import kotlinx.coroutines.runBlocking | ||
| import kotlinx.coroutines.withTimeout | ||
| import kotlin.concurrent.atomics.ExperimentalAtomicApi | ||
| import kotlin.test.Test | ||
| import kotlin.test.assertNotNull | ||
| import kotlin.test.assertTrue | ||
| import kotlin.time.Duration.Companion.seconds | ||
|
|
||
| /** | ||
| * Tests that the Protocol layer handles incoming messages concurrently, | ||
| * preventing deadlock when a request handler needs to wait for other messages. | ||
| * | ||
| * See: https://github.com/modelcontextprotocol/kotlin-sdk/issues/176 | ||
| */ | ||
| class ConcurrencyTest { | ||
|
|
||
| /** | ||
| * A channel-based transport that delivers messages asynchronously via Kotlin Channels, | ||
| * simulating real network transports. This is necessary to reproduce the concurrency | ||
| * bug — the synchronous InMemoryTransport masks the issue. | ||
| */ | ||
| @OptIn(ExperimentalAtomicApi::class) | ||
| private class ChannelTransport( | ||
| private val scope: CoroutineScope, | ||
| private val sendChannel: Channel<JSONRPCMessage>, | ||
| private val receiveChannel: Channel<JSONRPCMessage>, | ||
| ) : AbstractTransport() { | ||
| override suspend fun start() { | ||
| scope.launch { | ||
| for (message in receiveChannel) { | ||
| _onMessage.invoke(message) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| override suspend fun send(message: JSONRPCMessage, options: TransportSendOptions?) { | ||
| sendChannel.send(message) | ||
| } | ||
|
|
||
| override suspend fun close() { | ||
| sendChannel.close() | ||
| receiveChannel.cancel() | ||
| invokeOnCloseCallback() | ||
| } | ||
|
|
||
| companion object { | ||
| fun createLinkedPair(scope: CoroutineScope): Pair<ChannelTransport, ChannelTransport> { | ||
| val clientToServer = Channel<JSONRPCMessage>(Channel.UNLIMITED) | ||
| val serverToClient = Channel<JSONRPCMessage>(Channel.UNLIMITED) | ||
| return Pair( | ||
| ChannelTransport(scope, serverToClient, clientToServer), | ||
| ChannelTransport(scope, clientToServer, serverToClient), | ||
| ) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Verifies that concurrent tool calls are handled concurrently, not serially. | ||
| * | ||
| * Uses deterministic synchronization: the fast tool completes while the slow | ||
| * handler is still suspended, proving that handlers run concurrently rather | ||
| * than serially. No wall-clock timing thresholds are used. | ||
| */ | ||
| @OptIn(ExperimentalAtomicApi::class) | ||
| @Test | ||
| fun `server handles concurrent requests concurrently`() = runBlocking { | ||
| val serverOptions = ServerOptions( | ||
| capabilities = ServerCapabilities(tools = ServerCapabilities.Tools(null)), | ||
| ) | ||
| serverOptions.concurrentMessageHandling = true | ||
|
|
||
| val server = Server( | ||
| serverInfo = Implementation("test-server", "1.0"), | ||
| options = serverOptions, | ||
| ) | ||
|
|
||
| // Latch that blocks the slow handler until we signal it to finish. | ||
| // This lets us prove the fast handler completed while the slow one | ||
| // was still running — impossible under serial dispatch. | ||
| val slowHandlerCanFinish = CompletableDeferred<Unit>() | ||
|
|
||
| server.addTool("slow_tool", "A tool that blocks until signaled") { | ||
| slowHandlerCanFinish.await() | ||
| CallToolResult(content = listOf(TextContent("slow_tool_done"))) | ||
| } | ||
|
|
||
| server.addTool("fast_tool", "A tool that completes immediately") { | ||
| CallToolResult(content = listOf(TextContent("fast_tool_done"))) | ||
| } | ||
|
|
||
| val client = Client( | ||
| clientInfo = Implementation("test-client", "1.0"), | ||
| options = ClientOptions(), | ||
| ) | ||
|
|
||
| val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) | ||
| val (clientTransport, serverTransport) = ChannelTransport.createLinkedPair(scope) | ||
| val serverSessionResult = CompletableDeferred<ServerSession>() | ||
|
|
||
| try { | ||
| listOf( | ||
| launch { client.connect(clientTransport) }, | ||
| launch { serverSessionResult.complete(server.createSession(serverTransport)) }, | ||
| ).joinAll() | ||
|
|
||
| // Start the slow request (handler blocks on slowHandlerCanFinish) | ||
| val slowResult = CompletableDeferred<CallToolResult>() | ||
| launch { | ||
| slowResult.complete(client.callTool("slow_tool", mapOf())) | ||
| } | ||
|
|
||
| // Start the fast request | ||
| val fastResult = CompletableDeferred<CallToolResult>() | ||
| launch { | ||
| fastResult.complete(client.callTool("fast_tool", mapOf())) | ||
| } | ||
|
|
||
| // The fast request must complete while the slow handler is still suspended. | ||
| // Under serial dispatch, both requests would be blocked behind the slow handler, | ||
| // so the fast result could never arrive. | ||
| val fast = withTimeout(5.seconds) { fastResult.await() } | ||
| assertNotNull(fast) | ||
|
|
||
| // Now release the slow handler and verify it completes | ||
| slowHandlerCanFinish.complete(Unit) | ||
| val slow = withTimeout(5.seconds) { slowResult.await() } | ||
| assertNotNull(slow) | ||
| Unit | ||
| } finally { | ||
| clientTransport.close() | ||
| serverTransport.close() | ||
| scope.cancel() | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.