Add options in Transport.send method (#408)

Add support for `TransportSendOptions` in `Transport.send` method

## Motivation and Context
This change extends the `Transport.send` method signature to support
advanced transport features like resumption tokens and progress
callbacks. This is needed to enable:
- Long-running request resumption after reconnection
- Request-response association tracking
- Progress token handling in transport layer

needed for #235 

## How Has This Been Tested?
All transport tests passed

## Breaking Changes
Yes, it’s necessary to update the custom Transport implementations.
For users who rely on the transports provided by the sdk, there’s no
breaking change

## Types of changes
- [x] Bug fix (non-breaking change which fixes an issue)
- [x] 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
- [x] I have added or updated documentation as needed
This commit is contained in:
Pavel Gorgulov 2025-11-20 20:17:15 +01:00 • committed by GitHub
commit 2b9dfd9466
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 186 additions and 63 deletions

View file

@ -93,22 +93,58 @@ public val DEFAULT_REQUEST_TIMEOUT: Duration = 60.seconds
/**
* Options that can be given per request.
*
* @property relatedRequestId if present,
* `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with.
* @property resumptionToken the resumption token used to continue long-running requests that were interrupted.
* This allows clients to reconnect and continue from where they left off, if supported by the transport.
* @property onResumptionToken a callback that is invoked when the resumption token changes, if supported by the transport.
* This allows clients to persist the latest token for potential reconnection.
* @property onProgress callback for progress notifications.
* If set, requests progress notifications from the remote end (if supported).
* When progress notifications are received, this callback will be invoked.
* @property timeout a timeout for this request.
* If exceeded, a McpException with code `RequestTimeout` will be raised from request().
* If not specified, `DEFAULT_REQUEST_TIMEOUT` will be used as the timeout.
*/
public data class RequestOptions(
/**
* If set, requests progress notifications from the remote end (if supported).
* When progress notifications are received, this callback will be invoked.
*/
val onProgress: ProgressCallback? = null,
public class RequestOptions(
relatedRequestId: RequestId? = null,
resumptionToken: String? = null,
onResumptionToken: ((String) -> Unit)? = null,
public val onProgress: ProgressCallback? = null,
public val timeout: Duration = DEFAULT_REQUEST_TIMEOUT,
) : TransportSendOptions(relatedRequestId, resumptionToken, onResumptionToken) {
public operator fun component4(): ProgressCallback? = onProgress
public operator fun component5(): Duration = timeout
/**
* A timeout for this request. If exceeded, an McpError with code `RequestTimeout`
* will be raised from request().
*
* If not specified, `DEFAULT_REQUEST_TIMEOUT` will be used as the timeout.
*/
val timeout: Duration = DEFAULT_REQUEST_TIMEOUT,
)
public fun copy(
relatedRequestId: RequestId? = this.relatedRequestId,
resumptionToken: String? = this.resumptionToken,
onResumptionToken: ((String) -> Unit)? = this.onResumptionToken,
onProgress: ProgressCallback? = this.onProgress,
timeout: Duration = this.timeout,
): RequestOptions = RequestOptions(relatedRequestId, resumptionToken, onResumptionToken, onProgress, timeout)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
if (!super.equals(other)) return false
other as RequestOptions
return onProgress == other.onProgress && timeout == other.timeout
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + (onProgress?.hashCode() ?: 0)
result = 31 * result + timeout.hashCode()
return result
}
override fun toString(): String =
"RequestOptions(relatedRequestId=$relatedRequestId, resumptionToken=$resumptionToken, onResumptionToken=$onResumptionToken, onProgress=$onProgress, timeout=$timeout)"
}
/**
* Extra data given to request handlers.
@ -456,11 +492,9 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio
),
)
val serialized = JSONRPCNotification(
notification.method.value,
params = McpJson.encodeToJsonElement(notification),
)
transport.send(serialized)
val jsonRpcNotification = notification.toJSON()
transport.send(jsonRpcNotification, options)
result.completeExceptionally(reason)
}
@ -469,7 +503,7 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio
try {
withTimeout(timeout) {
logger.trace { "Sending request message with id: $jsonRpcRequestId" }
this@Protocol.transport?.send(jsonRpcRequest)
this@Protocol.transport?.send(jsonRpcRequest, options)
}
return result.await()
} catch (cause: TimeoutCancellationException) {
@ -489,13 +523,14 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio
/**
* Emits a notification, which is a one-way message that does not expect a response.
*/
public suspend fun notification(notification: Notification) {
public suspend fun notification(notification: Notification, relatedRequestId: RequestId? = null) {
logger.trace { "Sending notification: ${notification.method}" }
val transport = this.transport ?: error("Not connected")
assertNotificationCapability(notification.method)
val sendOptions = relatedRequestId?.let { TransportSendOptions(relatedRequestId = it) }
val jsonRpcNotification = notification.toJSON()
val message = notification.toJSON()
transport.send(message)
transport.send(jsonRpcNotification, sendOptions)
}
/**

View file

@ -18,8 +18,12 @@ public interface Transport {
/**
* Sends a JSON-RPC message (request or response).
*
* @property message The JSON-RPC message to send, either a request or a response.
* @property options Optional transport-specific options that control sending behavior.
* Different transport implementations may support different options.
*/
public suspend fun send(message: JSONRPCMessage)
public suspend fun send(message: JSONRPCMessage, options: TransportSendOptions? = null)
/**
* Closes the connection.

View file

@ -0,0 +1,50 @@
package io.modelcontextprotocol.kotlin.sdk.shared
import io.modelcontextprotocol.kotlin.sdk.types.RequestId
/**
* Options for sending a JSON-RPC message through transport.
*
* @property relatedRequestId if present,
* `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with.
* @property resumptionToken the resumption token used to continue long-running requests that were interrupted.
* This allows clients to reconnect and continue from where they left off, if supported by the transport.
* @property onResumptionToken a callback that is invoked when the resumption token changes, if supported by the transport.
* This allows clients to persist the latest token for potential reconnection.
*/
public open class TransportSendOptions(
public val relatedRequestId: RequestId? = null,
public val resumptionToken: String? = null,
public val onResumptionToken: ((String) -> Unit)? = null,
) {
public operator fun component1(): RequestId? = relatedRequestId
public operator fun component2(): String? = resumptionToken
public operator fun component3(): ((String) -> Unit)? = onResumptionToken
public open fun copy(
relatedRequestId: RequestId? = this.relatedRequestId,
resumptionToken: String? = this.resumptionToken,
onResumptionToken: ((String) -> Unit)? = this.onResumptionToken,
): TransportSendOptions = TransportSendOptions(relatedRequestId, resumptionToken, onResumptionToken)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as TransportSendOptions
return relatedRequestId == other.relatedRequestId &&
resumptionToken == other.resumptionToken &&
onResumptionToken == other.onResumptionToken
}
override fun hashCode(): Int {
var result = relatedRequestId?.hashCode() ?: 0
result = 31 * result + (resumptionToken?.hashCode() ?: 0)
result = 31 * result + (onResumptionToken?.hashCode() ?: 0)
return result
}
override fun toString(): String =
"TransportSendOptions(relatedRequestId=$relatedRequestId, resumptionToken=$resumptionToken, onResumptionToken=$onResumptionToken)"
}

View file

@ -90,7 +90,7 @@ public abstract class WebSocketMcpTransport : AbstractTransport() {
}
}
override suspend fun send(message: JSONRPCMessage) {
override suspend fun send(message: JSONRPCMessage, options: TransportSendOptions?) {
logger.debug { "Sending message" }
if (!initialized.load()) {
error("Not connected")

View file

@ -166,7 +166,7 @@ private class RecordingTransport : Transport {
override suspend fun start() {}
override suspend fun send(message: JSONRPCMessage) {
override suspend fun send(message: JSONRPCMessage, options: TransportSendOptions?) {
sentMessages.send(message)
}