fix(client): close stdio read sources during shutdown (#798)

## Summary

Fixes `StdioClientTransport.close()` so shutdown does not hang when the
stdin read loop is blocked waiting for input.

## Root Cause / Context

`StdioClientTransport.closeResources()` stopped the transport coroutine
scope and then waited for the scope job to finish. On the JVM, a
`Source.readAtMostTo()` call backed by a blocking Java stream does not
necessarily return when the coroutine is cancelled. If the read loop
stayed blocked, `close()` could wait indefinitely.

## Changes

- Close the stdin source during stdio client shutdown before waiting for
transport coroutines to finish.
- Also close the optional stderr source during shutdown.
- Keep source-close failures non-fatal and log them at debug level.
- Add a JVM regression test with a `RawSource` that blocks in
`readAtMostTo()` until `close()` is called.
- Assert the close path completes, emits `onClose`, and does not invoke
`onError`.

## Scope / Risk

This is limited to `StdioClientTransport` shutdown behavior. It does not
change the public API or server transports. The regression coverage is
JVM-focused because the reported hang is caused by a blocking Java
stream read.

## Verification

```bash
./gradlew :integration-test:jvmTest --tests 'io.modelcontextprotocol.kotlin.sdk.client.StdioClientTransportTest'
./gradlew :kotlin-sdk-client:jvmTest
./gradlew :kotlin-sdk-client:ktlintCheck :integration-test:ktlintCheck :kotlin-sdk-client:detekt :integration-test:detekt :kotlin-sdk-client:apiCheck
```

Closes #514
This commit is contained in:
King Star 2026-06-30 15:46:43 +08:00 • committed by GitHub
commit 0221b8db3d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -244,10 +244,20 @@ public class StdioClientTransport @JvmOverloads public constructor(
override suspend fun closeResources() {
withContext(NonCancellable) {
scope.stopProcessing("Closed")
closeReadSources()
scope.coroutineContext[Job]?.join() // Wait for all coroutines to complete
}
}
private fun closeReadSources() {
runCatching { input.close() }
.onFailure { logger.debug(it) { "Error closing stdin source" } }
error?.let { source ->
runCatching { source.close() }
.onFailure { logger.debug(it) { "Error closing stderr source" } }
}
}
private fun sendOutboundMessage(message: JSONRPCMessage, sink: Sink, mainScope: CoroutineScope) {
try {
val json = serializeMessage(message)