New MCP Schema types (#386)

Implement the last version of the mcp schema and complete restructuring
of the mcp schema implementation from a monolithic `types.kt` file into
separate files.

- #158 
- #185 
- #353 
- #298 
- #248 

## Motivation and Context
The previous implementation of the mcp schema was outdated and contained
several issues. In addition, it stored all mcp types in a single large
file, which made maintenance and further development more difficult

## How Has This Been Tested?
All tests passed

## Breaking Changes
Yes. The new types are now located in a separate package. Additionally,
many types have new parameters and modified constructors

## Types of changes
- [x] Bug fix (non-breaking change which fixes an issue)
- [x] New feature (non-breaking change which adds functionality)
- [x] 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

## Additional context
to adopt the new structure:
**Before:**
```kotlin
  import io.modelcontextprotocol.kotlin.sdk.InitializeRequest
  import io.modelcontextprotocol.kotlin.sdk.Resource
```

**After:**
```kotlin
  import io.modelcontextprotocol.kotlin.sdk.types.InitializeRequest
  import io.modelcontextprotocol.kotlin.sdk.types.Resource
```
This commit is contained in:
Pavel Gorgulov 2025-11-11 12:25:23 +01:00 • committed by GitHub
commit 21393e7ce3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
49 changed files with 13048 additions and 4230 deletions

File diff suppressed because it is too large Load diff

View file

@ -1,24 +1,27 @@
package io.modelcontextprotocol.kotlin.sdk.shared
import io.github.oshai.kotlinlogging.KotlinLogging
import io.modelcontextprotocol.kotlin.sdk.CancelledNotification
import io.modelcontextprotocol.kotlin.sdk.EmptyRequestResult
import io.modelcontextprotocol.kotlin.sdk.ErrorCode
import io.modelcontextprotocol.kotlin.sdk.JSONRPCError
import io.modelcontextprotocol.kotlin.sdk.JSONRPCNotification
import io.modelcontextprotocol.kotlin.sdk.JSONRPCRequest
import io.modelcontextprotocol.kotlin.sdk.JSONRPCResponse
import io.modelcontextprotocol.kotlin.sdk.McpError
import io.modelcontextprotocol.kotlin.sdk.Method
import io.modelcontextprotocol.kotlin.sdk.Notification
import io.modelcontextprotocol.kotlin.sdk.PingRequest
import io.modelcontextprotocol.kotlin.sdk.Progress
import io.modelcontextprotocol.kotlin.sdk.ProgressNotification
import io.modelcontextprotocol.kotlin.sdk.Request
import io.modelcontextprotocol.kotlin.sdk.RequestId
import io.modelcontextprotocol.kotlin.sdk.RequestResult
import io.modelcontextprotocol.kotlin.sdk.fromJSON
import io.modelcontextprotocol.kotlin.sdk.toJSON
import io.modelcontextprotocol.kotlin.sdk.types.CancelledNotification
import io.modelcontextprotocol.kotlin.sdk.types.CancelledNotificationParams
import io.modelcontextprotocol.kotlin.sdk.types.EmptyResult
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCError
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCNotification
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCRequest
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCResponse
import io.modelcontextprotocol.kotlin.sdk.types.McpException
import io.modelcontextprotocol.kotlin.sdk.types.McpJson
import io.modelcontextprotocol.kotlin.sdk.types.Method
import io.modelcontextprotocol.kotlin.sdk.types.Notification
import io.modelcontextprotocol.kotlin.sdk.types.PingRequest
import io.modelcontextprotocol.kotlin.sdk.types.Progress
import io.modelcontextprotocol.kotlin.sdk.types.ProgressNotification
import io.modelcontextprotocol.kotlin.sdk.types.ProgressToken
import io.modelcontextprotocol.kotlin.sdk.types.RPCError
import io.modelcontextprotocol.kotlin.sdk.types.Request
import io.modelcontextprotocol.kotlin.sdk.types.RequestId
import io.modelcontextprotocol.kotlin.sdk.types.RequestResult
import io.modelcontextprotocol.kotlin.sdk.types.fromJSON
import io.modelcontextprotocol.kotlin.sdk.types.toJSON
import kotlinx.atomicfu.AtomicRef
import kotlinx.atomicfu.atomic
import kotlinx.atomicfu.getAndUpdate
@ -35,9 +38,6 @@ import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.encodeToJsonElement
import kotlinx.serialization.serializer
import kotlin.reflect.KType
import kotlin.reflect.typeOf
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
@ -51,6 +51,11 @@ public const val IMPLEMENTATION_NAME: String = "mcp-ktor"
public typealias ProgressCallback = (Progress) -> Unit
@OptIn(ExperimentalSerializationApi::class)
@Deprecated(
message = "Use McpJson instead",
replaceWith = ReplaceWith("McpJson", "io.modelcontextprotocol.kotlin.sdk.types.McpJson"),
level = DeprecationLevel.WARNING,
)
public val McpJson: Json by lazy {
Json {
ignoreUnknownKeys = true
@ -143,9 +148,9 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio
public val responseHandlers: Map<RequestId, (response: JSONRPCResponse?, error: Exception?) -> Unit>
get() = _responseHandlers.value
private val _progressHandlers: AtomicRef<PersistentMap<RequestId, ProgressCallback>> =
private val _progressHandlers: AtomicRef<PersistentMap<ProgressToken, ProgressCallback>> =
atomic(persistentMapOf())
public val progressHandlers: Map<RequestId, ProgressCallback>
public val progressHandlers: Map<ProgressToken, ProgressCallback>
get() = _progressHandlers.value
/**
@ -183,7 +188,7 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio
}
setRequestHandler<PingRequest>(Method.Defined.Ping) { _, _ ->
EmptyRequestResult()
EmptyResult()
}
}
@ -222,7 +227,7 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio
transport = null
onClose()
val error = McpError(ErrorCode.Defined.ConnectionClosed.code, "Connection closed")
val error = McpException(RPCError.ErrorCode.CONNECTION_CLOSED, "Connection closed")
for (handler in handlersToNotify) {
handler(null, error)
}
@ -254,10 +259,10 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio
logger.trace { "No handler found for request: ${request.method}" }
try {
transport?.send(
JSONRPCResponse(
JSONRPCError(
id = request.id,
error = JSONRPCError(
ErrorCode.Defined.MethodNotFound,
error = RPCError(
code = RPCError.ErrorCode.METHOD_NOT_FOUND,
message = "Server does not support ${request.method}",
),
),
@ -276,7 +281,7 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio
transport?.send(
JSONRPCResponse(
id = request.id,
result = result,
result = result ?: EmptyResult(),
),
)
} catch (cause: Throwable) {
@ -284,10 +289,10 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio
try {
transport?.send(
JSONRPCResponse(
JSONRPCError(
id = request.id,
error = JSONRPCError(
code = ErrorCode.Defined.InternalError,
error = RPCError(
code = RPCError.ErrorCode.INTERNAL_ERROR,
message = cause.message ?: "Internal error",
),
),
@ -324,7 +329,7 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio
}
private fun onResponse(response: JSONRPCResponse?, error: JSONRPCError?) {
val messageId = response?.id
val messageId = response?.id ?: error?.id
val oldResponseHandlers = _responseHandlers.getAndUpdate { current ->
if (messageId != null && messageId in current) {
@ -347,10 +352,10 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio
handler(response, null)
} else {
check(error != null)
val error = McpError(
error.code.code,
error.message,
error.data,
val error = McpException(
code = error.error.code,
message = error.error.message,
data = error.error.data,
)
handler(null, error)
}
@ -415,11 +420,6 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio
return@put
}
if (response?.error != null) {
result.completeExceptionally(IllegalStateException(response.error.toString()))
return@put
}
try {
@Suppress("UNCHECKED_CAST")
result.complete(response!!.result as T)
@ -434,7 +434,7 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio
_progressHandlers.update { current -> current.remove(messageId) }
val notification = CancelledNotification(
params = CancelledNotification.Params(
params = CancelledNotificationParams(
requestId = messageId,
reason = reason.message ?: "Unknown",
),
@ -459,10 +459,10 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio
} catch (cause: TimeoutCancellationException) {
logger.error { "Request timed out after ${timeout.inWholeMilliseconds}ms: ${request.method}" }
cancel(
McpError(
ErrorCode.Defined.RequestTimeout.code,
"Request timed out",
JsonObject(mutableMapOf("timeout" to JsonPrimitive(timeout.inWholeMilliseconds))),
McpException(
code = RPCError.ErrorCode.REQUEST_TIMEOUT,
message = "Request timed out",
data = JsonObject(mutableMapOf("timeout" to JsonPrimitive(timeout.inWholeMilliseconds))),
),
)
result.cancel(cause)
@ -491,28 +491,21 @@ public abstract class Protocol(@PublishedApi internal val options: ProtocolOptio
method: Method,
noinline block: suspend (T, RequestHandlerExtra) -> RequestResult?,
) {
setRequestHandler(typeOf<T>(), method, block)
setRequestHandlerInternal(method, block)
}
@PublishedApi
internal fun <T : Request> setRequestHandler(
requestType: KType,
@Suppress("UNCHECKED_CAST")
internal fun <T : Request> setRequestHandlerInternal(
method: Method,
block: suspend (T, RequestHandlerExtra) -> RequestResult?,
) {
assertRequestHandlerCapability(method)
val serializer = McpJson.serializersModule.serializer(requestType)
_requestHandlers.update { current ->
current.put(method.value) { request, extraHandler ->
val result = McpJson.decodeFromJsonElement(serializer, request.params)
val response = if (result != null) {
@Suppress("UNCHECKED_CAST")
block(result as T, extraHandler)
} else {
EmptyRequestResult()
}
current.put(method.value) { jSONRPCRequest, extraHandler ->
val request = jSONRPCRequest.fromJSON()
val response = block(request as T, extraHandler)
response
}
}

View file

@ -1,7 +1,8 @@
package io.modelcontextprotocol.kotlin.sdk.shared
import io.github.oshai.kotlinlogging.KotlinLogging
import io.modelcontextprotocol.kotlin.sdk.JSONRPCMessage
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCMessage
import io.modelcontextprotocol.kotlin.sdk.types.McpJson
import kotlinx.io.Buffer
import kotlinx.io.indexOf
import kotlinx.io.readString

View file

@ -1,6 +1,6 @@
package io.modelcontextprotocol.kotlin.sdk.shared
import io.modelcontextprotocol.kotlin.sdk.JSONRPCMessage
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCMessage
import kotlinx.coroutines.CompletableDeferred
/**

View file

@ -5,7 +5,8 @@ import io.ktor.websocket.Frame
import io.ktor.websocket.WebSocketSession
import io.ktor.websocket.close
import io.ktor.websocket.readText
import io.modelcontextprotocol.kotlin.sdk.JSONRPCMessage
import io.modelcontextprotocol.kotlin.sdk.types.JSONRPCMessage
import io.modelcontextprotocol.kotlin.sdk.types.McpJson
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.InternalCoroutinesApi
@ -58,7 +59,7 @@ public abstract class WebSocketMcpTransport : AbstractTransport() {
while (true) {
val message = try {
session.incoming.receive()
} catch (e: ClosedReceiveChannelException) {
} catch (_: ClosedReceiveChannelException) {
logger.debug { "Closed receive channel, exiting" }
return@launch
}

View file

@ -1,315 +1,40 @@
package io.modelcontextprotocol.kotlin.sdk
import io.github.oshai.kotlinlogging.KotlinLogging
import io.modelcontextprotocol.kotlin.sdk.LoggingMessageNotification.SetLevelRequest
import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.descriptors.buildClassSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonContentPolymorphicSerializer
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonEncoder
import io.modelcontextprotocol.kotlin.sdk.types.error
import io.modelcontextprotocol.kotlin.sdk.types.success
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.long
import kotlinx.serialization.json.longOrNull
private val logger = KotlinLogging.logger {}
internal object ErrorCodeSerializer : KSerializer<ErrorCode> {
override val descriptor: SerialDescriptor =
PrimitiveSerialDescriptor("io.modelcontextprotocol.kotlin.sdk.ErrorCode", PrimitiveKind.INT)
override fun serialize(encoder: Encoder, value: ErrorCode) {
encoder.encodeInt(value.code)
}
override fun deserialize(decoder: Decoder): ErrorCode {
val decodedInt = decoder.decodeInt()
return ErrorCode.Defined.entries.firstOrNull { it.code == decodedInt }
?: ErrorCode.Unknown(decodedInt)
}
}
internal object RequestMethodSerializer : KSerializer<Method> {
override val descriptor: SerialDescriptor =
PrimitiveSerialDescriptor("io.modelcontextprotocol.kotlin.sdk.Method", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: Method) {
encoder.encodeString(value.value)
}
override fun deserialize(decoder: Decoder): Method {
val decodedString = decoder.decodeString()
return Method.Defined.entries.firstOrNull { it.value == decodedString }
?: Method.Custom(decodedString)
}
}
internal object StopReasonSerializer : KSerializer<StopReason> {
override val descriptor: SerialDescriptor =
PrimitiveSerialDescriptor("io.modelcontextprotocol.kotlin.sdk.StopReason", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: StopReason) {
encoder.encodeString(value.value)
}
override fun deserialize(decoder: Decoder): StopReason {
val decodedString = decoder.decodeString()
return when (decodedString) {
StopReason.StopSequence.value -> StopReason.StopSequence
StopReason.MaxTokens.value -> StopReason.MaxTokens
StopReason.EndTurn.value -> StopReason.EndTurn
else -> StopReason.Other(decodedString)
}
}
}
internal object ReferencePolymorphicSerializer : JsonContentPolymorphicSerializer<Reference>(Reference::class) {
override fun selectDeserializer(element: JsonElement): DeserializationStrategy<Reference> =
when (element.jsonObject.getValue("type").jsonPrimitive.content) {
ResourceTemplateReference.TYPE -> ResourceTemplateReference.serializer()
PromptReference.TYPE -> PromptReference.serializer()
else -> UnknownReference.serializer()
}
}
internal object PromptMessageContentPolymorphicSerializer :
JsonContentPolymorphicSerializer<PromptMessageContent>(PromptMessageContent::class) {
override fun selectDeserializer(element: JsonElement): DeserializationStrategy<PromptMessageContent> =
when (element.jsonObject.getValue("type").jsonPrimitive.content) {
ImageContent.TYPE -> ImageContent.serializer()
TextContent.TYPE -> TextContent.serializer()
EmbeddedResource.TYPE -> EmbeddedResource.serializer()
AudioContent.TYPE -> AudioContent.serializer()
else -> UnknownContent.serializer()
}
}
internal object PromptMessageContentMultimodalPolymorphicSerializer :
JsonContentPolymorphicSerializer<PromptMessageContentMultimodal>(PromptMessageContentMultimodal::class) {
override fun selectDeserializer(element: JsonElement): DeserializationStrategy<PromptMessageContentMultimodal> =
when (element.jsonObject.getValue("type").jsonPrimitive.content) {
ImageContent.TYPE -> ImageContent.serializer()
TextContent.TYPE -> TextContent.serializer()
AudioContent.TYPE -> AudioContent.serializer()
else -> UnknownContent.serializer()
}
}
internal object ResourceContentsPolymorphicSerializer :
JsonContentPolymorphicSerializer<ResourceContents>(ResourceContents::class) {
override fun selectDeserializer(element: JsonElement): DeserializationStrategy<ResourceContents> {
val jsonObject = element.jsonObject
return when {
jsonObject.contains("text") -> TextResourceContents.serializer()
jsonObject.contains("blob") -> BlobResourceContents.serializer()
else -> UnknownResourceContents.serializer()
}
}
}
internal fun selectRequestDeserializer(method: String): DeserializationStrategy<Request> {
selectClientRequestDeserializer(method)?.let { return it }
selectServerRequestDeserializer(method)?.let { return it }
return CustomRequest.serializer()
}
internal fun selectClientRequestDeserializer(method: String): DeserializationStrategy<ClientRequest>? = when (method) {
Method.Defined.Ping.value -> PingRequest.serializer()
Method.Defined.Initialize.value -> InitializeRequest.serializer()
Method.Defined.CompletionComplete.value -> CompleteRequest.serializer()
Method.Defined.LoggingSetLevel.value -> SetLevelRequest.serializer()
Method.Defined.PromptsGet.value -> GetPromptRequest.serializer()
Method.Defined.PromptsList.value -> ListPromptsRequest.serializer()
Method.Defined.ResourcesList.value -> ListResourcesRequest.serializer()
Method.Defined.ResourcesTemplatesList.value -> ListResourceTemplatesRequest.serializer()
Method.Defined.ResourcesRead.value -> ReadResourceRequest.serializer()
Method.Defined.ResourcesSubscribe.value -> SubscribeRequest.serializer()
Method.Defined.ResourcesUnsubscribe.value -> UnsubscribeRequest.serializer()
Method.Defined.ToolsCall.value -> CallToolRequest.serializer()
Method.Defined.ToolsList.value -> ListToolsRequest.serializer()
else -> null
}
private fun selectClientNotificationDeserializer(element: JsonElement): DeserializationStrategy<ClientNotification>? =
when (element.jsonObject.getValue("method").jsonPrimitive.content) {
Method.Defined.NotificationsCancelled.value -> CancelledNotification.serializer()
Method.Defined.NotificationsProgress.value -> ProgressNotification.serializer()
Method.Defined.NotificationsInitialized.value -> InitializedNotification.serializer()
Method.Defined.NotificationsRootsListChanged.value -> RootsListChangedNotification.serializer()
else -> null
}
internal object ClientNotificationPolymorphicSerializer :
JsonContentPolymorphicSerializer<ClientNotification>(ClientNotification::class) {
override fun selectDeserializer(element: JsonElement): DeserializationStrategy<ClientNotification> =
selectClientNotificationDeserializer(element)
?: UnknownMethodRequestOrNotification.serializer()
}
internal fun selectServerRequestDeserializer(method: String): DeserializationStrategy<ServerRequest>? = when (method) {
Method.Defined.Ping.value -> PingRequest.serializer()
Method.Defined.SamplingCreateMessage.value -> CreateMessageRequest.serializer()
Method.Defined.RootsList.value -> ListRootsRequest.serializer()
else -> null
}
internal fun selectServerNotificationDeserializer(element: JsonElement): DeserializationStrategy<ServerNotification>? =
when (element.jsonObject.getValue("method").jsonPrimitive.content) {
Method.Defined.NotificationsCancelled.value -> CancelledNotification.serializer()
Method.Defined.NotificationsProgress.value -> ProgressNotification.serializer()
Method.Defined.NotificationsMessage.value -> LoggingMessageNotification.serializer()
Method.Defined.NotificationsResourcesUpdated.value -> ResourceUpdatedNotification.serializer()
Method.Defined.NotificationsResourcesListChanged.value -> ResourceListChangedNotification.serializer()
Method.Defined.NotificationsToolsListChanged.value -> ToolListChangedNotification.serializer()
Method.Defined.NotificationsPromptsListChanged.value -> PromptListChangedNotification.serializer()
else -> null
}
internal object ServerNotificationPolymorphicSerializer :
JsonContentPolymorphicSerializer<ServerNotification>(ServerNotification::class) {
override fun selectDeserializer(element: JsonElement): DeserializationStrategy<ServerNotification> =
selectServerNotificationDeserializer(element)
?: UnknownMethodRequestOrNotification.serializer()
}
internal object NotificationPolymorphicSerializer :
JsonContentPolymorphicSerializer<Notification>(Notification::class) {
override fun selectDeserializer(element: JsonElement): DeserializationStrategy<Notification> =
selectClientNotificationDeserializer(element)
?: selectServerNotificationDeserializer(element)
?: UnknownMethodRequestOrNotification.serializer()
}
internal object RequestPolymorphicSerializer :
JsonContentPolymorphicSerializer<Request>(Request::class) {
override fun selectDeserializer(element: JsonElement): DeserializationStrategy<Request> {
val method = element.jsonObject.getOrElse("method") { null }?.jsonPrimitive?.content ?: run {
logger.error { "No method in $element" }
error("No method in $element")
}
return selectClientRequestDeserializer(method)
?: selectServerRequestDeserializer(method)
?: UnknownMethodRequestOrNotification.serializer()
}
}
private fun selectServerResultDeserializer(element: JsonElement): DeserializationStrategy<ServerResult>? {
val jsonObject = element.jsonObject
return when {
jsonObject.contains("tools") -> ListToolsResult.serializer()
jsonObject.contains("resources") -> ListResourcesResult.serializer()
jsonObject.contains("resourceTemplates") -> ListResourceTemplatesResult.serializer()
jsonObject.contains("prompts") -> ListPromptsResult.serializer()
jsonObject.contains("capabilities") -> InitializeResult.serializer()
jsonObject.contains("description") -> GetPromptResult.serializer()
jsonObject.contains("completion") -> CompleteResult.serializer()
jsonObject.contains("toolResult") -> CompatibilityCallToolResult.serializer()
jsonObject.contains("contents") -> ReadResourceResult.serializer()
jsonObject.contains("content") -> CallToolResult.serializer()
else -> null
}
}
private fun selectClientResultDeserializer(element: JsonElement): DeserializationStrategy<ClientResult>? {
val jsonObject = element.jsonObject
return when {
jsonObject.contains("model") -> CreateMessageResult.serializer()
jsonObject.contains("roots") -> ListRootsResult.serializer()
jsonObject.contains("action") -> CreateElicitationResult.serializer()
else -> null
}
}
internal object ServerResultPolymorphicSerializer :
JsonContentPolymorphicSerializer<ServerResult>(ServerResult::class) {
override fun selectDeserializer(element: JsonElement): DeserializationStrategy<ServerResult> =
selectServerResultDeserializer(element)
?: EmptyRequestResult.serializer()
}
internal object ClientResultPolymorphicSerializer :
JsonContentPolymorphicSerializer<ClientResult>(ClientResult::class) {
override fun selectDeserializer(element: JsonElement): DeserializationStrategy<ClientResult> =
selectClientResultDeserializer(element)
?: EmptyRequestResult.serializer()
}
internal object RequestResultPolymorphicSerializer :
JsonContentPolymorphicSerializer<RequestResult>(RequestResult::class) {
override fun selectDeserializer(element: JsonElement): DeserializationStrategy<RequestResult> =
selectClientResultDeserializer(element)
?: selectServerResultDeserializer(element)
?: EmptyRequestResult.serializer()
}
internal object JSONRPCMessagePolymorphicSerializer :
JsonContentPolymorphicSerializer<JSONRPCMessage>(JSONRPCMessage::class) {
override fun selectDeserializer(element: JsonElement): DeserializationStrategy<JSONRPCMessage> {
val jsonObject = element.jsonObject
return when {
jsonObject.contains("message") -> JSONRPCError.serializer()
!jsonObject.contains("method") -> JSONRPCResponse.serializer()
jsonObject.contains("id") -> JSONRPCRequest.serializer()
else -> JSONRPCNotification.serializer()
}
}
}
public val EmptyJsonObject: JsonObject = JsonObject(emptyMap())
public class RequestIdSerializer : KSerializer<RequestId> {
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("RequestId")
override fun deserialize(decoder: Decoder): RequestId {
val jsonDecoder = decoder as? JsonDecoder ?: error("Can only deserialize JSON")
val element = jsonDecoder.decodeJsonElement()
return when (element) {
is JsonPrimitive -> when {
element.isString -> RequestId.StringId(element.content)
element.longOrNull != null -> RequestId.NumberId(element.long)
else -> error("Invalid RequestId type")
}
else -> error("Invalid RequestId format")
}
}
override fun serialize(encoder: Encoder, value: RequestId) {
val jsonEncoder = encoder as? JsonEncoder ?: error("Can only serialize JSON")
when (value) {
is RequestId.StringId -> jsonEncoder.encodeString(value.value)
is RequestId.NumberId -> jsonEncoder.encodeLong(value.value)
}
}
}
@Deprecated(
message = "Use `io.modelcontextprotocol.kotlin.sdk.types.EmptyJsonObject` instead",
replaceWith = ReplaceWith("EmptyJsonObject", "io.modelcontextprotocol.kotlin.sdk.types.EmptyJsonObject"),
level = DeprecationLevel.WARNING,
)
public val EmptyJsonObject: JsonObject = io.modelcontextprotocol.kotlin.sdk.types.EmptyJsonObject
/**
* Creates a [CallToolResult] with single [TextContent] and [meta].
*/
public fun CallToolResult.Companion.ok(content: String, meta: JsonObject = EmptyJsonObject): CallToolResult =
CallToolResult(
content = listOf(TextContent(content)),
isError = false,
_meta = meta,
)
@Deprecated(
message = "Use `CallToolResult.success` instead",
replaceWith = ReplaceWith("CallToolResult.Companion.success"),
level = DeprecationLevel.WARNING,
)
public fun CallToolResult.ok(
content: String,
meta: JsonObject = EmptyJsonObject,
): io.modelcontextprotocol.kotlin.sdk.types.CallToolResult =
io.modelcontextprotocol.kotlin.sdk.types.CallToolResult.success(content, meta)
/**
* Creates a [CallToolResult] with single [TextContent] and [meta], with `isError` being true.
*/
public fun CallToolResult.Companion.error(content: String, meta: JsonObject = EmptyJsonObject): CallToolResult =
CallToolResult(
content = listOf(TextContent(content)),
isError = true,
_meta = meta,
)
@Deprecated(
message = "Use `CallToolResult.error` instead",
replaceWith = ReplaceWith("CallToolResult.Companion.error"),
level = DeprecationLevel.WARNING,
)
public fun CallToolResult.error(
content: String,
meta: JsonObject = EmptyJsonObject,
): io.modelcontextprotocol.kotlin.sdk.types.CallToolResult =
io.modelcontextprotocol.kotlin.sdk.types.CallToolResult.error(content, meta)

View file

@ -0,0 +1,14 @@
package io.modelcontextprotocol.kotlin.sdk.types
import kotlinx.serialization.json.JsonElement
/**
* Represents an error specific to the MCP protocol.
*
* @property code The error code.
* @property message The error message.
* @property data Additional error data as a JSON object.
*/
public class McpException(public val code: Int, message: String, public val data: JsonElement? = null) : Exception() {
override val message: String = "MCP error $code: $message"
}

View file

@ -0,0 +1,14 @@
package io.modelcontextprotocol.kotlin.sdk.types
import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
@Serializable
public data class PingRequest(override val params: BaseRequestParams? = null) :
ClientRequest,
ServerRequest {
@OptIn(ExperimentalSerializationApi::class)
@EncodeDefault
override val method: Method = Method.Defined.Ping
}

View file

@ -0,0 +1,145 @@
package io.modelcontextprotocol.kotlin.sdk.types
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObject
/**
* Describes an MCP (Model Context Protocol) implementation.
*
* This metadata helps clients identify and display information about servers or clients,
* including their name, version, and optional branding elements like icons and website links.
*
* @property name The programmatic identifier for this implementation.
* Intended for logical use and API identification. If [title] is not provided,
* this should be used as a fallback display name.
* @property version The version string of this implementation (e.g., "1.0.0", "2.1.3-beta").
* @property title Optional human-readable display name for this implementation.
* Intended for UI and end-user contexts, optimized to be easily understood
* even by those unfamiliar with domain-specific terminology.
* If not provided, [name] should be used for display purposes.
* @property websiteUrl Optional URL of the website for this implementation.
* Can be used to provide documentation, support, or additional information.
* @property icons Optional set of sized icons that clients can display in their user interface.
* See [Icon] for supported formats and requirements.
*/
@Serializable
public data class Implementation(
val name: String,
val version: String,
val title: String? = null,
val websiteUrl: String? = null,
val icons: List<Icon>? = null,
)
/**
* Capabilities that a client may support.
*
* Known capabilities are defined here, but this is not a closed set: any client
* can define its own additional capabilities through the [experimental] field.
*
* The presence of a capability object (non-null value) indicates that the client
* supports that capability.
*
* @property sampling Present if the client supports sampling from an LLM.
* @property roots Present if the client supports listing roots.
* @property elicitation Present if the client supports elicitation from the server.
* @property experimental Experimental, non-standard capabilities that the client supports.
* Keys are capability names, values are capability-specific configuration objects.
*/
@Serializable
public data class ClientCapabilities(
public val sampling: JsonObject? = null,
public val roots: Roots? = null,
public val elicitation: JsonObject? = null,
public val experimental: JsonObject? = null,
) {
public companion object {
public val sampling: JsonObject = EmptyJsonObject
public val elicitation: JsonObject = EmptyJsonObject
}
/**
* Indicates that the client supports listing roots.
*
* Roots are the top-level directories or locations that the server can access.
* When present (non-null), the server can query available roots and optionally
* receive notifications when the roots list changes.
*
* @property listChanged Whether the client supports notifications for changes to the roots list.
* If true, the client will send notifications when roots are added or removed.
*/
@Serializable
public data class Roots(val listChanged: Boolean? = null)
}
/**
* Capabilities that a server may support.
*
* Known capabilities are defined here, but this is not a closed set: any server
* can define its own additional capabilities through the [experimental] field.
*
* The presence of a capability object (non-null value) indicates that the server
* supports that capability.
*
* @property tools Present if the server offers any tools to call.
* @property resources Present if the server offers any resources to read.
* @property prompts Present if the server offers any prompt templates.
* @property logging Present if the server supports sending log messages to the client.
* @property completions Present if the server supports argument autocompletion suggestions.
* Keys are capability names, values are capability-specific configuration objects.
* @property experimental Experimental, non-standard capabilities that the server supports.
*/
@Serializable
public data class ServerCapabilities(
val tools: Tools? = null,
val resources: Resources? = null,
val prompts: Prompts? = null,
val logging: JsonObject? = null,
val completions: JsonObject? = null,
val experimental: JsonObject? = null,
) {
public companion object {
public val Logging: JsonObject = EmptyJsonObject
public val Completions: JsonObject = EmptyJsonObject
}
/**
* Indicates that the server offers tools to call.
*
* When present (non-null), clients can list and invoke tools (functions, actions, etc.)
* provided by the server.
*
* @property listChanged Whether this server supports notifications for changes to the tool list.
* If true, the server will send notifications when tools are added, modified, or removed.
*/
@Serializable
public data class Tools(val listChanged: Boolean? = null)
/**
* Indicates that the server offers resources to read.
*
* When present (non-null), clients can list and read resources (files, data sources, etc.)
* provided by the server.
*
* @property listChanged Whether this server supports notifications for changes to the resource list.
* If true, the server will send notifications when resources are added or removed.
* @property subscribe Whether this server supports subscribing to resource updates.
* If true, clients can subscribe to receive notifications when specific
* resources are modified.
*/
@Serializable
public data class Resources(val listChanged: Boolean? = null, val subscribe: Boolean? = null)
/**
* Indicates that the server offers prompt templates.
*
* When present (non-null), clients can list and invoke prompts provided by the server.
*
* @property listChanged Whether this server supports notifications for changes to the prompt list.
* If true, the server will send notifications when prompts are added, modified, or removed.
*/
@Serializable
public data class Prompts(val listChanged: Boolean? = null)
}

View file

@ -0,0 +1,164 @@
package io.modelcontextprotocol.kotlin.sdk.types
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObject
// ============================================================================
// Protocol Version Constants
// ============================================================================
public const val LATEST_PROTOCOL_VERSION: String = "2025-03-26"
public val SUPPORTED_PROTOCOL_VERSIONS: List<String> = listOf(
LATEST_PROTOCOL_VERSION,
"2024-11-05",
)
// ============================================================================
// Base Interfaces
// ============================================================================
/**
* Represents an entity that includes additional metadata in its responses.
*/
@Serializable
public sealed interface WithMeta {
@SerialName("_meta")
public val meta: JsonObject?
}
// ============================================================================
// Tokens
// ============================================================================
/**
* A progress token, used to associate progress notifications with the original request.
*/
public typealias ProgressToken = RequestId
public fun ProgressToken(value: String): ProgressToken = RequestId(value)
public fun ProgressToken(value: Long): ProgressToken = RequestId(value)
// ============================================================================
// Visual Elements
// ============================================================================
/**
* An optionally sized icon that can be displayed in a user interface.
*
* Icons help clients provide visual branding and identification for MCP implementations.
*
* **Security considerations:**
* - Consumers SHOULD ensure URLs serving icons are from the same domain as the client/server
* or a trusted domain to prevent malicious content.
* - Consumers SHOULD take appropriate precautions when rendering SVGs as they can contain
* executable JavaScript. Consider sanitizing SVG content or rendering in isolated contexts.
*
* @property src A standard URI pointing to an icon resource.
* Maybe an HTTP/HTTPS URL or a data: URI with Base64-encoded image data.
* Example: "https://example.com/icon.png" or "data:image/png;base64,iVBORw0KG..."
* @property mimeType Optional MIME type override if the source MIME type is missing or generic.
* For example, "image/png", "image/jpeg", or "image/svg+xml".
* Useful when the URL doesn't include a file extension or uses a generic MIME type.
* @property sizes Optional array of strings that specify sizes at which the icon can be used.
* Each string should be in WxH format (e.g., "48x48", "96x96") or "any" for
* scalable formats like SVG. If not provided, the client should assume that
* the icon can be used at any size.
* @property theme Optional specifier for the theme this icon is designed for.
* [Theme.Light] indicates the icon is designed for a light background,
* [Theme.Dark] indicates the icon is designed for a dark background.
* If not provided, the client should assume the icon can be used with any theme.
*/
@Serializable
public data class Icon(
val src: String,
val mimeType: String? = null,
val sizes: List<String>? = null,
val theme: Theme? = null,
) {
/**
* The theme context for which an icon is designed.
*
* @property Light Icon designed for use with a light background (typically darker icon).
* @property Dark Icon designed for use with a dark background (typically lighter icon).
*/
@Serializable
public enum class Theme {
/** Icon designed for use with a light background */
@SerialName("light")
Light,
/** Icon designed for use with a dark background */
@SerialName("dark")
Dark,
}
}
// ============================================================================
// Roles and References
// ============================================================================
/**
* The sender or recipient of messages and data in a conversation.
*/
@Serializable
public enum class Role {
@SerialName("user")
User,
@SerialName("assistant")
Assistant,
}
/**
* Base interface for reference types in the protocol.
*
* References are used to point to other entities (prompts, resources, etc.)
* without including their full definitions.
*/
@Serializable(with = ReferencePolymorphicSerializer::class)
public sealed interface Reference {
public val type: ReferenceType
}
@Serializable
public enum class ReferenceType(public val value: String) {
@SerialName("ref/prompt")
Prompt("ref/prompt"),
@SerialName("ref/resource")
ResourceTemplate("ref/resource"),
}
// ============================================================================
// Annotations and Metadata
// ============================================================================
/**
* Optional annotations for the client.
*
* The client can use annotations to inform how objects are used or displayed.
*
* @property audience Describes who the intended customer of this object or data is.
* Can include multiple entries to indicate content useful for multiple audiences
* (e.g., [Role.user, Role.assistant]).
* @property priority Describes how important this data is for operating the server.
* A value of 1.0 means "most important" and indicates that the data is effectively required,
* while 0.0 means "least important" and indicates that the data is entirely optional.
* Should be a value between 0.0 and 1.0.
* @property lastModified The moment the resource was last modified, as an ISO 8601 formatted string
* (e.g., "2025-01-12T15:00:58Z").
* Examples: last activity timestamp in an open file, timestamp when the resource was attached, etc.
*/
@Serializable
public data class Annotations(
val audience: List<Role>? = null,
val priority: Double? = null,
val lastModified: String? = null,
) {
init {
require(priority == null || priority in 0.0..1.0) { "Priority must be between 0.0 and 1.0" }
}
}

View file

@ -0,0 +1,93 @@
package io.modelcontextprotocol.kotlin.sdk.types
import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObject
/**
* A request from the client to the server to ask for completion options.
*
* @property params The request parameters containing the argument to complete and its context.
*/
@Serializable
public data class CompleteRequest(override val params: CompleteRequestParams) : ClientRequest {
@OptIn(ExperimentalSerializationApi::class)
@EncodeDefault
public override val method: Method = Method.Defined.CompletionComplete
}
/**
* Parameters for the completion request.
*
* @property argument The argument's information for which completion options are requested.
* @property ref A reference to either a prompt or resource template to complete within.
* @property context Additional, optional context for generating completions.
*/
@Serializable
public data class CompleteRequestParams(
val argument: Argument,
val ref: Reference,
val context: Context? = null,
@SerialName("_meta")
override val meta: RequestMeta? = null,
) : RequestParams {
/**
* The argument for which completion is being requested.
*
* @property name The name of the argument being completed.
* @property value The partial value of the argument to use for completion matching.
* This is typically the text the user has typed so far.
*/
@Serializable
public data class Argument(val name: String, val value: String)
/**
* Additional context to help generate more relevant completions.
*
* @property arguments Previously-resolved variables in a URI template or prompt.
* These can be used to provide context-aware completions.
* For example, if completing a file path, this might contain the repository or directory context.
*/
@Serializable
public data class Context(val arguments: Map<String, String>? = null)
}
/**
* The server's response to a [CompleteRequest].
*
* Provides completion options for prompt or resource template arguments,
* along with pagination information if there are many possible completions.
*
* @property completion The completion options and metadata about available results.
* @property meta Optional metadata for this response. See MCP specification for details on _meta usage.
*/
@Serializable
public data class CompleteResult(
public val completion: Completion,
@SerialName("_meta")
override val meta: JsonObject? = null,
) : ServerResult {
/**
* Completion options and pagination information.
*
* @property values An array of completion values. Must not exceed 100 items.
* Each value represents a possible completion for the requested argument.
* @property total The total number of completion options available.
* This can exceed the number of values actually sent in the response,
* indicating that pagination or filtering may be needed.
* @property hasMore Indicates whether there are additional completion options beyond
* those provided in the current response, even if the exact total is unknown.
* Use this when the complete set of completions is too large to calculate upfront.
*/
@Serializable
public data class Completion(val values: List<String>, val total: Int? = null, val hasMore: Boolean? = null) {
init {
require(values.size <= 100) {
"Completion 'values' must not exceed 100 items, got ${values.size}"
}
}
}
}

View file

@ -0,0 +1,163 @@
@file:OptIn(ExperimentalSerializationApi::class)
package io.modelcontextprotocol.kotlin.sdk.types
import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObject
@Serializable
public enum class ContentTypes(public val value: String) {
@SerialName("text")
TEXT("text"),
@SerialName("image")
IMAGE("image"),
@SerialName("audio")
AUDIO("audio"),
@SerialName("resource_link")
RESOURCE_LINK("resource_link"),
@SerialName("resource")
EMBEDDED_RESOURCE("resource"),
}
@Serializable(with = ContentBlockPolymorphicSerializer::class)
public sealed interface ContentBlock : WithMeta {
public val type: ContentTypes
}
@Serializable(with = MediaContentPolymorphicSerializer::class)
public sealed interface MediaContent : ContentBlock
/**
* Text provided to or from an LLM.
*
* @property text The text content of the message.
* @property annotations Optional annotations for the client.
* @property meta property/parameter is reserved by MCP to allow clients and servers
* to attach additional metadata to their interactions.
*/
@Serializable
public data class TextContent(
val text: String,
val annotations: Annotations? = null,
@SerialName("_meta")
override val meta: JsonObject? = null,
) : MediaContent {
@EncodeDefault
public override val type: ContentTypes = ContentTypes.TEXT
}
/**
* An image provided to or from an LLM.
*
* @property data The base64-encoded image data.
* @property mimeType The MIME type of the image. Different providers may support different image types.
* @property annotations Optional annotations for the client.
* @property meta property/parameter is reserved by MCP to allow clients and servers
* to attach additional metadata to their interactions.
*/
@Serializable
public data class ImageContent(
val data: String,
val mimeType: String,
val annotations: Annotations? = null,
@SerialName("_meta")
override val meta: JsonObject? = null,
) : MediaContent {
@EncodeDefault
public override val type: ContentTypes = ContentTypes.IMAGE
}
/**
* Audio provided to or from an LLM.
*
* @property data The base64-encoded audio data.
* @property mimeType The MIME type of the audio. Different providers may support different audio types.
* @property annotations Optional annotations for the client.
* @property meta property/parameter is reserved by MCP to allow clients and servers
* to attach additional metadata to their interactions.
*/
@Serializable
public data class AudioContent(
val data: String,
val mimeType: String,
val annotations: Annotations? = null,
@SerialName("_meta")
override val meta: JsonObject? = null,
) : MediaContent {
@EncodeDefault
public override val type: ContentTypes = ContentTypes.AUDIO
}
/**
* A resource that the server is capable of reading, included in a prompt or tool call result.
*
* Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.
*
* @property name Intended for programmatic or logical use
* but used as a display name in past specs or fallback (if the title isn’t present).
* @property uri The URI of this resource.
* @property title Intended for UI and end-user contexts — optimized to be human-readable and easily understood,
* even by those unfamiliar with domain-specific terminology.
*
* If not provided, the name should be used for display
* (except for Tool, where `annotations.title` should be given precedence over using `name`, if present).
* @property size The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization),
* if known.
*
* Hosts can use this to display file sizes and estimate context window usage.
* @property mimeType The MIME type of this resource, if known.
* @property icons Optional set of sized icons that clients can display in their user interface.
* See [Icon] for supported formats and requirements.
* @property description A description of what this resource represents.
*
* Clients can use this to improve the LLM’s understanding of available resources.
* It can be thought of as a "hint" to the model.
* @property annotations Optional annotations for the client.
* @property meta property/parameter is reserved by MCP to allow clients and servers
* to attach additional metadata to their interactions.
*/
@Serializable
public data class ResourceLink(
val name: String,
val uri: String,
val title: String? = null,
val size: Long? = null,
val mimeType: String? = null,
val icons: List<Icon>? = null,
val description: String? = null,
val annotations: Annotations? = null,
@SerialName("_meta")
override val meta: JsonObject? = null,
) : ContentBlock,
ResourceLike {
@EncodeDefault
public override val type: ContentTypes = ContentTypes.RESOURCE_LINK
}
/**
* The contents of a resource, embedded into a prompt or tool call result.
*
* It is up to the client how best to render embedded resources for the benefit of the LLM and/or the user.
*
* @property resource The resource contents.
* @property annotations Optional annotations for the client.
* @property meta property/parameter is reserved by MCP to allow clients and servers
* to attach additional metadata to their interactions.
*/
@Serializable
public data class EmbeddedResource(
val resource: ResourceContents,
val annotations: Annotations? = null,
@SerialName("_meta")
override val meta: JsonObject? = null,
) : ContentBlock {
@EncodeDefault
public override val type: ContentTypes = ContentTypes.EMBEDDED_RESOURCE
}

View file

@ -0,0 +1,111 @@
package io.modelcontextprotocol.kotlin.sdk.types
import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObject
/**
* A request from the server to elicit additional information from the user via the client.
*
* This request type allows servers to prompt users for structured input through forms
* or dialogs presented by the client. The server defines a schema for the requested data,
* and the client presents an appropriate UI to collect this information.
*
* @property params The elicitation parameters including the message and requested schema.
*/
@Serializable
public data class ElicitRequest(override val params: ElicitRequestParams) : ServerRequest {
@OptIn(ExperimentalSerializationApi::class)
@EncodeDefault
public override val method: Method = Method.Defined.ElicitationCreate
}
/**
* Parameters for an elicitation/create request.
*
* @property message The message to present to the user. This should clearly explain
* what information is being requested and why.
* @property requestedSchema A restricted subset of JSON Schema defining the structure
* of the requested data. Only top-level properties are allowed,
* without nesting.
* @property meta Optional metadata for this request. May include a progressToken for
* out-of-band progress notifications.
*/
@Serializable
public data class ElicitRequestParams(
val message: String,
val requestedSchema: RequestedSchema,
@SerialName("_meta")
override val meta: RequestMeta? = null,
) : RequestParams {
/**
* A restricted JSON Schema for elicitation requests.
*
* Only supports top-level primitive properties without nesting. Each property
* represents a field in the form or dialog presented to the user.
*
* @property properties A map of property names to their schema definitions.
* Each property must be a primitive type (string, number, boolean).
* @property required Optional list of property names that must be provided by the user.
* If omitted, all fields are considered optional.
* @property type Always "object" for elicitation schemas.
*/
@Serializable
public data class RequestedSchema(val properties: JsonObject, val required: List<String>? = null) {
@OptIn(ExperimentalSerializationApi::class)
@EncodeDefault
val type: String = "object"
}
}
/**
* The client's response to an [ElicitRequest].
*
* Represents the user's action and, if accepted, the submitted form data.
*
* @property action The user action in response to the elicitation prompt.
* @property content The submitted form data, only present when [action] is [Action.Accept].
* Contains values matching the requested schema, where keys correspond
* to property names and values are primitives (string, number, or boolean).
* @property meta Optional metadata for this response.
* @throws IllegalArgumentException if content is provided with a non-accept action.
*/
@Serializable
public data class ElicitResult(
val action: Action,
val content: JsonObject? = null,
@SerialName("_meta")
override val meta: JsonObject? = null,
) : ClientResult {
init {
require(action == Action.Accept || content == null) {
"Content can only be provided when action is 'accept', got action=$action with content"
}
}
/**
* The user's response action to an elicitation request.
*
* @property Accept User submitted the form/confirmed the action. Content will be provided.
* @property Decline User explicitly declined the action. No content provided.
* @property Cancel User dismissed the dialog without making an explicit choice. No content provided.
*/
@Serializable
public enum class Action {
/** User submitted the form/confirmed the action */
@SerialName("accept")
Accept,
/** User explicitly declined the action */
@SerialName("decline")
Decline,
/** User dismissed without making an explicit choice */
@SerialName("cancel")
Cancel,
}
}

View file

@ -0,0 +1,74 @@
package io.modelcontextprotocol.kotlin.sdk.types
import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObject
/**
* This request is sent from the client to the server when it first connects,
* asking it to begin initialization.
*
* The initialize request is the first message exchanged in the MCP protocol handshake.
* It allows the client to communicate its capabilities and protocol version to the server,
* and receive the server's capabilities in response.
*
* @property params The initialization parameters including protocol version and client capabilities.
*/
@Serializable
public data class InitializeRequest(override val params: InitializeRequestParams) : ClientRequest {
@OptIn(ExperimentalSerializationApi::class)
@EncodeDefault
override val method: Method = Method.Defined.Initialize
}
/**
* Parameters for an initialize request.
*
* @property protocolVersion The latest version of the Model Context Protocol that the client supports.
* The client MAY decide to support older versions as well.
* The server will respond with its preferred version, which may differ.
* @property capabilities The capabilities that this client supports.
* Describes which optional features the client has implemented.
* @property clientInfo Information about the client implementation, including name, version, and branding.
* @property meta Optional metadata for this request. May include a progressToken for
* out-of-band progress notifications.
*/
@Serializable
public data class InitializeRequestParams(
val protocolVersion: String,
val capabilities: ClientCapabilities,
val clientInfo: Implementation,
@SerialName("_meta")
override val meta: RequestMeta? = null,
) : RequestParams
/**
* After receiving an [InitializeRequest] from the client, the server sends this response.
*
* The server communicates its chosen protocol version, capabilities, and optional
* instructions for how to effectively use its features.
*
* @property protocolVersion The version of the Model Context Protocol that the server wants to use.
* This may not match the version that the client requested.
* If the client cannot support this version, it MUST disconnect.
* @property capabilities The capabilities that this server supports.
* Describes which optional features the server has implemented.
* @property serverInfo Information about the server implementation, including name, version, and branding.
* @property instructions Optional instructions describing how to use the server and its features.
* Clients can use this to improve the LLM's understanding of available
* tools, resources, etc. It can be thought of as a "hint" to the model.
* For example, this information MAY be added to the system prompt to help
* the LLM make better use of the server's capabilities.
* @property meta Optional metadata for this response.
*/
@Serializable
public data class InitializeResult(
val protocolVersion: String = LATEST_PROTOCOL_VERSION,
val capabilities: ServerCapabilities,
val serverInfo: Implementation,
val instructions: String? = null,
@SerialName("_meta")
override val meta: JsonObject? = null,
) : ServerResult

View file

@ -0,0 +1,225 @@
@file:OptIn(ExperimentalAtomicApi::class, ExperimentalSerializationApi::class)
package io.modelcontextprotocol.kotlin.sdk.types
import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.decodeFromJsonElement
import kotlinx.serialization.json.encodeToJsonElement
import kotlin.concurrent.atomics.AtomicLong
import kotlin.concurrent.atomics.ExperimentalAtomicApi
import kotlin.concurrent.atomics.incrementAndFetch
import kotlin.jvm.JvmInline
public const val JSONRPC_VERSION: String = "2.0"
private val REQUEST_MESSAGE_ID: AtomicLong = AtomicLong(0L)
public fun RequestId(value: String): RequestId = RequestId.StringId(value)
public fun RequestId(value: Long): RequestId = RequestId.NumberId(value)
/**
* A uniquely identifying ID for a request in JSON-RPC.
*/
@Serializable(with = RequestIdPolymorphicSerializer::class)
public sealed interface RequestId {
@JvmInline
@Serializable
public value class StringId(public val value: String) : RequestId
@JvmInline
@Serializable
public value class NumberId(public val value: Long) : RequestId
}
/**
* Converts the request to a JSON-RPC request.
*
* @return The JSON-RPC request representation.
*/
public fun Request.toJSON(): JSONRPCRequest = JSONRPCRequest(
method = method.value,
params = this.params?.let {
McpJson.encodeToJsonElement(it)
},
)
/**
* Decodes a JSON-RPC request into a protocol-specific [Request].
*
* @return The decoded [Request]
*/
public fun JSONRPCRequest.fromJSON(): Request =
McpJson.decodeFromJsonElement<Request>(McpJson.encodeToJsonElement(this))
/**
* Converts the notification to a JSON-RPC notification.
*
* @return The JSON-RPC notification representation.
*/
public fun Notification.toJSON(): JSONRPCNotification = JSONRPCNotification(
method = method.value,
params = this.params?.let {
McpJson.encodeToJsonElement(it)
},
)
/**
* Decodes a JSON-RPC notification into a protocol-specific [Notification].
*
* @return The decoded [Notification].
*/
internal fun JSONRPCNotification.fromJSON(): Notification =
McpJson.decodeFromJsonElement<Notification>(McpJson.encodeToJsonElement(this))
/**
* Base interface for all JSON-RPC 2.0 messages.
*
* All messages in the MCP protocol follow the JSON-RPC 2.0 specification.
*/
@Serializable(with = JSONRPCMessagePolymorphicSerializer::class)
public sealed interface JSONRPCMessage {
public val jsonrpc: String
}
// ============================================================================
// JSONRPCRequest
// ============================================================================
/**
* A request that expects a response.
*
* Requests are identified by a unique [id] and specify a [method] to invoke.
* The server or client (depending on direction) must respond with either a
* [JSONRPCResponse] or [JSONRPCError] that has the same [id].
*
* @property jsonrpc Always "2.0" to indicate JSON-RPC 2.0 protocol.
* @property id A unique identifier for this request. The response will include the same ID.
* Can be a string or number.
* @property method The name of the method to invoke (e.g., "tools/list", "resources/read").
* @property params Optional parameters for the method. Structure depends on the specific method.
*/
@Serializable
public data class JSONRPCRequest(
val id: RequestId = RequestId(REQUEST_MESSAGE_ID.incrementAndFetch()),
val method: String,
val params: JsonElement? = null,
) : JSONRPCMessage {
@EncodeDefault
override val jsonrpc: String = JSONRPC_VERSION
}
// ============================================================================
// JSONRPCNotification
// ============================================================================
/**
* A notification which does not expect a response.
*
* Notifications are fire-and-forget messages. They do not have an `id` and
* the recipient does not send any response (neither success nor error).
*
* Examples: progress updates, resource change notifications, log messages.
*
* @property jsonrpc Always "2.0" to indicate JSON-RPC 2.0 protocol.
* @property method The name of the notification method (e.g., "notifications/progress",
* "notifications/resources/updated").
* @property params Optional parameters for the notification. Structure depends on the specific method.
*/
@Serializable
public data class JSONRPCNotification(val method: String, val params: JsonElement? = null) : JSONRPCMessage {
@EncodeDefault
override val jsonrpc: String = JSONRPC_VERSION
}
// ============================================================================
// JSONRPCResponse
// ============================================================================
/**
* A successful (non-error) response to a request.
*
* Sent in response to a [JSONRPCRequest] when the method execution succeeds.
* The [id] must match the [id] of the original request.
*
* @property jsonrpc Always "2.0" to indicate JSON-RPC 2.0 protocol.
* @property id The identifier from the original request. Used to match responses to requests.
* @property result The result of the method execution. Structure depends on the method that was called.
*/
@Serializable
public data class JSONRPCResponse(val id: RequestId, val result: RequestResult = EmptyResult()) : JSONRPCMessage {
@EncodeDefault
override val jsonrpc: String = JSONRPC_VERSION
}
// ============================================================================
// JSONRPCError
// ============================================================================
/**
* A response to a request that indicates an error occurred.
*
* Sent in response to a [JSONRPCRequest] when the method execution fails.
* The [id] must match the [id] of the original request.
*
* @property jsonrpc Always "2.0" to indicate JSON-RPC 2.0 protocol.
* @property id The identifier from the original request. Used to match error responses to requests.
* @property error Details about the error that occurred, including error code and message.
*/
@Serializable
public data class JSONRPCError(val id: RequestId, val error: RPCError) : JSONRPCMessage {
@EncodeDefault
override val jsonrpc: String = JSONRPC_VERSION
}
/**
* Error information for a failed JSON-RPC request.
*
* @property code The error type that occurred. A number indicating the error category.
* See standard JSON-RPC 2.0 error codes:
* - -32700: Parse error (invalid JSON)
* - -32600: Invalid request (not valid JSON-RPC)
* - -32601: Method not found
* - -32602: Invalid params
* - -32603: Internal error
* - -32000 to -32099: Server-defined errors
* @property message A short description of the error.
* The message SHOULD be limited to a concise single sentence.
* @property data Additional information about the error.
* The value of this member is defined by the sender
* (e.g., detailed error information, nested errors, etc.).
*/
@Serializable
public data class RPCError(val code: Int, val message: String, val data: JsonElement? = null) {
/**
* Standard JSON-RPC 2.0 and MCP SDK error codes.
*/
public object ErrorCode {
// SDK-specific error codes
/** Connection was closed */
public const val CONNECTION_CLOSED: Int = -32000
/** Request timed out */
public const val REQUEST_TIMEOUT: Int = -32001
// Standard JSON-RPC 2.0 error codes
/** Invalid JSON was received */
public const val PARSE_ERROR: Int = -32700
/** The JSON sent is not a valid Request object */
public const val INVALID_REQUEST: Int = -32600
/** The method does not exist or is not available */
public const val METHOD_NOT_FOUND: Int = -32601
/** Invalid method parameter(s) */
public const val INVALID_PARAMS: Int = -32602
/** Internal JSON-RPC error */
public const val INTERNAL_ERROR: Int = -32603
}
}

View file

@ -0,0 +1,83 @@
package io.modelcontextprotocol.kotlin.sdk.types
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.ClassDiscriminatorMode
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.add
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
public val EmptyJsonObject: JsonObject = JsonObject(emptyMap())
@OptIn(ExperimentalSerializationApi::class)
public val McpJson: Json by lazy {
Json {
ignoreUnknownKeys = true
encodeDefaults = true
isLenient = true
classDiscriminatorMode = ClassDiscriminatorMode.NONE
explicitNulls = false
}
}
public fun Map<String, Any?>.toJson(): Map<String, JsonElement> = this.mapValues { (_, value) ->
runCatching { convertToJsonElement(value) }
.getOrElse { JsonPrimitive(value.toString()) }
}
@OptIn(ExperimentalUnsignedTypes::class, ExperimentalSerializationApi::class)
private fun convertToJsonElement(value: Any?): JsonElement = when (value) {
null -> JsonNull
is JsonElement -> value
is String -> JsonPrimitive(value)
is Number -> JsonPrimitive(value)
is Boolean -> JsonPrimitive(value)
is Char -> JsonPrimitive(value.toString())
is Enum<*> -> JsonPrimitive(value.name)
is Map<*, *> -> buildJsonObject { value.forEach { (k, v) -> put(k.toString(), convertToJsonElement(v)) } }
is Collection<*> -> buildJsonArray { value.forEach { add(convertToJsonElement(it)) } }
is Array<*> -> buildJsonArray { value.forEach { add(convertToJsonElement(it)) } }
// Primitive arrays
is IntArray -> buildJsonArray { value.forEach { add(it) } }
is LongArray -> buildJsonArray { value.forEach { add(it) } }
is FloatArray -> buildJsonArray { value.forEach { add(it) } }
is DoubleArray -> buildJsonArray { value.forEach { add(it) } }
is BooleanArray -> buildJsonArray { value.forEach { add(it) } }
is ShortArray -> buildJsonArray { value.forEach { add(it) } }
is ByteArray -> buildJsonArray { value.forEach { add(it) } }
is CharArray -> buildJsonArray { value.forEach { add(it.toString()) } }
// Unsigned arrays
is UIntArray -> buildJsonArray { value.forEach { add(JsonPrimitive(it)) } }
is ULongArray -> buildJsonArray { value.forEach { add(JsonPrimitive(it)) } }
is UShortArray -> buildJsonArray { value.forEach { add(JsonPrimitive(it)) } }
is UByteArray -> buildJsonArray { value.forEach { add(JsonPrimitive(it)) } }
else -> {
JsonPrimitive(value.toString())
}
}

View file

@ -0,0 +1,84 @@
package io.modelcontextprotocol.kotlin.sdk.types
import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* The severity of a log message.
*
* These levels map to syslog message severities, as specified in
* [RFC-5424](https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1).
*
* Levels are ordered from least to most severe:
* [Debug] < [Info] < [Notice] < [Warning] < [Error] < [Critical] < [Alert] < [Emergency]
*/
@Serializable
public enum class LoggingLevel {
/** Detailed debug information for troubleshooting (RFC-5424: Debug) */
@SerialName("debug")
Debug,
/** Informational messages about normal operations (RFC-5424: Informational) */
@SerialName("info")
Info,
/** Normal but significant conditions (RFC-5424: Notice) */
@SerialName("notice")
Notice,
/** Warning conditions that may require attention (RFC-5424: Warning) */
@SerialName("warning")
Warning,
/** Error conditions that require attention (RFC-5424: Error) */
@SerialName("error")
Error,
/** Critical conditions requiring immediate action (RFC-5424: Critical) */
@SerialName("critical")
Critical,
/** Action must be taken immediately (RFC-5424: Alert) */
@SerialName("alert")
Alert,
/** System is unusable, highest severity (RFC-5424: Emergency) */
@SerialName("emergency")
Emergency,
}
/**
* A request from the client to the server to enable or adjust logging.
*
* After receiving this request, the server should send log messages at the specified
* [level][SetLevelRequestParams.level] and higher (more severe) to the client as
* notifications/message events.
*
* @property params The parameters specifying the desired logging level.
*/
@Serializable
public data class SetLevelRequest(override val params: SetLevelRequestParams) : ClientRequest {
@OptIn(ExperimentalSerializationApi::class)
@EncodeDefault
override val method: Method = Method.Defined.LoggingSetLevel
}
/**
* Parameters for a logging/setLevel request.
*
* @property level The minimum severity level of logging that the client wants to receive
* from the server. The server should send all logs at this level and higher
* (i.e., more severe) to the client as notifications/message.
* For example, if [level] is [LoggingLevel.Warning], the server should send
* warning, error, critical, alert, and emergency messages, but not info, notice, or debug.
* @property meta Optional metadata for this request. May include a progressToken for
* out-of-band progress notifications.
*/
@Serializable
public data class SetLevelRequestParams(
val level: LoggingLevel,
@SerialName("_meta")
override val meta: RequestMeta? = null,
) : RequestParams

View file

@ -0,0 +1,49 @@
package io.modelcontextprotocol.kotlin.sdk.types
import kotlinx.serialization.Serializable
/**
* Represents a method in the protocol, which can be predefined or custom.
*/
@Serializable(with = MethodSerializer::class)
public sealed interface Method {
public val value: String
/**
* Enum of predefined methods supported by the protocol.
*/
@Serializable
public enum class Defined(override val value: String) : Method {
Initialize("initialize"),
Ping("ping"),
ResourcesList("resources/list"),
ResourcesTemplatesList("resources/templates/list"),
ResourcesRead("resources/read"),
ResourcesSubscribe("resources/subscribe"),
ResourcesUnsubscribe("resources/unsubscribe"),
PromptsList("prompts/list"),
PromptsGet("prompts/get"),
NotificationsCancelled("notifications/cancelled"),
NotificationsInitialized("notifications/initialized"),
NotificationsProgress("notifications/progress"),
NotificationsMessage("notifications/message"),
NotificationsResourcesUpdated("notifications/resources/updated"),
NotificationsResourcesListChanged("notifications/resources/list_changed"),
NotificationsToolsListChanged("notifications/tools/list_changed"),
NotificationsRootsListChanged("notifications/roots/list_changed"),
NotificationsPromptsListChanged("notifications/prompts/list_changed"),
ToolsList("tools/list"),
ToolsCall("tools/call"),
LoggingSetLevel("logging/setLevel"),
SamplingCreateMessage("sampling/createMessage"),
CompletionComplete("completion/complete"),
RootsList("roots/list"),
ElicitationCreate("elicitation/create"),
}
/**
* Represents a custom method defined by the user.
*/
@Serializable
public data class Custom(override val value: String) : Method
}

View file

@ -0,0 +1,327 @@
@file:OptIn(ExperimentalSerializationApi::class)
package io.modelcontextprotocol.kotlin.sdk.types
import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
/**
* Represents a notification in the protocol.
*/
@Serializable(with = NotificationPolymorphicSerializer::class)
public sealed interface Notification {
public val method: Method
public val params: NotificationParams?
}
/**
* Represents a notification sent by the client.
*/
@Serializable(with = ClientNotificationPolymorphicSerializer::class)
public sealed interface ClientNotification : Notification
/**
* Represents a notification sent by the server.
*/
@Serializable(with = ServerNotificationPolymorphicSerializer::class)
public sealed interface ServerNotification : Notification
/**
* Interface for notification parameter types.
*
* @property meta Optional metadata for the notification.
*/
@Serializable
public sealed interface NotificationParams : WithMeta
/**
* Base parameters for notifications that only contain metadata.
*/
@Serializable
public data class BaseNotificationParams(@SerialName("_meta") override val meta: JsonObject? = null) :
NotificationParams
/**
* Represents a progress notification.
*
* @property progress The progress thus far. This should increase every time progress is made,
* even if the total is unknown.
* @property total Total number of items to a process (or total progress required), if known.
* @property message An optional message describing the current progress.
*/
@Serializable
public class Progress(
public val progress: Double,
public val total: Double? = null,
public val message: String? = null,
)
// ============================================================================
// Custom Notification
// ============================================================================
/**
* Represents a custom notification method that is not part of the core MCP specification.
*
* The MCP protocol allows implementations to define custom methods for extending functionality.
* This class captures such custom notifications while preserving all their data.
*
* @property method The custom method name. By convention, custom methods often contain
* organization-specific prefixes (e.g., "mycompany/custom_event").
* @property params Raw JSON parameters for the custom notification, if present.
*/
@Serializable
public data class CustomNotification(override val method: Method, override val params: BaseNotificationParams? = null) :
ClientNotification,
ServerNotification
// ============================================================================
// Cancelled Notification
// ============================================================================
/**
* This notification can be sent by either side to indicate that it is cancelling a previously-issued request.
*
* The request SHOULD still be in-flight, but due to communication latency,
* it is always possible that this notification MAY arrive after the request has already finished.
*
* This notification indicates that the result will be unused, so any associated processing SHOULD cease.
*
* A client MUST NOT attempt to cancel its `initialize` request.
*
* @property params Details of the cancellation request.
*/
@Serializable
public data class CancelledNotification(override val params: CancelledNotificationParams) :
ClientNotification,
ServerNotification {
@EncodeDefault
override val method: Method = Method.Defined.NotificationsCancelled
}
/**
* Parameters for a notifications/cancelled notification.
*
* @property requestId The ID of the request to cancel.
* This MUST correspond to the ID of a request previously issued in the same direction.
* @property reason An optional string describing the reason for the cancellation.
* This MAY be logged or presented to the user.
* @property meta Optional metadata for this notification.
*/
@Serializable
public data class CancelledNotificationParams(
val requestId: RequestId,
val reason: String? = null,
@SerialName("_meta")
override val meta: JsonObject? = null,
) : NotificationParams
// ============================================================================
// Initialized Notification
// ============================================================================
/**
* This notification is sent from the client to the server after initialization has finished.
*
* The client sends this after receiving the [InitializeResult] to signal that it is ready
* to begin normal operations.
*
* @property params Optional notification parameters containing metadata.
*/
@Serializable
public data class InitializedNotification(override val params: BaseNotificationParams? = null) : ClientNotification {
@EncodeDefault
override val method: Method = Method.Defined.NotificationsInitialized
}
// ============================================================================
// Logging Message Notification
// ============================================================================
/**
* A notification of a log message passed from server to client.
*
* If no [SetLevelRequest] has been sent from the client, the server MAY decide
* which messages to send automatically.
*
* @property params The log message parameters including level and data.
*/
@Serializable
public data class LoggingMessageNotification(override val params: LoggingMessageNotificationParams) :
ServerNotification {
@EncodeDefault
override val method: Method = Method.Defined.NotificationsMessage
}
/**
* Parameters for a notifications/message notification.
*
* @property level The severity of this log message.
* @property data The data to be logged, such as a string message or an object.
* Any JSON serializable type is allowed here.
* @property logger An optional name of the logger issuing this message.
* @property meta Optional metadata for this notification.
*/
@Serializable
public data class LoggingMessageNotificationParams(
val level: LoggingLevel,
val data: JsonElement,
val logger: String? = null,
@SerialName("_meta")
override val meta: JsonObject? = null,
) : NotificationParams
// ============================================================================
// Progress Notification
// ============================================================================
/**
* An out-of-band notification used to inform the receiver of a progress update for a long-running request.
*
* This notification can be sent by either the client or server to provide progress updates
* for requests that include a progressToken in their _meta field.
*
* @property params The progress update parameters.
*/
@Serializable
public data class ProgressNotification(override val params: ProgressNotificationParams) :
ClientNotification,
ServerNotification {
@EncodeDefault
override val method: Method = Method.Defined.NotificationsProgress
}
/**
* Parameters for a notifications/progress notification.
*
* @property progressToken The progress token which was given in the initial request,
* used to associate this notification with the request that is proceeding.
* @property progress The progress thus far. This should increase every time progress is made,
* even if the total is unknown.
* @property total Total number of items to process (or total progress required), if known.
* @property message An optional message describing the current progress.
* @property meta Optional metadata for this notification.
*/
@Serializable
public data class ProgressNotificationParams(
val progressToken: ProgressToken,
val progress: Double,
val total: Double? = null,
val message: String? = null,
@SerialName("_meta")
override val meta: JsonObject? = null,
) : NotificationParams
// ============================================================================
// Prompts List Changed Notification
// ============================================================================
/**
* An optional notification from the server to the client, informing it that the list of prompts it offers has changed.
*
* Servers may issue this without any previous subscription from the client.
* Sent only if the server's [ServerCapabilities.prompts] has `listChanged = true`.
*
* @property params Optional notification parameters containing metadata.
*/
@Serializable
public data class PromptListChangedNotification(override val params: BaseNotificationParams? = null) :
ServerNotification {
@EncodeDefault
override val method: Method = Method.Defined.NotificationsPromptsListChanged
}
// ============================================================================
// Resources List Changed Notification
// ============================================================================
/**
* An optional notification from the server to the client, informing it that the list of resources it can read from has changed.
*
* Servers may issue this without any previous subscription from the client.
* Sent only if the server's [ServerCapabilities.resources] has `listChanged = true`.
*
* @property params Optional notification parameters containing metadata.
*/
@Serializable
public data class ResourceListChangedNotification(override val params: BaseNotificationParams? = null) :
ServerNotification {
@EncodeDefault
override val method: Method = Method.Defined.NotificationsResourcesListChanged
}
// ============================================================================
// Resource Updated Notification
// ============================================================================
/**
* A notification from the server to the client, informing it that a resource has changed and may need to be read again.
*
* This should only be sent if the client previously sent a resources/subscribe request
* and the server's [ServerCapabilities.resources] has `subscribe = true`.
*
* @property params Parameters identifying which resource was updated.
*/
@Serializable
public data class ResourceUpdatedNotification(override val params: ResourceUpdatedNotificationParams) :
ServerNotification {
@EncodeDefault
override val method: Method = Method.Defined.NotificationsResourcesUpdated
}
/**
* Parameters for a notifications/resources/updated notification.
*
* @property uri The URI of the resource that has been updated.
* This might be a sub-resource of the one that the client actually subscribed to.
* @property meta Optional metadata for this notification.
*/
@Serializable
public data class ResourceUpdatedNotificationParams(
val uri: String,
@SerialName("_meta")
override val meta: JsonObject? = null,
) : NotificationParams
// ============================================================================
// Roots List Changed Notification
// ============================================================================
/**
* A notification from the client to the server, informing it that the list of roots has changed.
*
* This notification should be sent whenever the client adds, removes, or modifies any root.
* The server should then request an updated list of roots using the ListRootsRequest.
* Sent only if the client's [ClientCapabilities.roots] has `listChanged = true`.
*
* @property params Optional notification parameters containing metadata.
*/
@Serializable
public data class RootsListChangedNotification(override val params: BaseNotificationParams? = null) :
ClientNotification {
@EncodeDefault
override val method: Method = Method.Defined.NotificationsRootsListChanged
}
// ============================================================================
// Tools List Changed Notification
// ============================================================================
/**
* An optional notification from the server to the client, informing it that the list of tools it offers has changed.
*
* Servers may issue this without any previous subscription from the client.
* Sent only if the server's [ServerCapabilities.tools] has `listChanged = true`.
*
* @property params Optional notification parameters containing metadata.
*/
@Serializable
public data class ToolListChangedNotification(override val params: BaseNotificationParams? = null) :
ServerNotification {
@EncodeDefault
override val method: Method = Method.Defined.NotificationsToolsListChanged
}

Some files were not shown because too many files have changed in this diff Show more