Handle additional error types in client initialization handling (#404)

May throw the following exceptions: `CancellationException`,
`McpException`, `StreamableHttpError`, and `SerializationException`

## Motivation and Context
This makes it possible to handle errors directly without needing to
inspect the cause. For example:
```kotlin
try {
    client.connect(transport)
} catch (e: StreamableHttpError) {
    // ...
}
```

## How Has This Been Tested?
locally

## 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)
- [ ] 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
- [ ] I have added or updated documentation as needed
This commit is contained in:
Pavel Gorgulov 2025-11-20 19:09:23 +01:00 • committed by GitHub
commit 0f9209ad4a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -34,6 +34,7 @@ import io.modelcontextprotocol.kotlin.sdk.types.ListRootsResult
import io.modelcontextprotocol.kotlin.sdk.types.ListToolsRequest
import io.modelcontextprotocol.kotlin.sdk.types.ListToolsResult
import io.modelcontextprotocol.kotlin.sdk.types.LoggingLevel
import io.modelcontextprotocol.kotlin.sdk.types.McpException
import io.modelcontextprotocol.kotlin.sdk.types.Method
import io.modelcontextprotocol.kotlin.sdk.types.PingRequest
import io.modelcontextprotocol.kotlin.sdk.types.ReadResourceRequest
@ -54,6 +55,7 @@ import kotlinx.atomicfu.update
import kotlinx.collections.immutable.minus
import kotlinx.collections.immutable.persistentMapOf
import kotlinx.collections.immutable.toPersistentSet
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.JsonObject
import kotlin.coroutines.cancellation.CancellationException
@ -196,11 +198,15 @@ public open class Client(private val clientInfo: Implementation, options: Client
logger.error(error) { "Failed to initialize client: ${error.message}" }
close()
if (error !is CancellationException) {
throw IllegalStateException("Error connecting to transport: ${error.message}", error)
}
when (error) {
is CancellationException,
is McpException,
is StreamableHttpError,
is SerializationException,
-> throw error
throw error
else -> throw IllegalStateException("Error connecting to transport: ${error.message}", error)
}
}
}