From 7068ce413803cd290cce4b0b79aa15493a29921d Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Mon, 11 May 2026 12:11:13 +0200 Subject: [PATCH 01/27] feat(mcp-client): split core/server modules --- build.sbt | 20 ++++++++++++++----- .../src/main/scala/chimp/AdderMcpZio.scala | 1 + examples/src/main/scala/chimp/adderMcp.scala | 1 + .../main/scala/chimp/adderWithAuthMcp.scala | 1 + .../src/main/scala/chimp/twoToolsMcp.scala | 1 + .../src/main/scala/chimp/weatherMcp.scala | 2 +- .../main/scala/chimp/server}/McpHandler.scala | 2 +- .../scala/chimp/server}/mcpEndpoint.scala | 2 +- .../src/main/scala/chimp/server}/tool.scala | 2 +- .../scala/chimp/server}/McpHandlerSpec.scala | 2 +- 10 files changed, 24 insertions(+), 10 deletions(-) rename {core/src/main/scala/chimp => server/src/main/scala/chimp/server}/McpHandler.scala (99%) rename {core/src/main/scala/chimp => server/src/main/scala/chimp/server}/mcpEndpoint.scala (98%) rename {core/src/main/scala/chimp => server/src/main/scala/chimp/server}/tool.scala (99%) rename {core/src/test/scala/chimp => server/src/test/scala/chimp/server}/McpHandlerSpec.scala (99%) diff --git a/build.sbt b/build.sbt index dcc2607..301e721 100644 --- a/build.sbt +++ b/build.sbt @@ -27,24 +27,34 @@ val scalaTest = "org.scalatest" %% "scalatest" % scalaTestV % Test lazy val rootProject = (project in file(".")) .settings(commonSettings: _*) .settings(publishArtifact := false, name := "chimp") - .aggregate(core, examples) + .aggregate(core, server, examples) lazy val core: Project = (project in file("core")) .settings(commonSettings: _*) .settings( - name := "core", + name := "chimp-core", libraryDependencies ++= Seq( scalaTest, "io.circe" %% "circe-core" % circeV, "io.circe" %% "circe-generic" % circeV, "io.circe" %% "circe-parser" % circeV, + "org.slf4j" % "slf4j-api" % "2.0.17" + ) + ) + +lazy val server: Project = (project in file("server")) + .settings(commonSettings: _*) + .settings( + name := "chimp-server", + libraryDependencies ++= Seq( + scalaTest, "com.softwaremill.sttp.tapir" %% "tapir-core" % tapirV, "com.softwaremill.sttp.tapir" %% "tapir-json-circe" % tapirV, "com.softwaremill.sttp.tapir" %% "tapir-apispec-docs" % tapirV, - "com.softwaremill.sttp.apispec" %% "jsonschema-circe" % "0.11.10", - "org.slf4j" % "slf4j-api" % "2.0.18" + "com.softwaremill.sttp.apispec" %% "jsonschema-circe" % "0.11.10" ) ) + .dependsOn(core) lazy val examples = (project in file("examples")) .settings(commonSettings: _*) @@ -59,4 +69,4 @@ lazy val examples = (project in file("examples")) ), verifyExamplesCompileUsingScalaCli := VerifyExamplesCompileUsingScalaCli(sLog.value, sourceDirectory.value) ) - .dependsOn(core) + .dependsOn(server) diff --git a/examples/src/main/scala/chimp/AdderMcpZio.scala b/examples/src/main/scala/chimp/AdderMcpZio.scala index c371329..b5e7cb9 100644 --- a/examples/src/main/scala/chimp/AdderMcpZio.scala +++ b/examples/src/main/scala/chimp/AdderMcpZio.scala @@ -4,6 +4,7 @@ package chimp +import chimp.server.* import io.circe.Codec import sttp.tapir.* import sttp.tapir.server.ziohttp.ZioHttpInterpreter diff --git a/examples/src/main/scala/chimp/adderMcp.scala b/examples/src/main/scala/chimp/adderMcp.scala index 7849a86..880a261 100644 --- a/examples/src/main/scala/chimp/adderMcp.scala +++ b/examples/src/main/scala/chimp/adderMcp.scala @@ -4,6 +4,7 @@ package chimp +import chimp.server.* import io.circe.Codec import sttp.tapir.* import sttp.tapir.server.netty.sync.NettySyncServer diff --git a/examples/src/main/scala/chimp/adderWithAuthMcp.scala b/examples/src/main/scala/chimp/adderWithAuthMcp.scala index ea93697..5f6b0fb 100644 --- a/examples/src/main/scala/chimp/adderWithAuthMcp.scala +++ b/examples/src/main/scala/chimp/adderWithAuthMcp.scala @@ -4,6 +4,7 @@ package chimp +import chimp.server.* import io.circe.Codec import sttp.model.Header import sttp.tapir.* diff --git a/examples/src/main/scala/chimp/twoToolsMcp.scala b/examples/src/main/scala/chimp/twoToolsMcp.scala index f1aa04e..b066d10 100644 --- a/examples/src/main/scala/chimp/twoToolsMcp.scala +++ b/examples/src/main/scala/chimp/twoToolsMcp.scala @@ -4,6 +4,7 @@ package chimp +import chimp.server.* import io.circe.Codec import sttp.tapir.* import sttp.tapir.server.netty.sync.NettySyncServer diff --git a/examples/src/main/scala/chimp/weatherMcp.scala b/examples/src/main/scala/chimp/weatherMcp.scala index 08a8b8e..27663e2 100644 --- a/examples/src/main/scala/chimp/weatherMcp.scala +++ b/examples/src/main/scala/chimp/weatherMcp.scala @@ -5,7 +5,7 @@ package chimp -import chimp.* +import chimp.server.* import io.circe.Codec import io.circe.parser.decode import ox.either diff --git a/core/src/main/scala/chimp/McpHandler.scala b/server/src/main/scala/chimp/server/McpHandler.scala similarity index 99% rename from core/src/main/scala/chimp/McpHandler.scala rename to server/src/main/scala/chimp/server/McpHandler.scala index 1406ebb..3a378ac 100644 --- a/core/src/main/scala/chimp/McpHandler.scala +++ b/server/src/main/scala/chimp/server/McpHandler.scala @@ -1,4 +1,4 @@ -package chimp +package chimp.server import chimp.protocol.* import io.circe.* diff --git a/core/src/main/scala/chimp/mcpEndpoint.scala b/server/src/main/scala/chimp/server/mcpEndpoint.scala similarity index 98% rename from core/src/main/scala/chimp/mcpEndpoint.scala rename to server/src/main/scala/chimp/server/mcpEndpoint.scala index 7252873..caef462 100644 --- a/core/src/main/scala/chimp/mcpEndpoint.scala +++ b/server/src/main/scala/chimp/server/mcpEndpoint.scala @@ -1,4 +1,4 @@ -package chimp +package chimp.server import io.circe.Json import org.slf4j.LoggerFactory diff --git a/core/src/main/scala/chimp/tool.scala b/server/src/main/scala/chimp/server/tool.scala similarity index 99% rename from core/src/main/scala/chimp/tool.scala rename to server/src/main/scala/chimp/server/tool.scala index 3ad1f47..9a580ce 100644 --- a/core/src/main/scala/chimp/tool.scala +++ b/server/src/main/scala/chimp/server/tool.scala @@ -1,4 +1,4 @@ -package chimp +package chimp.server import sttp.tapir.Schema import io.circe.Decoder diff --git a/core/src/test/scala/chimp/McpHandlerSpec.scala b/server/src/test/scala/chimp/server/McpHandlerSpec.scala similarity index 99% rename from core/src/test/scala/chimp/McpHandlerSpec.scala rename to server/src/test/scala/chimp/server/McpHandlerSpec.scala index 2e9fa98..c6225d3 100644 --- a/core/src/test/scala/chimp/McpHandlerSpec.scala +++ b/server/src/test/scala/chimp/server/McpHandlerSpec.scala @@ -1,4 +1,4 @@ -package chimp +package chimp.server import chimp.protocol.* import chimp.protocol.JSONRPCMessage.given From 73d7cc6ac62ba90f9af86611260481dff1d512e4 Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Mon, 11 May 2026 12:29:20 +0200 Subject: [PATCH 02/27] feat: define protocol in shared core project using latest version MCP 2025-11-25 --- .../scala/chimp/protocol/Cancellation.scala | 11 + .../scala/chimp/protocol/Completion.scala | 24 ++ .../scala/chimp/protocol/Elicitation.scala | 41 ++ core/src/main/scala/chimp/protocol/Ids.scala | 27 ++ .../main/scala/chimp/protocol/JsonRpc.scala | 67 +++ .../main/scala/chimp/protocol/Lifecycle.scala | 48 +++ .../main/scala/chimp/protocol/Logging.scala | 36 ++ .../main/scala/chimp/protocol/Progress.scala | 13 + .../main/scala/chimp/protocol/Prompts.scala | 56 +++ .../chimp/protocol/ProtocolVersion.scala | 9 + .../main/scala/chimp/protocol/Resources.scala | 105 +++++ .../src/main/scala/chimp/protocol/Roots.scala | 18 + .../main/scala/chimp/protocol/Sampling.scala | 50 +++ .../src/main/scala/chimp/protocol/Tools.scala | 123 ++++++ .../src/main/scala/chimp/protocol/model.scala | 385 ------------------ 15 files changed, 628 insertions(+), 385 deletions(-) create mode 100644 core/src/main/scala/chimp/protocol/Cancellation.scala create mode 100644 core/src/main/scala/chimp/protocol/Completion.scala create mode 100644 core/src/main/scala/chimp/protocol/Elicitation.scala create mode 100644 core/src/main/scala/chimp/protocol/Ids.scala create mode 100644 core/src/main/scala/chimp/protocol/JsonRpc.scala create mode 100644 core/src/main/scala/chimp/protocol/Lifecycle.scala create mode 100644 core/src/main/scala/chimp/protocol/Logging.scala create mode 100644 core/src/main/scala/chimp/protocol/Progress.scala create mode 100644 core/src/main/scala/chimp/protocol/Prompts.scala create mode 100644 core/src/main/scala/chimp/protocol/ProtocolVersion.scala create mode 100644 core/src/main/scala/chimp/protocol/Resources.scala create mode 100644 core/src/main/scala/chimp/protocol/Roots.scala create mode 100644 core/src/main/scala/chimp/protocol/Sampling.scala create mode 100644 core/src/main/scala/chimp/protocol/Tools.scala delete mode 100644 core/src/main/scala/chimp/protocol/model.scala diff --git a/core/src/main/scala/chimp/protocol/Cancellation.scala b/core/src/main/scala/chimp/protocol/Cancellation.scala new file mode 100644 index 0000000..4c5bba1 --- /dev/null +++ b/core/src/main/scala/chimp/protocol/Cancellation.scala @@ -0,0 +1,11 @@ +package chimp.protocol + +import io.circe.{Codec, Json} + +final case class CancelledParams( + requestId: RequestId, + reason: Option[String] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class CancelledNotification(method: String = "notifications/cancelled", params: CancelledParams) derives Codec diff --git a/core/src/main/scala/chimp/protocol/Completion.scala b/core/src/main/scala/chimp/protocol/Completion.scala new file mode 100644 index 0000000..9ae661e --- /dev/null +++ b/core/src/main/scala/chimp/protocol/Completion.scala @@ -0,0 +1,24 @@ +package chimp.protocol + +import io.circe.{Codec, Json} + +enum CompleteRef derives Codec: + case Prompt(prompt: PromptReference) + case Resource(resource: ResourceReference) + +final case class CompleteArgument(name: String, value: String) derives Codec + +final case class CompleteContext(arguments: Option[Map[String, String]] = None) derives Codec + +final case class CompleteParams( + ref: CompleteRef, + argument: CompleteArgument, + context: Option[CompleteContext] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class CompleteRequest(method: String = "completion/complete", params: CompleteParams) derives Codec + +final case class Completion(values: List[String], total: Option[Int] = None, hasMore: Option[Boolean] = None) derives Codec + +final case class CompleteResult(completion: Completion, _meta: Option[Map[String, Json]] = None) derives Codec diff --git a/core/src/main/scala/chimp/protocol/Elicitation.scala b/core/src/main/scala/chimp/protocol/Elicitation.scala new file mode 100644 index 0000000..e42cba1 --- /dev/null +++ b/core/src/main/scala/chimp/protocol/Elicitation.scala @@ -0,0 +1,41 @@ +package chimp.protocol + +import io.circe.{Codec, Decoder, Encoder, Json} + +enum ElicitAction: + case Accept, Decline, Cancel + +object ElicitAction: + given Encoder[ElicitAction] = Encoder.instance: + case ElicitAction.Accept => Json.fromString("accept") + case ElicitAction.Decline => Json.fromString("decline") + case ElicitAction.Cancel => Json.fromString("cancel") + given Decoder[ElicitAction] = Decoder.decodeString.emap: + case "accept" => Right(ElicitAction.Accept) + case "decline" => Right(ElicitAction.Decline) + case "cancel" => Right(ElicitAction.Cancel) + case other => Left(s"Unknown elicitation action: $other") + +final case class ElicitParams( + message: String, + requestedSchema: Json, + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class ElicitRequest(method: String = "elicitation/create", params: ElicitParams) derives Codec + +final case class ElicitResult( + action: ElicitAction, + content: Option[Map[String, Json]] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec + +object Elicitation: + def applyDefaults(requestedSchema: Json, provided: Map[String, Json]): Map[String, Json] = + val propsOpt = requestedSchema.hcursor.downField("properties").focus.flatMap(_.asObject) + propsOpt match + case None => provided + case Some(props) => + val withDefaults = props.toMap.flatMap: (key, schema) => + schema.hcursor.downField("default").focus.map(d => key -> d) + withDefaults ++ provided diff --git a/core/src/main/scala/chimp/protocol/Ids.scala b/core/src/main/scala/chimp/protocol/Ids.scala new file mode 100644 index 0000000..13803dc --- /dev/null +++ b/core/src/main/scala/chimp/protocol/Ids.scala @@ -0,0 +1,27 @@ +package chimp.protocol + +import io.circe.{Codec, Decoder, Encoder, Json} + +opaque type RequestId = String | Int +object RequestId: + def apply(value: String | Int): RequestId = value + def unapply(id: RequestId): Option[String | Int] = Some(id) + given encoder: Encoder[RequestId] = Encoder.instance: + case s: String => Json.fromString(s) + case i: Int => Json.fromInt(i) + given decoder: Decoder[RequestId] = Decoder.instance: c => + c.as[String].map(RequestId(_)).orElse(c.as[Int].map(RequestId(_))) + given codec: Codec[RequestId] = Codec.from(decoder, encoder) + +opaque type ProgressToken = String | Int +object ProgressToken: + def apply(value: String | Int): ProgressToken = value + def unapply(token: ProgressToken): Option[String | Int] = Some(token) + given encoder: Encoder[ProgressToken] = Encoder.instance: + case s: String => Json.fromString(s) + case i: Int => Json.fromInt(i) + given decoder: Decoder[ProgressToken] = Decoder.instance: c => + c.as[String].map(ProgressToken(_)).orElse(c.as[Int].map(ProgressToken(_))) + given codec: Codec[ProgressToken] = Codec.from(decoder, encoder) + +type Cursor = String diff --git a/core/src/main/scala/chimp/protocol/JsonRpc.scala b/core/src/main/scala/chimp/protocol/JsonRpc.scala new file mode 100644 index 0000000..616bf87 --- /dev/null +++ b/core/src/main/scala/chimp/protocol/JsonRpc.scala @@ -0,0 +1,67 @@ +package chimp.protocol + +import io.circe.syntax.* +import io.circe.{Codec, Decoder, DecodingFailure, Encoder, Json} + +enum JSONRPCMessage: + case Request(jsonrpc: String = "2.0", method: String, params: Option[Json] = None, id: RequestId) + case Notification(jsonrpc: String = "2.0", method: String, params: Option[Json] = None) + case Response(jsonrpc: String = "2.0", id: RequestId, result: Json) + case Error(jsonrpc: String = "2.0", id: RequestId, error: JSONRPCErrorObject) + +object JSONRPCMessage: + + given Decoder[JSONRPCMessage] = Decoder.instance: c => + val jsonrpc = c.downField("jsonrpc").as[String].getOrElse("2.0") + val methodOpt = c.downField("method").as[String].toOption + val idOpt = c.downField("id").as[RequestId].toOption + val paramsOpt = c.downField("params").focus + val resultOpt = c.downField("result").focus + val errorOpt = c.downField("error").as[JSONRPCErrorObject].toOption + + (methodOpt, idOpt, resultOpt, errorOpt) match + case (Some(method), Some(id), None, None) => Right(Request(jsonrpc, method, paramsOpt, id)) + case (Some(method), None, None, None) => Right(Notification(jsonrpc, method, paramsOpt)) + case (None, Some(id), Some(result), None) => Right(Response(jsonrpc, id, result)) + case (None, Some(id), None, Some(error)) => Right(Error(jsonrpc, id, error)) + case _ => Left(DecodingFailure("type JSONRPCMessage could not be decoded from JSON", c.history)) + + given Encoder[JSONRPCMessage] = Encoder.instance: + case Request(jsonrpc, method, params, id) => + Json + .obj( + "jsonrpc" -> Json.fromString(jsonrpc), + "method" -> Json.fromString(method), + "params" -> params.getOrElse(Json.Null), + "id" -> id.asJson + ) + .dropNullValues + case Notification(jsonrpc, method, params) => + Json + .obj( + "jsonrpc" -> Json.fromString(jsonrpc), + "method" -> Json.fromString(method), + "params" -> params.getOrElse(Json.Null) + ) + .dropNullValues + case Response(jsonrpc, id, result) => + Json.obj( + "jsonrpc" -> Json.fromString(jsonrpc), + "id" -> id.asJson, + "result" -> result + ) + case Error(jsonrpc, id, error) => + Json.obj( + "jsonrpc" -> Json.fromString(jsonrpc), + "id" -> id.asJson, + "error" -> error.asJson + ) + +final case class JSONRPCErrorObject(code: Int, message: String, data: Option[Json] = None) derives Codec + +enum JSONRPCErrorCodes(val code: Int): + case ParseError extends JSONRPCErrorCodes(-32700) + case InvalidRequest extends JSONRPCErrorCodes(-32600) + case MethodNotFound extends JSONRPCErrorCodes(-32601) + case InvalidParams extends JSONRPCErrorCodes(-32602) + case InternalError extends JSONRPCErrorCodes(-32603) diff --git a/core/src/main/scala/chimp/protocol/Lifecycle.scala b/core/src/main/scala/chimp/protocol/Lifecycle.scala new file mode 100644 index 0000000..f014907 --- /dev/null +++ b/core/src/main/scala/chimp/protocol/Lifecycle.scala @@ -0,0 +1,48 @@ +package chimp.protocol + +import io.circe.{Codec, Json} + +final case class Implementation(name: String, version: String, title: Option[String] = None) derives Codec + +final case class ClientRootsCapability(listChanged: Option[Boolean] = None) derives Codec + +final case class ClientCapabilities( + experimental: Option[Map[String, Json]] = None, + roots: Option[ClientRootsCapability] = None, + sampling: Option[Json] = None, + elicitation: Option[Json] = None +) derives Codec + +final case class ServerPromptsCapability(listChanged: Option[Boolean] = None) derives Codec +final case class ServerResourcesCapability(subscribe: Option[Boolean] = None, listChanged: Option[Boolean] = None) derives Codec +final case class ServerToolsCapability(listChanged: Option[Boolean] = None) derives Codec + +final case class ServerCapabilities( + experimental: Option[Map[String, Json]] = None, + logging: Option[Json] = None, + completions: Option[Json] = None, + prompts: Option[ServerPromptsCapability] = None, + resources: Option[ServerResourcesCapability] = None, + tools: Option[ServerToolsCapability] = None +) derives Codec + +final case class InitializeParams( + protocolVersion: String, + capabilities: ClientCapabilities, + clientInfo: Implementation, + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class InitializeRequest(method: String = "initialize", params: InitializeParams) derives Codec + +final case class InitializeResult( + protocolVersion: String, + capabilities: ServerCapabilities, + serverInfo: Implementation, + instructions: Option[String] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class InitializedNotification(method: String = "notifications/initialized") derives Codec + +final case class PingRequest(method: String = "ping") derives Codec diff --git a/core/src/main/scala/chimp/protocol/Logging.scala b/core/src/main/scala/chimp/protocol/Logging.scala new file mode 100644 index 0000000..2aa93d6 --- /dev/null +++ b/core/src/main/scala/chimp/protocol/Logging.scala @@ -0,0 +1,36 @@ +package chimp.protocol + +import io.circe.{Codec, Decoder, Encoder, Json} + +enum LoggingLevel: + case Debug, Info, Notice, Warning, Error, Critical, Alert, Emergency + +object LoggingLevel: + given Encoder[LoggingLevel] = Encoder.instance: l => + Json.fromString(l.toString.toLowerCase) + given Decoder[LoggingLevel] = Decoder.decodeString.emap: + case "debug" => Right(LoggingLevel.Debug) + case "info" => Right(LoggingLevel.Info) + case "notice" => Right(LoggingLevel.Notice) + case "warning" => Right(LoggingLevel.Warning) + case "error" => Right(LoggingLevel.Error) + case "critical" => Right(LoggingLevel.Critical) + case "alert" => Right(LoggingLevel.Alert) + case "emergency" => Right(LoggingLevel.Emergency) + case other => Left(s"Unknown logging level: $other") + +final case class SetLevelParams(level: LoggingLevel, _meta: Option[Map[String, Json]] = None) derives Codec + +final case class SetLevelRequest(method: String = "logging/setLevel", params: SetLevelParams) derives Codec + +final case class LoggingMessageParams( + level: LoggingLevel, + data: Json, + logger: Option[String] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class LoggingMessageNotification( + method: String = "notifications/message", + params: LoggingMessageParams +) derives Codec diff --git a/core/src/main/scala/chimp/protocol/Progress.scala b/core/src/main/scala/chimp/protocol/Progress.scala new file mode 100644 index 0000000..ffaea36 --- /dev/null +++ b/core/src/main/scala/chimp/protocol/Progress.scala @@ -0,0 +1,13 @@ +package chimp.protocol + +import io.circe.{Codec, Json} + +final case class ProgressParams( + progressToken: ProgressToken, + progress: Double, + total: Option[Double] = None, + message: Option[String] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class ProgressNotification(method: String = "notifications/progress", params: ProgressParams) derives Codec diff --git a/core/src/main/scala/chimp/protocol/Prompts.scala b/core/src/main/scala/chimp/protocol/Prompts.scala new file mode 100644 index 0000000..f83e00f --- /dev/null +++ b/core/src/main/scala/chimp/protocol/Prompts.scala @@ -0,0 +1,56 @@ +package chimp.protocol + +import io.circe.{Codec, Decoder, DecodingFailure, Encoder, Json} + +enum Role: + case User, Assistant + +object Role: + given Encoder[Role] = Encoder.instance: + case Role.User => Json.fromString("user") + case Role.Assistant => Json.fromString("assistant") + given Decoder[Role] = Decoder.decodeString.emap: + case "user" => Right(Role.User) + case "assistant" => Right(Role.Assistant) + case other => Left(s"Unknown role: $other") + +final case class PromptArgument( + name: String, + description: Option[String] = None, + required: Option[Boolean] = None, + title: Option[String] = None +) derives Codec + +final case class Prompt( + name: String, + title: Option[String] = None, + description: Option[String] = None, + arguments: Option[List[PromptArgument]] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class PromptMessage(role: Role, content: ToolContent) derives Codec + +final case class ListPromptsParams(cursor: Option[Cursor] = None, _meta: Option[Map[String, Json]] = None) derives Codec +final case class ListPromptsRequest(method: String = "prompts/list", params: Option[ListPromptsParams] = None) derives Codec +final case class ListPromptsResult( + prompts: List[Prompt], + nextCursor: Option[String] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class GetPromptParams( + name: String, + arguments: Option[Map[String, String]] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec +final case class GetPromptRequest(method: String = "prompts/get", params: GetPromptParams) derives Codec +final case class GetPromptResult( + messages: List[PromptMessage], + description: Option[String] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class PromptListChangedNotification(method: String = "notifications/prompts/list_changed") derives Codec + +final case class PromptReference(`type`: String = "ref/prompt", name: String) derives Codec diff --git a/core/src/main/scala/chimp/protocol/ProtocolVersion.scala b/core/src/main/scala/chimp/protocol/ProtocolVersion.scala new file mode 100644 index 0000000..612a63b --- /dev/null +++ b/core/src/main/scala/chimp/protocol/ProtocolVersion.scala @@ -0,0 +1,9 @@ +package chimp.protocol + +object ProtocolVersion: + val Latest: String = "2025-11-25" + + val Supported: Set[String] = Set("2025-06-18", "2025-11-25") + + def negotiate(requested: String): String = + if Supported.contains(requested) then requested else Latest diff --git a/core/src/main/scala/chimp/protocol/Resources.scala b/core/src/main/scala/chimp/protocol/Resources.scala new file mode 100644 index 0000000..7b45b61 --- /dev/null +++ b/core/src/main/scala/chimp/protocol/Resources.scala @@ -0,0 +1,105 @@ +package chimp.protocol + +import io.circe.syntax.* +import io.circe.{Codec, Decoder, DecodingFailure, Encoder, HCursor, Json} + +final case class Resource( + uri: String, + name: String, + title: Option[String] = None, + description: Option[String] = None, + mimeType: Option[String] = None, + size: Option[Long] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class ResourceTemplate( + uriTemplate: String, + name: String, + title: Option[String] = None, + description: Option[String] = None, + mimeType: Option[String] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec + +enum ResourceContents: + case Text(uri: String, text: String, mimeType: Option[String] = None, _meta: Option[Map[String, Json]] = None) + case Blob(uri: String, blob: String, mimeType: Option[String] = None, _meta: Option[Map[String, Json]] = None) + +object ResourceContents: + given Encoder[ResourceContents] = Encoder.instance: + case Text(uri, text, mimeType, meta) => + Json + .obj( + "uri" -> Json.fromString(uri), + "text" -> Json.fromString(text), + "mimeType" -> mimeType.map(Json.fromString).getOrElse(Json.Null), + "_meta" -> meta.map(_.asJson).getOrElse(Json.Null) + ) + .dropNullValues + case Blob(uri, blob, mimeType, meta) => + Json + .obj( + "uri" -> Json.fromString(uri), + "blob" -> Json.fromString(blob), + "mimeType" -> mimeType.map(Json.fromString).getOrElse(Json.Null), + "_meta" -> meta.map(_.asJson).getOrElse(Json.Null) + ) + .dropNullValues + + given Decoder[ResourceContents] = Decoder.instance: (c: HCursor) => + val uri = c.downField("uri").as[String] + val mimeType = c.downField("mimeType").as[Option[String]] + val meta = c.downField("_meta").as[Option[Map[String, Json]]] + val textOpt = c.downField("text").as[Option[String]] + val blobOpt = c.downField("blob").as[Option[String]] + for + u <- uri + mt <- mimeType + m <- meta + t <- textOpt + b <- blobOpt + r <- (t, b) match + case (Some(text), None) => Right(Text(u, text, mt, m)) + case (None, Some(blob)) => Right(Blob(u, blob, mt, m)) + case _ => Left(DecodingFailure("ResourceContents must have exactly one of 'text' or 'blob'", c.history)) + yield r + +final case class ListResourcesParams(cursor: Option[Cursor] = None, _meta: Option[Map[String, Json]] = None) derives Codec +final case class ListResourcesRequest(method: String = "resources/list", params: Option[ListResourcesParams] = None) derives Codec +final case class ListResourcesResult( + resources: List[Resource], + nextCursor: Option[String] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class ListResourceTemplatesParams(cursor: Option[Cursor] = None, _meta: Option[Map[String, Json]] = None) derives Codec +final case class ListResourceTemplatesRequest( + method: String = "resources/templates/list", + params: Option[ListResourceTemplatesParams] = None +) derives Codec +final case class ListResourceTemplatesResult( + resourceTemplates: List[ResourceTemplate], + nextCursor: Option[String] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class ReadResourceParams(uri: String, _meta: Option[Map[String, Json]] = None) derives Codec +final case class ReadResourceRequest(method: String = "resources/read", params: ReadResourceParams) derives Codec +final case class ReadResourceResult(contents: List[ResourceContents], _meta: Option[Map[String, Json]] = None) derives Codec + +final case class SubscribeParams(uri: String, _meta: Option[Map[String, Json]] = None) derives Codec +final case class SubscribeRequest(method: String = "resources/subscribe", params: SubscribeParams) derives Codec + +final case class UnsubscribeParams(uri: String, _meta: Option[Map[String, Json]] = None) derives Codec +final case class UnsubscribeRequest(method: String = "resources/unsubscribe", params: UnsubscribeParams) derives Codec + +final case class ResourceUpdatedParams(uri: String, _meta: Option[Map[String, Json]] = None) derives Codec +final case class ResourceUpdatedNotification( + method: String = "notifications/resources/updated", + params: ResourceUpdatedParams +) derives Codec + +final case class ResourceListChangedNotification(method: String = "notifications/resources/list_changed") derives Codec + +final case class ResourceReference(`type`: String = "ref/resource", uri: String) derives Codec diff --git a/core/src/main/scala/chimp/protocol/Roots.scala b/core/src/main/scala/chimp/protocol/Roots.scala new file mode 100644 index 0000000..c8a69a8 --- /dev/null +++ b/core/src/main/scala/chimp/protocol/Roots.scala @@ -0,0 +1,18 @@ +package chimp.protocol + +import io.circe.{Codec, Json} + +final case class Root( + uri: String, + name: Option[String] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class ListRootsRequest(method: String = "roots/list") derives Codec + +final case class ListRootsResult( + roots: List[Root], + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class RootsListChangedNotification(method: String = "notifications/roots/list_changed") derives Codec diff --git a/core/src/main/scala/chimp/protocol/Sampling.scala b/core/src/main/scala/chimp/protocol/Sampling.scala new file mode 100644 index 0000000..1c8efc2 --- /dev/null +++ b/core/src/main/scala/chimp/protocol/Sampling.scala @@ -0,0 +1,50 @@ +package chimp.protocol + +import io.circe.{Codec, Decoder, Encoder, Json} + +final case class ModelHint(name: Option[String] = None) derives Codec + +final case class ModelPreferences( + hints: Option[List[ModelHint]] = None, + costPriority: Option[Double] = None, + speedPriority: Option[Double] = None, + intelligencePriority: Option[Double] = None +) derives Codec + +enum IncludeContext: + case None, ThisServer, AllServers + +object IncludeContext: + given Encoder[IncludeContext] = Encoder.instance: + case IncludeContext.None => Json.fromString("none") + case IncludeContext.ThisServer => Json.fromString("thisServer") + case IncludeContext.AllServers => Json.fromString("allServers") + given Decoder[IncludeContext] = Decoder.decodeString.emap: + case "none" => Right(IncludeContext.None) + case "thisServer" => Right(IncludeContext.ThisServer) + case "allServers" => Right(IncludeContext.AllServers) + case other => Left(s"Unknown includeContext: $other") + +final case class SamplingMessage(role: Role, content: ToolContent) derives Codec + +final case class CreateMessageParams( + messages: List[SamplingMessage], + maxTokens: Int, + modelPreferences: Option[ModelPreferences] = None, + systemPrompt: Option[String] = None, + includeContext: Option[IncludeContext] = None, + temperature: Option[Double] = None, + stopSequences: Option[List[String]] = None, + metadata: Option[Map[String, Json]] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class CreateMessageRequest(method: String = "sampling/createMessage", params: CreateMessageParams) derives Codec + +final case class CreateMessageResult( + role: Role, + content: ToolContent, + model: String, + stopReason: Option[String] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec diff --git a/core/src/main/scala/chimp/protocol/Tools.scala b/core/src/main/scala/chimp/protocol/Tools.scala new file mode 100644 index 0000000..0c7ef8f --- /dev/null +++ b/core/src/main/scala/chimp/protocol/Tools.scala @@ -0,0 +1,123 @@ +package chimp.protocol + +import io.circe.syntax.* +import io.circe.{Codec, Decoder, DecodingFailure, Encoder, HCursor, Json} + +final case class ToolAnnotations( + title: Option[String] = None, + readOnlyHint: Option[Boolean] = None, + destructiveHint: Option[Boolean] = None, + idempotentHint: Option[Boolean] = None, + openWorldHint: Option[Boolean] = None +) derives Codec + +final case class ToolDefinition( + name: String, + description: Option[String] = None, + inputSchema: Json, + outputSchema: Option[Json] = None, + title: Option[String] = None, + annotations: Option[ToolAnnotations] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class ListToolsParams(cursor: Option[Cursor] = None, _meta: Option[Map[String, Json]] = None) derives Codec + +final case class ListToolsRequest(method: String = "tools/list", params: Option[ListToolsParams] = None) derives Codec + +final case class ListToolsResponse( + tools: List[ToolDefinition], + nextCursor: Option[String] = None, + _meta: Option[Map[String, Json]] = None +) derives Codec + +enum ToolContent: + case Text(`type`: String = "text", text: String) + case Image(`type`: String = "image", data: String, mimeType: String) + case Audio(`type`: String = "audio", data: String, mimeType: String) + case ResourceContent(`type`: String = "resource", resource: ResourceContents) + case ResourceLink( + `type`: String = "resource_link", + uri: String, + name: Option[String] = None, + description: Option[String] = None, + mimeType: Option[String] = None + ) + +object ToolContent: + given Encoder[ToolContent] = Encoder.instance: + case Text(_, text) => + Json.obj( + "type" -> Json.fromString("text"), + "text" -> Json.fromString(text) + ) + case Image(_, data, mimeType) => + Json.obj( + "type" -> Json.fromString("image"), + "data" -> Json.fromString(data), + "mimeType" -> Json.fromString(mimeType) + ) + case Audio(_, data, mimeType) => + Json.obj( + "type" -> Json.fromString("audio"), + "data" -> Json.fromString(data), + "mimeType" -> Json.fromString(mimeType) + ) + case ResourceContent(_, resource) => + Json.obj( + "type" -> Json.fromString("resource"), + "resource" -> resource.asJson + ) + case ResourceLink(_, uri, name, description, mimeType) => + Json + .obj( + "type" -> Json.fromString("resource_link"), + "uri" -> Json.fromString(uri), + "name" -> name.map(Json.fromString).getOrElse(Json.Null), + "description" -> description.map(Json.fromString).getOrElse(Json.Null), + "mimeType" -> mimeType.map(Json.fromString).getOrElse(Json.Null) + ) + .dropNullValues + + given Decoder[ToolContent] = Decoder.instance: (c: HCursor) => + c.downField("type").as[String].flatMap: + case "text" => + c.downField("text").as[String].map(Text("text", _)) + case "image" => + for + data <- c.downField("data").as[String] + mimeType <- c.downField("mimeType").as[String] + yield Image("image", data, mimeType) + case "audio" => + for + data <- c.downField("data").as[String] + mimeType <- c.downField("mimeType").as[String] + yield Audio("audio", data, mimeType) + case "resource" => + c.downField("resource").as[ResourceContents].map(ResourceContent("resource", _)) + case "resource_link" => + for + uri <- c.downField("uri").as[String] + name <- c.downField("name").as[Option[String]] + description <- c.downField("description").as[Option[String]] + mimeType <- c.downField("mimeType").as[Option[String]] + yield ResourceLink("resource_link", uri, name, description, mimeType) + case other => + Left(DecodingFailure(s"Unknown ToolContent type: $other", c.history)) + +final case class CallToolParams( + name: String, + arguments: Json, + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class CallToolRequest(method: String = "tools/call", params: CallToolParams) derives Codec + +final case class CallToolResult( + content: List[ToolContent], + structuredContent: Option[Json] = None, + isError: Boolean = false, + _meta: Option[Map[String, Json]] = None +) derives Codec + +final case class ToolListChangedNotification(method: String = "notifications/tools/list_changed") derives Codec diff --git a/core/src/main/scala/chimp/protocol/model.scala b/core/src/main/scala/chimp/protocol/model.scala deleted file mode 100644 index 0a6e2f4..0000000 --- a/core/src/main/scala/chimp/protocol/model.scala +++ /dev/null @@ -1,385 +0,0 @@ -// Combined MCP 2025-03-26 protocol and tool data model. -// NOTE: RequestId and ProgressToken use newtype wrappers for spec accuracy and to avoid ambiguous implicits. -package chimp.protocol - -import io.circe.syntax.* -import io.circe.{Codec, Decoder, Encoder, Json} - -// --- JSON-RPC base types --- -// Use newtype wrappers for union types to avoid ambiguous implicits -opaque type RequestId = String | Int -object RequestId { - def apply(value: String | Int): RequestId = value - def unapply(id: RequestId): Option[String | Int] = Some(id) - given encoder: Encoder[RequestId] = Encoder.instance { - case s: String => Json.fromString(s) - case i: Int => Json.fromInt(i) - } - given decoder: Decoder[RequestId] = Decoder.instance { c => - c.as[String].map(RequestId(_)).orElse(c.as[Int].map(RequestId(_))) - } - given codec: Codec[RequestId] = Codec.from(decoder, encoder) -} -opaque type ProgressToken = String | Int -object ProgressToken { - def apply(value: String | Int): ProgressToken = value - def unapply(token: ProgressToken): Option[String | Int] = Some(token) - given encoder: Encoder[ProgressToken] = Encoder.instance { - case s: String => Json.fromString(s) - case i: Int => Json.fromInt(i) - } - given decoder: Decoder[ProgressToken] = Decoder.instance { c => - c.as[String].map(ProgressToken(_)).orElse(c.as[Int].map(ProgressToken(_))) - } - given codec: Codec[ProgressToken] = Codec.from(decoder, encoder) -} -// For pagination -type Cursor = String - -// Note: JSONRPCMessage is a protocol sum type; custom codecs are needed for serialization. -enum JSONRPCMessage: - case Request(jsonrpc: String = "2.0", method: String, params: Option[Json] = None, id: RequestId) - case Notification(jsonrpc: String = "2.0", method: String, params: Option[Json] = None) - case Response(jsonrpc: String = "2.0", id: RequestId, result: Json) - case Error(jsonrpc: String = "2.0", id: RequestId, error: JSONRPCErrorObject) - case BatchRequest(requests: List[JSONRPCMessage]) - case BatchResponse(responses: List[JSONRPCMessage]) - -object JSONRPCMessage { - import io.circe.* - import io.circe.syntax.* - - given Decoder[JSONRPCMessage] = Decoder.instance { c => - val jsonrpc = c.downField("jsonrpc").as[String].getOrElse("2.0") - val methodOpt = c.downField("method").as[String].toOption - val idOpt = c.downField("id").as[RequestId].toOption - val paramsOpt = c.downField("params").focus - val resultOpt = c.downField("result").focus - val errorOpt = c.downField("error").as[JSONRPCErrorObject].toOption - val isBatchRequest = c.keys.exists(_.exists(_ == "requests")) - val isBatchResponse = c.keys.exists(_.exists(_ == "responses")) - - (methodOpt, idOpt, paramsOpt, resultOpt, errorOpt, isBatchRequest, isBatchResponse) match { - case (Some(method), Some(id), _, None, None, false, false) => - // Request (with or without params) - Right(JSONRPCMessage.Request(jsonrpc, method, paramsOpt, id)) - case (Some(method), None, _, None, None, false, false) => - // Notification (with or without params) - Right(JSONRPCMessage.Notification(jsonrpc, method, paramsOpt)) - case (None, Some(id), None, Some(result), None, false, false) => - // Response - Right(JSONRPCMessage.Response(jsonrpc, id, result)) - case (None, Some(id), None, None, Some(error), false, false) => - // Error - Right(JSONRPCMessage.Error(jsonrpc, id, error)) - case (None, None, None, None, None, true, false) => - // BatchRequest - c.downField("requests").as[List[JSONRPCMessage]].map(JSONRPCMessage.BatchRequest(_)) - case (None, None, None, None, None, false, true) => - // BatchResponse - c.downField("responses").as[List[JSONRPCMessage]].map(JSONRPCMessage.BatchResponse(_)) - case _ => - Left(DecodingFailure("type JSONRPCMessage could not be decoded from JSON", c.history)) - } - } - - given Encoder[JSONRPCMessage] = Encoder.instance { - case JSONRPCMessage.Request(jsonrpc, method, params, id) => - Json - .obj( - "jsonrpc" -> Json.fromString(jsonrpc), - "method" -> Json.fromString(method), - "params" -> params.getOrElse(Json.Null), - "id" -> id.asJson - ) - .dropNullValues - case JSONRPCMessage.Notification(jsonrpc, method, params) => - Json - .obj( - "jsonrpc" -> Json.fromString(jsonrpc), - "method" -> Json.fromString(method), - "params" -> params.getOrElse(Json.Null) - ) - .dropNullValues - case JSONRPCMessage.Response(jsonrpc, id, result) => - Json.obj( - "jsonrpc" -> Json.fromString(jsonrpc), - "id" -> id.asJson, - "result" -> result - ) - case JSONRPCMessage.Error(jsonrpc, id, error) => - Json.obj( - "jsonrpc" -> Json.fromString(jsonrpc), - "id" -> id.asJson, - "error" -> error.asJson - ) - case JSONRPCMessage.BatchRequest(requests) => - Json.obj( - "requests" -> requests.asJson - ) - case JSONRPCMessage.BatchResponse(responses) => - Json.obj( - "responses" -> responses.asJson - ) - } -} - -final case class JSONRPCErrorObject( - code: Int, - message: String, - data: Option[Json] = None -) derives Codec - -enum JSONRPCErrorCodes(val code: Int) { - case ParseError extends JSONRPCErrorCodes(-32700) - case InvalidRequest extends JSONRPCErrorCodes(-32600) - case MethodNotFound extends JSONRPCErrorCodes(-32601) - case InvalidParams extends JSONRPCErrorCodes(-32602) - case InternalError extends JSONRPCErrorCodes(-32603) - - // Optionally, a method to get enum from code - def fromCode(code: Int): Option[JSONRPCErrorCodes] = code match { - case -32700 => Some(ParseError) - case -32600 => Some(InvalidRequest) - case -32601 => Some(MethodNotFound) - case -32602 => Some(InvalidParams) - case -32603 => Some(InternalError) - case _ => None - } -} - -// --- Capabilities --- -final case class ClientCapabilities( - experimental: Option[Map[String, Json]] = None, - roots: Option[ClientRootsCapability] = None, - sampling: Option[Json] = None -) derives Codec -final case class ClientRootsCapability(listChanged: Option[Boolean] = None) derives Codec - -final case class ServerCapabilities( - experimental: Option[Map[String, Json]] = None, - logging: Option[Json] = None, - completions: Option[Json] = None, - prompts: Option[ServerPromptsCapability] = None, - resources: Option[ServerResourcesCapability] = None, - tools: Option[ServerToolsCapability] = None -) derives Codec -final case class ServerPromptsCapability(listChanged: Option[Boolean] = None) derives Codec -final case class ServerResourcesCapability(subscribe: Option[Boolean] = None, listChanged: Option[Boolean] = None) derives Codec -final case class ServerToolsCapability(listChanged: Option[Boolean] = None) derives Codec - -final case class Implementation(name: String, version: String) derives Codec - -// --- Progress, Cancellation, Initialization, Ping --- -final case class CancelledNotification( - method: String = "notifications/cancelled", - params: CancelledParams -) derives Codec -final case class CancelledParams(requestId: RequestId, reason: Option[String] = None) derives Codec - -final case class InitializeRequest( - method: String = "initialize", - params: InitializeParams -) derives Codec -final case class InitializeParams( - protocolVersion: String, - capabilities: ClientCapabilities, - clientInfo: Implementation -) derives Codec -final case class InitializeResult( - protocolVersion: String, - capabilities: ServerCapabilities, - serverInfo: Implementation, - instructions: Option[String] = None -) derives Codec -final case class InitializedNotification(method: String = "notifications/initialized") derives Codec - -final case class PingRequest(method: String = "ping") derives Codec - -// --- Model selection --- -final case class ModelPreferences( - hints: Option[List[ModelHint]] = None, - costPriority: Option[Double] = None, - speedPriority: Option[Double] = None, - intelligencePriority: Option[Double] = None -) derives Codec -final case class ModelHint(name: Option[String] = None) derives Codec - -// --- Resource and prompt references --- -final case class ResourceReference(`type`: String = "ref/resource", uri: String) derives Codec -final case class PromptReference(`type`: String = "ref/prompt", name: String) derives Codec - -// --- Roots --- -final case class ListRootsRequest(method: String = "roots/list") derives Codec -final case class ListRootsResult(roots: List[Root]) derives Codec -final case class Root(uri: String, name: Option[String] = None) derives Codec -final case class RootsListChangedNotification(method: String = "notifications/roots/list_changed") derives Codec - -// --- Autocomplete --- -// Use an enum for CompleteRef instead of Either -enum CompleteRef derives Codec: - case Prompt(prompt: PromptReference) - case Resource(resource: ResourceReference) - -final case class CompleteRequest( - method: String = "completion/complete", - params: CompleteParams -) derives Codec -final case class CompleteParams( - ref: CompleteRef, - argument: CompleteArgument -) derives Codec -final case class CompleteArgument(name: String, value: String) derives Codec -final case class CompleteResult(completion: Completion) derives Codec -final case class Completion(values: List[String], total: Option[Int] = None, hasMore: Option[Boolean] = None) derives Codec - -// --- Tool model --- -final case class ToolAnnotations( - title: Option[String] = None, - readOnlyHint: Option[Boolean] = None, - destructiveHint: Option[Boolean] = None, - idempotentHint: Option[Boolean] = None, - openWorldHint: Option[Boolean] = None -) derives Codec - -final case class ToolDefinition( - name: String, - description: Option[String] = None, - inputSchema: Json, - annotations: Option[ToolAnnotations] = None -) derives Codec - -final case class ListToolsResponse( - tools: List[ToolDefinition], - nextCursor: Option[String] = None -) derives Codec - -// Tool result content types -enum ToolContent: - case Text( - `type`: String = "text", - text: String - ) - case Image( - `type`: String = "image", - data: String, // base64 - mimeType: String - ) - case Audio( - `type`: String = "audio", - data: String, // base64 - mimeType: String - ) - case ResourceContent( - `type`: String = "resource", - resource: Resource - ) - -object ToolContent { - import io.circe.{DecodingFailure, HCursor} - given Encoder[ToolContent] = Encoder.instance { - case ToolContent.Text(_, text) => - Json.obj( - "type" -> Json.fromString("text"), - "text" -> Json.fromString(text) - ) - case ToolContent.Image(_, data, mimeType) => - Json.obj( - "type" -> Json.fromString("image"), - "data" -> Json.fromString(data), - "mimeType" -> Json.fromString(mimeType) - ) - case ToolContent.Audio(_, data, mimeType) => - Json.obj( - "type" -> Json.fromString("audio"), - "data" -> Json.fromString(data), - "mimeType" -> Json.fromString(mimeType) - ) - case ToolContent.ResourceContent(_, resource) => - Json.obj( - "type" -> Json.fromString("resource"), - "resource" -> resource.asJson - ) - } - - given Decoder[ToolContent] = Decoder.instance { (c: HCursor) => - c.downField("type").as[String].flatMap { - case "text" => - c.downField("text").as[String].map(ToolContent.Text("text", _)) - case "image" => - for { - data <- c.downField("data").as[String] - mimeType <- c.downField("mimeType").as[String] - } yield ToolContent.Image("image", data, mimeType) - case "audio" => - for { - data <- c.downField("data").as[String] - mimeType <- c.downField("mimeType").as[String] - } yield ToolContent.Audio("audio", data, mimeType) - case "resource" => - c.downField("resource").as[Resource].map(ToolContent.ResourceContent("resource", _)) - case other => - Left(DecodingFailure(s"Unknown ToolContent type: $other", c.history)) - } - } -} - -final case class Resource( - uri: String, - mimeType: String, - text: Option[String] = None -) derives Codec - -final case class ToolCallResult( - content: List[ToolContent], - isError: Boolean = false -) derives Codec - -// --- Tool call (request/response) --- -final case class CallToolRequest( - method: String = "tools/call", - params: CallToolParams -) derives Codec -final case class CallToolParams( - name: String, - arguments: Json -) derives Codec -final case class CallToolResult( - content: List[ToolContent], - isError: Boolean = false -) derives Codec - -// --- List tools (request/response) --- -final case class ListToolsRequest( - method: String = "tools/list", - params: Option[ListToolsParams] = None -) derives Codec -final case class ListToolsParams(cursor: Option[Cursor] = None) derives Codec -// ListToolsResponse is above - -// --- Notifications for list changes --- -final case class ToolListChangedNotification(method: String = "notifications/tools/list_changed") derives Codec -final case class PromptListChangedNotification(method: String = "notifications/prompts/list_changed") derives Codec -final case class ResourceListChangedNotification(method: String = "notifications/resources/list_changed") derives Codec - -// --- Logging --- -final case class LoggingMessageNotification( - method: String = "notifications/logging/message", - params: LoggingMessageParams -) derives Codec -final case class LoggingMessageParams( - level: String, - message: String -) derives Codec - -// --- Progress notification --- -final case class ProgressNotification( - method: String = "notifications/progress", - params: ProgressParams -) derives Codec -final case class ProgressParams( - requestId: RequestId, - progressToken: Option[ProgressToken] = None, - message: Option[String] = None, - percent: Option[Double] = None -) derives Codec From 972ff76cbfa7757d150310a40852d7f04f40c3ed Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Mon, 11 May 2026 12:32:04 +0200 Subject: [PATCH 03/27] feat: drop batch support in server, it was part of the protocol only for a short period of time and is gone in 2 last versions, not adopted by official clients --- .../test/scala/chimp/protocol/ModelSpec.scala | 68 --------- .../main/scala/chimp/server/McpHandler.scala | 45 +----- server/src/main/scala/chimp/server/tool.scala | 9 +- .../scala/chimp/server/McpHandlerSpec.scala | 137 +----------------- 4 files changed, 21 insertions(+), 238 deletions(-) diff --git a/core/src/test/scala/chimp/protocol/ModelSpec.scala b/core/src/test/scala/chimp/protocol/ModelSpec.scala index 16f8938..c5d26c5 100644 --- a/core/src/test/scala/chimp/protocol/ModelSpec.scala +++ b/core/src/test/scala/chimp/protocol/ModelSpec.scala @@ -115,74 +115,6 @@ class ModelSpec extends AnyFlatSpec with Matchers { decoded shouldBe error } - it should "handle BatchRequest messages according to JSON-RPC 2.0 spec" in { - // Given - val batchRequest: JSONRPCMessage = BatchRequest( - List( - Request(method = "method1", id = RequestId(1)), - Request(method = "method2", id = RequestId(2)) - ) - ) - val expectedJson = parseJson(""" - { - "requests": [ - { - "jsonrpc": "2.0", - "method": "method1", - "id": 1 - }, - { - "jsonrpc": "2.0", - "method": "method2", - "id": 2 - } - ] - } - """) - - // When - val json = batchRequest.asJson - val decoded = json.as[JSONRPCMessage].getOrElse(fail("Failed to decode JSON")) - - // Then - json shouldBe expectedJson - decoded shouldBe batchRequest - } - - it should "handle BatchResponse messages according to JSON-RPC 2.0 spec" in { - // Given - val batchResponse: JSONRPCMessage = BatchResponse( - List( - Response(id = RequestId(1), result = Json.obj("result1" -> Json.fromString("value1"))), - Response(id = RequestId(2), result = Json.obj("result2" -> Json.fromString("value2"))) - ) - ) - val expectedJson = parseJson(""" - { - "responses": [ - { - "jsonrpc": "2.0", - "id": 1, - "result": {"result1": "value1"} - }, - { - "jsonrpc": "2.0", - "id": 2, - "result": {"result2": "value2"} - } - ] - } - """) - - // When - val json = batchResponse.asJson - val decoded = json.as[JSONRPCMessage].getOrElse(fail("Failed to decode JSON")) - - // Then - json shouldBe expectedJson - decoded shouldBe batchResponse - } - it should "handle both numeric and string request IDs according to JSON-RPC 2.0 spec" in { // Given val numericRequest: JSONRPCMessage = Request(method = "test", id = RequestId(123)) diff --git a/server/src/main/scala/chimp/server/McpHandler.scala b/server/src/main/scala/chimp/server/McpHandler.scala index 3a378ac..7195483 100644 --- a/server/src/main/scala/chimp/server/McpHandler.scala +++ b/server/src/main/scala/chimp/server/McpHandler.scala @@ -49,7 +49,6 @@ class McpHandler[F[_]]( showJsonSchemaMetadata: Boolean ): private val logger = LoggerFactory.getLogger(classOf[McpHandler[_]]) - private val ProtocolVersion = "2025-03-26" private val toolsByName = tools.map(t => t.name -> t).toMap /** Converts a ServerTool to its protocol definition. */ @@ -74,10 +73,12 @@ class McpHandler[F[_]]( logger.debug(s"Protocol error (id=$id, code=$code): $message") JSONRPCMessage.Error(id = id, error = JSONRPCErrorObject(code = code, message = message)) - private def handleInitialize(id: RequestId): JSONRPCMessage.Response = + private def handleInitialize(params: Option[Json], id: RequestId): JSONRPCMessage.Response = + val requested = params.flatMap(_.hcursor.downField("protocolVersion").as[String].toOption) + val negotiated = requested.map(ProtocolVersion.negotiate).getOrElse(ProtocolVersion.Latest) val capabilities = ServerCapabilities(tools = Some(ServerToolsCapability(listChanged = Some(false)))) val result = - InitializeResult(protocolVersion = ProtocolVersion, capabilities = capabilities, serverInfo = Implementation(name, version)) + InitializeResult(protocolVersion = negotiated, capabilities = capabilities, serverInfo = Implementation(name, version)) JSONRPCMessage.Response(id = id, result = result.asJson) /** Handles the 'tools/list' JSON-RPC method, returning the list of available tools. */ @@ -121,13 +122,13 @@ class McpHandler[F[_]]( .logic(decodedInput, headers) .map: case Right(result) => - val callResult = ToolCallResult( + val callResult = CallToolResult( content = List(ToolContent.Text(text = result)), isError = false ) JSONRPCMessage.Response(id = id, result = callResult.asJson) case Left(errorMsg) => - val callResult = ToolCallResult( + val callResult = CallToolResult( content = List(ToolContent.Text(text = errorMsg)), isError = true ) @@ -149,45 +150,13 @@ class McpHandler[F[_]]( McpResponse.JsonResponse((response: JSONRPCMessage).asJson) } case "initialize" => - val response = handleInitialize(id) + val response = handleInitialize(params, id) McpResponse.JsonResponse((response: JSONRPCMessage).asJson).unit case other => val errorResponse = protocolError(id, JSONRPCErrorCodes.MethodNotFound.code, s"Unknown method: $other") McpResponse.JsonResponse((errorResponse: JSONRPCMessage).asJson).unit - case Right(JSONRPCMessage.BatchRequest(requests)) => - // For each sub-request, process as a single request using flatMap/fold (no .sequence) - def processBatch(reqs: List[JSONRPCMessage], acc: List[JSONRPCMessage]): F[List[JSONRPCMessage]] = - reqs match - case Nil => acc.reverse.unit - case head :: tail => - head match - case JSONRPCMessage.Notification(_, _, _) => - processBatch(tail, acc) // skip notifications - case _ => - doHandleJsonRpc((head: JSONRPCMessage).asJson, headers).flatMap { resp => - resp match - case McpResponse.JsonResponse(json) => - val msg = json - .as[JSONRPCMessage] - .getOrElse( - protocolError(RequestId("null"), JSONRPCErrorCodes.InternalError.code, "Failed to decode sub-response") - ) - processBatch(tail, msg :: acc) - case McpResponse.EmptyAcceptResponse => - processBatch(tail, acc) // skip notifications in batch - } - processBatch(requests, Nil).map { responses => - // Per JSON-RPC spec, notifications (no id) should not be included in the response - val filtered = responses.collect { - case r @ JSONRPCMessage.Response(_, id, _) => r - case e @ JSONRPCMessage.Error(_, id, _) => e - } - val batchResponse = JSONRPCMessage.BatchResponse(filtered) - McpResponse.JsonResponse((batchResponse: JSONRPCMessage).asJson) - } case Right(notification: JSONRPCMessage.Notification) => logger.debug(s"Received notification: ${notification.method}") - // For notifications, return EmptyAcceptResponse to indicate no body should be sent McpResponse.EmptyAcceptResponse.unit case Right(_) => val errorResponse = protocolError(RequestId("null"), JSONRPCErrorCodes.InvalidRequest.code, "Invalid request type") diff --git a/server/src/main/scala/chimp/server/tool.scala b/server/src/main/scala/chimp/server/tool.scala index 9a580ce..691a319 100644 --- a/server/src/main/scala/chimp/server/tool.scala +++ b/server/src/main/scala/chimp/server/tool.scala @@ -25,8 +25,13 @@ case class PartialTool( /** Specify the input type for the tool, providing both a Tapir Schema and a Circe Decoder. */ def input[I: Schema: Decoder]: Tool[I] = Tool[I](name, description, summon[Schema[I]], summon[Decoder[I]], annotations) -/** Creates a new MCP tool description with the given name. */ -def tool(name: String): PartialTool = PartialTool(name) +private val ToolNameRegex = "^[A-Za-z0-9_./-]+$".r + +/** Creates a new MCP tool description with the given name. The name must match `^[A-Za-z0-9_./-]+$` and be 1–64 characters long. */ +def tool(name: String): PartialTool = + require(name.length >= 1 && name.length <= 64, s"Tool name must be 1..64 characters long, got ${name.length}: $name") + require(ToolNameRegex.matches(name), s"Tool name must match ${ToolNameRegex.regex}, got: $name") + PartialTool(name) // diff --git a/server/src/test/scala/chimp/server/McpHandlerSpec.scala b/server/src/test/scala/chimp/server/McpHandlerSpec.scala index c6225d3..af06931 100644 --- a/server/src/test/scala/chimp/server/McpHandlerSpec.scala +++ b/server/src/test/scala/chimp/server/McpHandlerSpec.scala @@ -74,7 +74,7 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: resp match case Response(_, _, result) => val resultObj = result.as[InitializeResult].getOrElse(fail("Failed to decode result")) - resultObj.protocolVersion shouldBe "2025-03-26" + resultObj.protocolVersion shouldBe "2025-11-25" resultObj.serverInfo.name should include("Chimp MCP server") case _ => fail("Expected Response") @@ -111,7 +111,7 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: // Then resp match case Response(_, _, result) => - val resultObj = result.as[ToolCallResult].getOrElse(fail("Failed to decode result")) + val resultObj = result.as[CallToolResult].getOrElse(fail("Failed to decode result")) resultObj.isError shouldBe false resultObj.content should have length 1 resultObj.content.head shouldBe ToolContent.Text("text", "hello") @@ -132,7 +132,7 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: // Then resp match case Response(_, _, result) => - val resultObj = result.as[ToolCallResult].getOrElse(fail("Failed to decode result")) + val resultObj = result.as[CallToolResult].getOrElse(fail("Failed to decode result")) resultObj.isError shouldBe false resultObj.content.head shouldBe ToolContent.Text("text", "5") case _ => fail("Expected Response") @@ -248,7 +248,7 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: // Then resp match case Response(_, _, result) => - val resultObj = result.as[ToolCallResult].getOrElse(fail("Failed to decode result")) + val resultObj = result.as[CallToolResult].getOrElse(fail("Failed to decode result")) resultObj.isError shouldBe true resultObj.content.head shouldBe ToolContent.Text("text", "Intentional failure") case _ => fail("Expected Response") @@ -268,90 +268,6 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: error.message should include("Unknown method") case _ => fail("Expected Error") - it should "handle batch requests with mixed results" in: - // Given - val req1 = Request( - method = "tools/call", - params = Some( - Json.obj( - "name" -> Json.fromString("echo"), - "arguments" -> Json.obj("message" -> Json.fromString("hi")) - ) - ), - id = RequestId("b1") - ) - val req2 = Request( - method = "tools/call", - params = Some( - Json.obj( - "name" -> Json.fromString("add"), - "arguments" -> Json.obj("a" -> Json.fromInt(1), "b" -> Json.fromInt(2)) - ) - ), - id = RequestId("b2") - ) - val req3 = Request( - method = "tools/call", - params = Some( - Json.obj( - "name" -> Json.fromString("fail"), - "arguments" -> Json.obj("message" -> Json.fromString("fail")) - ) - ), - id = RequestId("b3") - ) - val req4 = Request( - method = "tools/call", - params = Some( - Json.obj( - "name" -> Json.fromString("unknown"), - "arguments" -> Json.obj("foo" -> Json.fromString("bar")) - ) - ), - id = RequestId("b4") - ) - val notification = Notification(method = "tools/list", params = None) - val batch = BatchRequest(List(req1, req2, req3, req4, notification)) - val json = batch.asJson - // When - val response = handler.handleJsonRpc(json, Seq.empty) - val respJson = extractJsonFromResponse(response) - val resp = respJson.as[JSONRPCMessage].getOrElse(fail("Failed to decode batch response")) - // Then - resp match - case BatchResponse(responses) => - // Should not include notification response - responses.foreach { - case Response(_, id, result) if id == RequestId("b1") => - val r = result.as[ToolCallResult].getOrElse(fail("Failed to decode result")) - r.isError shouldBe false - r.content.head shouldBe ToolContent.Text("text", "hi") - case Response(_, id, result) if id == RequestId("b2") => - val r = result.as[ToolCallResult].getOrElse(fail("Failed to decode result")) - r.isError shouldBe false - r.content.head shouldBe ToolContent.Text("text", "3") - case Response(_, id, result) if id == RequestId("b3") => - val r = result.as[ToolCallResult].getOrElse(fail("Failed to decode result")) - r.isError shouldBe true - r.content.head shouldBe ToolContent.Text("text", "Intentional failure") - case Error(_, id, error) if id == RequestId("b4") => - error.code shouldBe MethodNotFound.code - error.message should include("Unknown tool") - case other => fail(s"Unexpected response: $other") - } - responses.exists { - case Response(_, id, _) if id == RequestId("b1") => true - case Response(_, id, _) if id == RequestId("b2") => true - case Response(_, id, _) if id == RequestId("b3") => true - case Error(_, id, _) if id == RequestId("b4") => true - case _ => false - } shouldBe true - responses.exists { - case Notification(_, _, _) => true - case _ => false - } shouldBe false - case _ => fail("Expected BatchResponse") - it should "call a tool with a header and receive the header's value in the response" in: // Given val params = Json.obj( @@ -367,7 +283,7 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: // Then resp match case Response(_, _, result) => - val resultObj = result.as[ToolCallResult].getOrElse(fail("Failed to decode result")) + val resultObj = result.as[CallToolResult].getOrElse(fail("Failed to decode result")) resultObj.isError shouldBe false resultObj.content.head shouldBe ToolContent.Text("text", "header name: header-name, header value: my-secret-header") case _ => fail("Expected Response") @@ -388,7 +304,7 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: // Then resp match case Response(_, _, result) => - val resultObj = result.as[ToolCallResult].getOrElse(fail("Failed to decode result")) + val resultObj = result.as[CallToolResult].getOrElse(fail("Failed to decode result")) resultObj.isError shouldBe false resultObj.content.head shouldBe ToolContent.Text( "text", @@ -411,7 +327,7 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: // Then resp match case Response(_, _, result) => - val resultObj = result.as[ToolCallResult].getOrElse(fail("Failed to decode result")) + val resultObj = result.as[CallToolResult].getOrElse(fail("Failed to decode result")) resultObj.isError shouldBe false resultObj.content.head shouldBe ToolContent.Text("text", "no header") case _ => fail("Expected Response") @@ -461,42 +377,3 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: requiredFields should not contain "optionalField" case _ => fail("Expected Response") - it should "handle batch requests with mixed headers" in: - // Given - val req1 = Request( - method = "tools/call", - params = Some( - Json.obj( - "name" -> Json.fromString("headerEcho"), - "arguments" -> Json.obj("dummy" -> Json.fromString("hi")) - ) - ), - id = RequestId("bh1") - ) - val req2 = Request( - method = "tools/call", - params = Some( - Json.obj( - "name" -> Json.fromString("headerEcho"), - "arguments" -> Json.obj("dummy" -> Json.fromString("yo")) - ) - ), - id = RequestId("bh2") - ) - val batch = BatchRequest(List(req1, req2)) - val json = batch.asJson - // When - val response = handler.handleJsonRpc(json, Seq(Header("header-name", "batch-header"))) - val respJson = extractJsonFromResponse(response) - val resp = respJson.as[JSONRPCMessage].getOrElse(fail("Failed to decode batch response")) - // Then - resp match - case BatchResponse(responses) => - responses.foreach { - case Response(_, id, result) if id == RequestId("bh1") || id == RequestId("bh2") => - val r = result.as[ToolCallResult].getOrElse(fail("Failed to decode result")) - r.isError shouldBe false - r.content.head shouldBe ToolContent.Text("text", "header name: header-name, header value: batch-header") - case other => fail(s"Unexpected response: $other") - } - case _ => fail("Expected BatchResponse") From d7678431f99b03ca6ced80d7c92a24bff187c0f2 Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Mon, 11 May 2026 13:00:07 +0200 Subject: [PATCH 04/27] feat: client scaffold, transport abstraction and default http and stdio implementation, basic client interface --- build.sbt | 14 +- .../scala/chimp/client/DefaultMcpClient.scala | 66 +++++++++ .../main/scala/chimp/client/McpClient.scala | 27 ++++ .../scala/chimp/client/McpExceptions.scala | 10 ++ .../chimp/client/internal/CapsBuilder.scala | 6 + .../chimp/client/internal/Correlator.scala | 9 ++ .../client/transport/HttpTransport.scala | 72 ++++++++++ .../client/transport/StdioTransport.scala | 127 ++++++++++++++++++ .../transport/StreamingHttpTransport.scala | 16 +++ .../transport/StreamingStdioTransport.scala | 17 +++ .../chimp/client/transport/Transport.scala | 17 +++ .../chimp/client/HttpTransportSpec.scala | 43 ++++++ .../scala/chimp/client/McpClientSpec.scala | 42 ++++++ 13 files changed, 465 insertions(+), 1 deletion(-) create mode 100644 client/src/main/scala/chimp/client/DefaultMcpClient.scala create mode 100644 client/src/main/scala/chimp/client/McpClient.scala create mode 100644 client/src/main/scala/chimp/client/McpExceptions.scala create mode 100644 client/src/main/scala/chimp/client/internal/CapsBuilder.scala create mode 100644 client/src/main/scala/chimp/client/internal/Correlator.scala create mode 100644 client/src/main/scala/chimp/client/transport/HttpTransport.scala create mode 100644 client/src/main/scala/chimp/client/transport/StdioTransport.scala create mode 100644 client/src/main/scala/chimp/client/transport/StreamingHttpTransport.scala create mode 100644 client/src/main/scala/chimp/client/transport/StreamingStdioTransport.scala create mode 100644 client/src/main/scala/chimp/client/transport/Transport.scala create mode 100644 client/src/test/scala/chimp/client/HttpTransportSpec.scala create mode 100644 client/src/test/scala/chimp/client/McpClientSpec.scala diff --git a/build.sbt b/build.sbt index 301e721..207d3eb 100644 --- a/build.sbt +++ b/build.sbt @@ -6,6 +6,7 @@ import com.softwaremill.UpdateVersionInDocs val scalaTestV = "3.2.20" val circeV = "0.14.15" val tapirV = "1.13.18" +val sttpClient4V = "4.0.23" lazy val verifyExamplesCompileUsingScalaCli = taskKey[Unit]("Verify that each example compiles using Scala CLI") @@ -27,7 +28,7 @@ val scalaTest = "org.scalatest" %% "scalatest" % scalaTestV % Test lazy val rootProject = (project in file(".")) .settings(commonSettings: _*) .settings(publishArtifact := false, name := "chimp") - .aggregate(core, server, examples) + .aggregate(core, server, client, examples) lazy val core: Project = (project in file("core")) .settings(commonSettings: _*) @@ -56,6 +57,17 @@ lazy val server: Project = (project in file("server")) ) .dependsOn(core) +lazy val client: Project = (project in file("client")) + .settings(commonSettings: _*) + .settings( + name := "chimp-client", + libraryDependencies ++= Seq( + scalaTest, + "com.softwaremill.sttp.client4" %% "core" % sttpClient4V + ) + ) + .dependsOn(core) + lazy val examples = (project in file("examples")) .settings(commonSettings: _*) .settings( diff --git a/client/src/main/scala/chimp/client/DefaultMcpClient.scala b/client/src/main/scala/chimp/client/DefaultMcpClient.scala new file mode 100644 index 0000000..e3627b8 --- /dev/null +++ b/client/src/main/scala/chimp/client/DefaultMcpClient.scala @@ -0,0 +1,66 @@ +package chimp.client + +import chimp.client.internal.Correlator +import chimp.client.transport.Transport +import chimp.protocol.* +import io.circe.syntax.* +import io.circe.{Decoder, Json} +import sttp.monad.MonadError +import sttp.monad.syntax.* + +object DefaultMcpClient: + def create[F[_], Caps]( + transport: Transport[F], + clientInfo: Implementation, + protocolVersion: String, + wireCaps: ClientCapabilities + ): McpClient[F, Caps] = new Impl[F, Caps](transport, clientInfo, protocolVersion, wireCaps) + + private final class Impl[F[_], Caps]( + transport: Transport[F], + clientInfo: Implementation, + protocolVersion: String, + wireCaps: ClientCapabilities + ) extends McpClient[F, Caps]: + private given MonadError[F] = transport.monad + private val correlator = Correlator() + + override def initialize(): F[InitializeResult] = + val params = InitializeParams( + protocolVersion = protocolVersion, + capabilities = wireCaps, + clientInfo = clientInfo + ) + sendRequest[InitializeResult]("initialize", Some(params.asJson)).flatMap: r => + sendNotification("notifications/initialized", None).map(_ => r) + + override def ping(): F[Unit] = + sendRequest[Json]("ping", None).map(_ => ()) + + override def close(): F[Unit] = transport.close() + + override def listTools(cursor: Option[Cursor]): F[ListToolsResponse] = + val params = cursor.map(c => ListToolsParams(cursor = Some(c)).asJson) + sendRequest[ListToolsResponse]("tools/list", params) + + override def callTool(name: String, arguments: Json): F[CallToolResult] = + val params = CallToolParams(name = name, arguments = arguments).asJson + sendRequest[CallToolResult]("tools/call", Some(params)) + + private def sendRequest[R: Decoder](method: String, params: Option[Json]): F[R] = + val req = JSONRPCMessage.Request(method = method, params = params, id = correlator.nextId()) + transport.send(req).flatMap: + case Some(JSONRPCMessage.Response(_, _, result)) => + result.as[R] match + case Right(r) => summon[MonadError[F]].unit(r) + case Left(e) => summon[MonadError[F]].error(McpProtocolException(s"Failed to decode $method result: ${e.getMessage}")) + case Some(JSONRPCMessage.Error(_, _, error)) => + summon[MonadError[F]].error(McpProtocolException(s"$method failed: ${error.code} ${error.message}")) + case Some(other) => + summon[MonadError[F]].error(McpProtocolException(s"Unexpected response to $method: $other")) + case None => + summon[MonadError[F]].error(McpProtocolException(s"No response received for request $method")) + + private def sendNotification(method: String, params: Option[Json]): F[Unit] = + val n = JSONRPCMessage.Notification(method = method, params = params) + transport.send(n).map(_ => ()) diff --git a/client/src/main/scala/chimp/client/McpClient.scala b/client/src/main/scala/chimp/client/McpClient.scala new file mode 100644 index 0000000..f8a0676 --- /dev/null +++ b/client/src/main/scala/chimp/client/McpClient.scala @@ -0,0 +1,27 @@ +package chimp.client + +import chimp.client.internal.CapsBuilder +import chimp.client.transport.Transport +import chimp.protocol.* +import io.circe.Json + +/** An MCP client. The `Caps` type parameter is an intersection of capability typeclasses (`Roots[F]`, `Sampling[F]`, `Elicitation[F]`) + * the host application opts into; each one is advertised on `initialize` and routed to the corresponding `given` handler when the + * server invokes it. + */ +trait McpClient[F[_], +Caps]: + def initialize(): F[InitializeResult] + def ping(): F[Unit] + def close(): F[Unit] + + def listTools(cursor: Option[Cursor] = None): F[ListToolsResponse] + def callTool(name: String, arguments: Json): F[CallToolResult] + +object McpClient: + inline def apply[F[_], Caps]( + transport: Transport[F], + clientInfo: Implementation, + protocolVersion: String = ProtocolVersion.Latest + ): McpClient[F, Caps] = + val wire = CapsBuilder.wire[F, Caps] + DefaultMcpClient.create[F, Caps](transport, clientInfo, protocolVersion, wire) diff --git a/client/src/main/scala/chimp/client/McpExceptions.scala b/client/src/main/scala/chimp/client/McpExceptions.scala new file mode 100644 index 0000000..969528a --- /dev/null +++ b/client/src/main/scala/chimp/client/McpExceptions.scala @@ -0,0 +1,10 @@ +package chimp.client + +class McpTransportException(message: String, cause: Throwable = null) extends RuntimeException(message, cause) + +final class McpAuthorizationException(message: String, val statusCode: Int) extends McpTransportException(message) + +final class McpSessionNotFoundException(sessionId: String) + extends McpTransportException(s"Server reported session-id $sessionId as not found") + +final class McpProtocolException(message: String) extends McpTransportException(message) diff --git a/client/src/main/scala/chimp/client/internal/CapsBuilder.scala b/client/src/main/scala/chimp/client/internal/CapsBuilder.scala new file mode 100644 index 0000000..ba09ed6 --- /dev/null +++ b/client/src/main/scala/chimp/client/internal/CapsBuilder.scala @@ -0,0 +1,6 @@ +package chimp.client.internal + +import chimp.protocol.ClientCapabilities + +object CapsBuilder: + inline def wire[F[_], Caps]: ClientCapabilities = ClientCapabilities() diff --git a/client/src/main/scala/chimp/client/internal/Correlator.scala b/client/src/main/scala/chimp/client/internal/Correlator.scala new file mode 100644 index 0000000..0504f46 --- /dev/null +++ b/client/src/main/scala/chimp/client/internal/Correlator.scala @@ -0,0 +1,9 @@ +package chimp.client.internal + +import chimp.protocol.RequestId + +import java.util.concurrent.atomic.AtomicLong + +final class Correlator: + private val counter = AtomicLong(0L) + def nextId(): RequestId = RequestId(counter.incrementAndGet().toInt) diff --git a/client/src/main/scala/chimp/client/transport/HttpTransport.scala b/client/src/main/scala/chimp/client/transport/HttpTransport.scala new file mode 100644 index 0000000..a718dc7 --- /dev/null +++ b/client/src/main/scala/chimp/client/transport/HttpTransport.scala @@ -0,0 +1,72 @@ +package chimp.client.transport + +import chimp.client.{McpAuthorizationException, McpProtocolException, McpSessionNotFoundException, McpTransportException} +import chimp.protocol.{JSONRPCMessage, ProtocolVersion} +import io.circe.parser +import io.circe.syntax.* +import sttp.client4.{Backend, Response, basicRequest} +import sttp.model.{MediaType, StatusCode, Uri} +import sttp.monad.MonadError +import sttp.monad.syntax.* + +import java.util.concurrent.atomic.AtomicReference + +/** Non-streaming Streamable HTTP transport. Works against any sttp `Backend[F]`. */ +final class HttpTransport[F[_]]( + backend: Backend[F], + uri: Uri, + protocolVersion: String = ProtocolVersion.Latest +) extends Transport[F]: + + given monad: MonadError[F] = backend.monad + + private val sessionId = AtomicReference[Option[String]](None) + + override def send(msg: JSONRPCMessage): F[Option[JSONRPCMessage]] = + val body = msg.asJson.deepDropNullValues.noSpaces + var req = basicRequest + .post(uri) + .header("Content-Type", "application/json") + .header("Accept", s"${MediaType.ApplicationJson.toString}, text/event-stream") + .header("MCP-Protocol-Version", protocolVersion) + .body(body) + sessionId.get().foreach(s => req = req.header("Mcp-Session-Id", s)) + + req.send(backend).flatMap(interpret) + + private def interpret(response: Response[Either[String, String]]): F[Option[JSONRPCMessage]] = + response.header("Mcp-Session-Id").foreach(s => sessionId.set(Some(s))) + response.code match + case StatusCode.Ok => + response.body match + case Right(bodyStr) => + parser.decode[JSONRPCMessage](bodyStr) match + case Right(m) => monad.unit(Some(m)) + case Left(e) => monad.error(McpProtocolException(s"Failed to decode response body: ${e.getMessage}")) + case Left(err) => + monad.error(McpTransportException(s"HTTP 200 with empty body: $err")) + case StatusCode.Accepted => + monad.unit(None) + case StatusCode.Unauthorized => + monad.error(McpAuthorizationException(s"Authorization required", response.code.code)) + case StatusCode.Forbidden => + monad.error(McpAuthorizationException(s"Forbidden", response.code.code)) + case StatusCode.NotFound if sessionId.get().isDefined => + val id = sessionId.get().get + sessionId.set(None) + monad.error(McpSessionNotFoundException(id)) + case other => + monad.error(McpTransportException(s"Unexpected HTTP response: ${other.code} ${response.body.fold(identity, identity)}")) + + override def onIncoming(handler: JSONRPCMessage => F[Unit]): F[Unit] = monad.unit(()) + + override def close(): F[Unit] = + sessionId.get() match + case None => monad.unit(()) + case Some(id) => + val req = basicRequest + .delete(uri) + .header("Mcp-Session-Id", id) + .header("MCP-Protocol-Version", protocolVersion) + sessionId.set(None) + req.send(backend).map(_ => ()) diff --git a/client/src/main/scala/chimp/client/transport/StdioTransport.scala b/client/src/main/scala/chimp/client/transport/StdioTransport.scala new file mode 100644 index 0000000..52177bf --- /dev/null +++ b/client/src/main/scala/chimp/client/transport/StdioTransport.scala @@ -0,0 +1,127 @@ +package chimp.client.transport + +import chimp.protocol.{JSONRPCMessage, RequestId} +import io.circe.parser +import io.circe.syntax.* +import org.slf4j.LoggerFactory +import sttp.monad.{IdentityMonad, MonadError} +import sttp.shared.Identity + +import java.io.{BufferedReader, BufferedWriter, File, InputStreamReader, OutputStreamWriter} +import java.nio.charset.StandardCharsets +import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference} +import java.util.concurrent.{ConcurrentHashMap, SynchronousQueue, TimeUnit} + +import scala.jdk.CollectionConverters.* + +/** Synchronous stdio transport spawning the MCP server as a subprocess. + * + * For fiber-based effects (ZIO, cats-effect), use a `StreamingStdioTransport` impl from a per-effect chimp client subproject. + */ +final class StdioTransport( + command: List[String], + env: Map[String, String] = Map.empty, + workDir: Option[File] = None +) extends Transport[Identity]: + + private val log = LoggerFactory.getLogger(classOf[StdioTransport]) + + given monad: MonadError[Identity] = IdentityMonad + + private val proc: Process = + val pb = ProcessBuilder(command.asJava) + workDir.foreach(pb.directory) + if env.nonEmpty then + val procEnv = pb.environment() + env.foreach { case (k, v) => procEnv.put(k, v) } + pb.redirectErrorStream(false) + pb.start() + + private val writer = BufferedWriter(OutputStreamWriter(proc.getOutputStream, StandardCharsets.UTF_8)) + private val reader = BufferedReader(InputStreamReader(proc.getInputStream, StandardCharsets.UTF_8)) + private val errReader = BufferedReader(InputStreamReader(proc.getErrorStream, StandardCharsets.UTF_8)) + + private val pending = ConcurrentHashMap[RequestId, SynchronousQueue[JSONRPCMessage]]() + private val incomingHandler = AtomicReference[JSONRPCMessage => Identity[Unit]](_ => ()) + private val closed = AtomicBoolean(false) + + private val readerThread = startDaemon("mcp-stdio-reader", readLoop _) + private val stderrThread = startDaemon("mcp-stdio-stderr", drainStderr _) + + private def startDaemon(name: String, body: () => Unit): Thread = + val t = Thread(() => body()) + t.setName(name) + t.setDaemon(true) + t.start() + t + + private def readLoop(): Unit = + try + var line: String = reader.readLine() + while line != null do + if line.nonEmpty then + parser.decode[JSONRPCMessage](line) match + case Right(msg) => dispatch(msg) + case Left(e) => log.warn(s"Failed to parse JSON-RPC line: ${e.getMessage}; raw: $line") + line = reader.readLine() + catch case e: Exception => if !closed.get() then log.warn(s"Reader loop ended: ${e.getMessage}") + finally drainPending() + + private def drainStderr(): Unit = + try + var line: String = errReader.readLine() + while line != null do + log.info(s"stdio-server: $line") + line = errReader.readLine() + catch case _: Exception => () + + private def dispatch(msg: JSONRPCMessage): Unit = msg match + case r: JSONRPCMessage.Response => + val q = pending.remove(r.id) + if q != null then q.offer(r, 1, TimeUnit.SECONDS) + case e: JSONRPCMessage.Error => + val q = pending.remove(e.id) + if q != null then q.offer(e, 1, TimeUnit.SECONDS) + case other => + incomingHandler.get()(other) + + private def drainPending(): Unit = + val it = pending.entrySet().iterator() + while it.hasNext do + val entry = it.next() + val poison = JSONRPCMessage.Error( + id = entry.getKey, + error = chimp.protocol.JSONRPCErrorObject(code = -32000, message = "Transport closed") + ) + entry.getValue.offer(poison, 100, TimeUnit.MILLISECONDS) + it.remove() + + override def send(msg: JSONRPCMessage): Identity[Option[JSONRPCMessage]] = + if closed.get() then throw chimp.client.McpTransportException("Stdio transport is closed") + msg match + case r: JSONRPCMessage.Request => + val q = SynchronousQueue[JSONRPCMessage]() + pending.put(r.id, q) + writeLine(r) + Some(q.take()) + case other => + writeLine(other) + None + + private def writeLine(msg: JSONRPCMessage): Unit = + writer.synchronized: + writer.write(msg.asJson.deepDropNullValues.noSpaces) + writer.newLine() + writer.flush() + + override def onIncoming(handler: JSONRPCMessage => Identity[Unit]): Identity[Unit] = + incomingHandler.set(handler) + + override def close(): Identity[Unit] = + if closed.compareAndSet(false, true) then + try writer.close() catch case _: Exception => () + if proc.isAlive then + if !proc.waitFor(2, TimeUnit.SECONDS) then proc.destroy() + if !proc.waitFor(2, TimeUnit.SECONDS) then proc.destroyForcibly() + readerThread.interrupt() + stderrThread.interrupt() diff --git a/client/src/main/scala/chimp/client/transport/StreamingHttpTransport.scala b/client/src/main/scala/chimp/client/transport/StreamingHttpTransport.scala new file mode 100644 index 0000000..7e55e4f --- /dev/null +++ b/client/src/main/scala/chimp/client/transport/StreamingHttpTransport.scala @@ -0,0 +1,16 @@ +package chimp.client.transport + +import sttp.capabilities.Streams +import sttp.client4.StreamBackend +import sttp.model.Uri + +/** Abstract Streamable HTTP transport using a Streams-capable sttp backend. + * + * Concrete implementations live in per-effect chimp client subprojects (`client-zio`, `client-fs2`) and provide SSE parsing, + * resumability via `Last-Event-ID`, and bidirectional server-initiated dispatch over a long-lived GET. + */ +abstract class StreamingHttpTransport[F[_], S]( + backend: StreamBackend[F, S], + uri: Uri, + streams: Streams[S] +) extends Transport[F] diff --git a/client/src/main/scala/chimp/client/transport/StreamingStdioTransport.scala b/client/src/main/scala/chimp/client/transport/StreamingStdioTransport.scala new file mode 100644 index 0000000..a710810 --- /dev/null +++ b/client/src/main/scala/chimp/client/transport/StreamingStdioTransport.scala @@ -0,0 +1,17 @@ +package chimp.client.transport + +import sttp.capabilities.Streams + +import java.io.File + +/** Abstract async stdio transport using a Streams-capable effect. + * + * Concrete implementations live in per-effect chimp client subprojects (`client-zio`, `client-fs2`) and replace blocking + * `readLine` reads with non-blocking stream consumption tied to the effect's runtime. + */ +abstract class StreamingStdioTransport[F[_], S]( + command: List[String], + env: Map[String, String] = Map.empty, + workDir: Option[File] = None, + streams: Streams[S] +) extends Transport[F] diff --git a/client/src/main/scala/chimp/client/transport/Transport.scala b/client/src/main/scala/chimp/client/transport/Transport.scala new file mode 100644 index 0000000..1147bb0 --- /dev/null +++ b/client/src/main/scala/chimp/client/transport/Transport.scala @@ -0,0 +1,17 @@ +package chimp.client.transport + +import chimp.protocol.JSONRPCMessage +import sttp.monad.MonadError + +/** A bidirectional transport carrying JSON-RPC messages for an MCP client. + * + * - `send(req)` for a `Request` returns the matching `Response` or `Error` from the peer. + * - `send(notif)` for a `Notification` returns `None` once the message has been delivered. + * - `onIncoming(handler)` registers a callback for server-initiated requests and notifications. + * HTTP non-streaming transports never invoke it; stdio and streaming transports do. + */ +trait Transport[F[_]]: + given monad: MonadError[F] + def send(msg: JSONRPCMessage): F[Option[JSONRPCMessage]] + def onIncoming(handler: JSONRPCMessage => F[Unit]): F[Unit] + def close(): F[Unit] diff --git a/client/src/test/scala/chimp/client/HttpTransportSpec.scala b/client/src/test/scala/chimp/client/HttpTransportSpec.scala new file mode 100644 index 0000000..1e7c55b --- /dev/null +++ b/client/src/test/scala/chimp/client/HttpTransportSpec.scala @@ -0,0 +1,43 @@ +package chimp.client + +import chimp.client.transport.HttpTransport +import chimp.protocol.* +import io.circe.Json +import io.circe.syntax.* +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers +import sttp.client4.testing.SyncBackendStub +import sttp.model.StatusCode +import sttp.shared.Identity + +class HttpTransportSpec extends AnyFlatSpec with Matchers: + + private val mcpUri = sttp.model.Uri.parse("http://localhost/mcp").toOption.get + + private def envelope(body: JSONRPCMessage): String = (body: JSONRPCMessage).asJson.noSpaces + + it should "POST a request and decode the response body" in: + val expectedResult = Json.obj("ok" -> Json.fromBoolean(true)) + val backend = SyncBackendStub.whenAnyRequest.thenRespondAdjust( + envelope(JSONRPCMessage.Response(id = RequestId(1), result = expectedResult)), + StatusCode.Ok + ) + + val t = HttpTransport[Identity](backend, mcpUri) + val req: JSONRPCMessage = JSONRPCMessage.Request(method = "x", params = None, id = RequestId(1)) + t.send(req) match + case Some(JSONRPCMessage.Response(_, _, r)) => r shouldBe expectedResult + case other => fail(s"Expected Response, got: $other") + + it should "return None for 202 Accepted (notification ack)" in: + val backend = SyncBackendStub.whenAnyRequest.thenRespondAdjust("", StatusCode.Accepted) + val t = HttpTransport[Identity](backend, mcpUri) + val n: JSONRPCMessage = JSONRPCMessage.Notification(method = "notifications/initialized") + t.send(n) shouldBe None + + it should "fail with McpAuthorizationException on 401" in: + val backend = SyncBackendStub.whenAnyRequest.thenRespondAdjust("", StatusCode.Unauthorized) + val t = HttpTransport[Identity](backend, mcpUri) + val req: JSONRPCMessage = JSONRPCMessage.Request(method = "x", params = None, id = RequestId(1)) + val ex = intercept[McpAuthorizationException](t.send(req)) + ex.statusCode shouldBe 401 diff --git a/client/src/test/scala/chimp/client/McpClientSpec.scala b/client/src/test/scala/chimp/client/McpClientSpec.scala new file mode 100644 index 0000000..675d5db --- /dev/null +++ b/client/src/test/scala/chimp/client/McpClientSpec.scala @@ -0,0 +1,42 @@ +package chimp.client + +import chimp.client.transport.HttpTransport +import chimp.protocol.* +import io.circe.syntax.* +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers +import sttp.client4.testing.SyncBackendStub +import sttp.shared.Identity + +class McpClientSpec extends AnyFlatSpec with Matchers: + + private val mcpUri = sttp.model.Uri.parse("http://localhost/mcp").toOption.get + private val clientInfo = Implementation(name = "chimp-test", version = "0.0.1") + + it should "initialize and read the server's protocol version" in: + val initResult = InitializeResult( + protocolVersion = ProtocolVersion.Latest, + capabilities = ServerCapabilities(), + serverInfo = Implementation(name = "test-server", version = "1.0") + ) + val responseEnvelope = + (JSONRPCMessage.Response(id = RequestId(1), result = initResult.asJson): JSONRPCMessage).asJson.noSpaces + + val backend = SyncBackendStub.whenAnyRequest.thenRespondAdjust(responseEnvelope) + val t = HttpTransport[Identity](backend, mcpUri) + val client = McpClient[Identity, Any](t, clientInfo) + val result = client.initialize() + result.protocolVersion shouldBe ProtocolVersion.Latest + result.serverInfo.name shouldBe "test-server" + + it should "call a tool and decode the result" in: + val callResult = CallToolResult(content = List(ToolContent.Text(text = "hi"))) + val responseEnvelope = + (JSONRPCMessage.Response(id = RequestId(1), result = callResult.asJson): JSONRPCMessage).asJson.noSpaces + + val backend = SyncBackendStub.whenAnyRequest.thenRespondAdjust(responseEnvelope) + val t = HttpTransport[Identity](backend, mcpUri) + val client = McpClient[Identity, Any](t, clientInfo) + val r = client.callTool("echo", io.circe.Json.obj("message" -> io.circe.Json.fromString("hi"))) + r.isError shouldBe false + r.content.head shouldBe ToolContent.Text("text", "hi") From cc3e515354490dd08d9d4ed56c5167352301aaef Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Mon, 11 May 2026 14:56:13 +0200 Subject: [PATCH 05/27] feat: client capabilities, server notifications, full mcp client definition --- .../scala/chimp/client/DefaultMcpClient.scala | 97 +++++++++++++++++-- .../main/scala/chimp/client/McpClient.scala | 31 +++++- .../client/capabilities/CapsDerive.scala | 63 ++++++++++++ .../client/capabilities/Elicitation.scala | 7 ++ .../chimp/client/capabilities/Roots.scala | 7 ++ .../chimp/client/capabilities/Sampling.scala | 7 ++ .../client/internal/CapabilityHandlers.scala | 32 ++++++ .../chimp/client/internal/CapsBuilder.scala | 6 -- .../notifications/ServerNotification.scala | 32 ++++++ .../ServerNotificationListener.scala | 6 ++ .../chimp/client/CapabilityDispatchSpec.scala | 72 ++++++++++++++ .../scala/chimp/client/CapsDeriveSpec.scala | 35 +++++++ .../chimp/client/InMemoryTransport.scala | 35 +++++++ .../chimp/client/ServerNotificationSpec.scala | 32 ++++++ 14 files changed, 445 insertions(+), 17 deletions(-) create mode 100644 client/src/main/scala/chimp/client/capabilities/CapsDerive.scala create mode 100644 client/src/main/scala/chimp/client/capabilities/Elicitation.scala create mode 100644 client/src/main/scala/chimp/client/capabilities/Roots.scala create mode 100644 client/src/main/scala/chimp/client/capabilities/Sampling.scala create mode 100644 client/src/main/scala/chimp/client/internal/CapabilityHandlers.scala delete mode 100644 client/src/main/scala/chimp/client/internal/CapsBuilder.scala create mode 100644 client/src/main/scala/chimp/client/notifications/ServerNotification.scala create mode 100644 client/src/main/scala/chimp/client/notifications/ServerNotificationListener.scala create mode 100644 client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala create mode 100644 client/src/test/scala/chimp/client/CapsDeriveSpec.scala create mode 100644 client/src/test/scala/chimp/client/InMemoryTransport.scala create mode 100644 client/src/test/scala/chimp/client/ServerNotificationSpec.scala diff --git a/client/src/main/scala/chimp/client/DefaultMcpClient.scala b/client/src/main/scala/chimp/client/DefaultMcpClient.scala index e3627b8..75ce645 100644 --- a/client/src/main/scala/chimp/client/DefaultMcpClient.scala +++ b/client/src/main/scala/chimp/client/DefaultMcpClient.scala @@ -1,6 +1,7 @@ package chimp.client -import chimp.client.internal.Correlator +import chimp.client.internal.{CapabilityHandlers, Correlator} +import chimp.client.notifications.ServerNotificationListener import chimp.client.transport.Transport import chimp.protocol.* import io.circe.syntax.* @@ -8,22 +9,59 @@ import io.circe.{Decoder, Json} import sttp.monad.MonadError import sttp.monad.syntax.* +import java.util.concurrent.atomic.AtomicReference + object DefaultMcpClient: def create[F[_], Caps]( transport: Transport[F], clientInfo: Implementation, protocolVersion: String, - wireCaps: ClientCapabilities - ): McpClient[F, Caps] = new Impl[F, Caps](transport, clientInfo, protocolVersion, wireCaps) + wireCaps: ClientCapabilities, + handlers: CapabilityHandlers[F] + ): McpClient[F, Caps] = + val impl = new Impl[F, Caps](transport, clientInfo, protocolVersion, wireCaps, handlers) + impl.installIncoming() + impl private final class Impl[F[_], Caps]( transport: Transport[F], clientInfo: Implementation, protocolVersion: String, - wireCaps: ClientCapabilities + wireCaps: ClientCapabilities, + handlers: CapabilityHandlers[F] ) extends McpClient[F, Caps]: private given MonadError[F] = transport.monad private val correlator = Correlator() + private val listeners = AtomicReference[List[ServerNotificationListener[F]]](Nil) + + def installIncoming(): Unit = + val _ = transport.onIncoming(handleIncoming) + + private def handleIncoming(msg: JSONRPCMessage): F[Unit] = msg match + case JSONRPCMessage.Request(_, method, params, id) => + handlers.methods.get(method) match + case Some(h) => + val rawParams = params.getOrElse(Json.obj()) + h(rawParams).flatMap(result => + transport.send(JSONRPCMessage.Response(id = id, result = result)).map(_ => ()) + ).handleError { case t => + val err = JSONRPCMessage.Error( + id = id, + error = JSONRPCErrorObject(code = JSONRPCErrorCodes.InternalError.code, message = Option(t.getMessage).getOrElse("internal error")) + ) + transport.send(err).map(_ => ()) + } + case None => + val err = JSONRPCMessage.Error( + id = id, + error = JSONRPCErrorObject(code = JSONRPCErrorCodes.MethodNotFound.code, message = s"No handler for method: $method") + ) + transport.send(err).map(_ => ()) + case n: JSONRPCMessage.Notification => + listeners.get().foldLeft(summon[MonadError[F]].unit(())): (acc, l) => + acc.flatMap(_ => l.onNotification(n).handleError(_ => summon[MonadError[F]].unit(()))) + case _ => + summon[MonadError[F]].unit(()) override def initialize(): F[InitializeResult] = val params = InitializeParams( @@ -34,8 +72,7 @@ object DefaultMcpClient: sendRequest[InitializeResult]("initialize", Some(params.asJson)).flatMap: r => sendNotification("notifications/initialized", None).map(_ => r) - override def ping(): F[Unit] = - sendRequest[Json]("ping", None).map(_ => ()) + override def ping(): F[Unit] = sendRequest[Json]("ping", None).map(_ => ()) override def close(): F[Unit] = transport.close() @@ -47,6 +84,54 @@ object DefaultMcpClient: val params = CallToolParams(name = name, arguments = arguments).asJson sendRequest[CallToolResult]("tools/call", Some(params)) + override def listPrompts(cursor: Option[Cursor]): F[ListPromptsResult] = + val params = cursor.map(c => ListPromptsParams(cursor = Some(c)).asJson) + sendRequest[ListPromptsResult]("prompts/list", params) + + override def getPrompt(name: String, arguments: Map[String, String]): F[GetPromptResult] = + val argOpt = if arguments.isEmpty then None else Some(arguments) + val params = GetPromptParams(name = name, arguments = argOpt).asJson + sendRequest[GetPromptResult]("prompts/get", Some(params)) + + override def listResources(cursor: Option[Cursor]): F[ListResourcesResult] = + val params = cursor.map(c => ListResourcesParams(cursor = Some(c)).asJson) + sendRequest[ListResourcesResult]("resources/list", params) + + override def listResourceTemplates(cursor: Option[Cursor]): F[ListResourceTemplatesResult] = + val params = cursor.map(c => ListResourceTemplatesParams(cursor = Some(c)).asJson) + sendRequest[ListResourceTemplatesResult]("resources/templates/list", params) + + override def readResource(uri: String): F[ReadResourceResult] = + sendRequest[ReadResourceResult]("resources/read", Some(ReadResourceParams(uri = uri).asJson)) + + override def subscribeResource(uri: String): F[Unit] = + sendRequest[Json]("resources/subscribe", Some(SubscribeParams(uri = uri).asJson)).map(_ => ()) + + override def unsubscribeResource(uri: String): F[Unit] = + sendRequest[Json]("resources/unsubscribe", Some(UnsubscribeParams(uri = uri).asJson)).map(_ => ()) + + override def complete(ref: CompleteRef, argument: CompleteArgument): F[CompleteResult] = + val params = CompleteParams(ref = ref, argument = argument).asJson + sendRequest[CompleteResult]("completion/complete", Some(params)) + + override def setLoggingLevel(level: LoggingLevel): F[Unit] = + sendRequest[Json]("logging/setLevel", Some(SetLevelParams(level = level).asJson)).map(_ => ()) + + override def sendProgress(token: ProgressToken, progress: Double, total: Option[Double], message: Option[String]): F[Unit] = + val params = ProgressParams(progressToken = token, progress = progress, total = total, message = message).asJson + sendNotification("notifications/progress", Some(params)) + + override def sendCancelled(requestId: RequestId, reason: Option[String]): F[Unit] = + val params = CancelledParams(requestId = requestId, reason = reason).asJson + sendNotification("notifications/cancelled", Some(params)) + + override def sendRootsListChanged(): F[Unit] = + sendNotification("notifications/roots/list_changed", None) + + override def onServerNotification(listener: ServerNotificationListener[F]): F[Unit] = + listeners.updateAndGet(ls => ls :+ listener) + summon[MonadError[F]].unit(()) + private def sendRequest[R: Decoder](method: String, params: Option[Json]): F[R] = val req = JSONRPCMessage.Request(method = method, params = params, id = correlator.nextId()) transport.send(req).flatMap: diff --git a/client/src/main/scala/chimp/client/McpClient.scala b/client/src/main/scala/chimp/client/McpClient.scala index f8a0676..cf3679d 100644 --- a/client/src/main/scala/chimp/client/McpClient.scala +++ b/client/src/main/scala/chimp/client/McpClient.scala @@ -1,9 +1,11 @@ package chimp.client -import chimp.client.internal.CapsBuilder +import chimp.client.capabilities.CapsDerive +import chimp.client.notifications.ServerNotificationListener import chimp.client.transport.Transport import chimp.protocol.* import io.circe.Json +import sttp.monad.MonadError /** An MCP client. The `Caps` type parameter is an intersection of capability typeclasses (`Roots[F]`, `Sampling[F]`, `Elicitation[F]`) * the host application opts into; each one is advertised on `initialize` and routed to the corresponding `given` handler when the @@ -17,11 +19,30 @@ trait McpClient[F[_], +Caps]: def listTools(cursor: Option[Cursor] = None): F[ListToolsResponse] def callTool(name: String, arguments: Json): F[CallToolResult] + def listPrompts(cursor: Option[Cursor] = None): F[ListPromptsResult] + def getPrompt(name: String, arguments: Map[String, String] = Map.empty): F[GetPromptResult] + + def listResources(cursor: Option[Cursor] = None): F[ListResourcesResult] + def listResourceTemplates(cursor: Option[Cursor] = None): F[ListResourceTemplatesResult] + def readResource(uri: String): F[ReadResourceResult] + def subscribeResource(uri: String): F[Unit] + def unsubscribeResource(uri: String): F[Unit] + + def complete(ref: CompleteRef, argument: CompleteArgument): F[CompleteResult] + + def setLoggingLevel(level: LoggingLevel): F[Unit] + + def sendProgress(token: ProgressToken, progress: Double, total: Option[Double] = None, message: Option[String] = None): F[Unit] + def sendCancelled(requestId: RequestId, reason: Option[String] = None): F[Unit] + def sendRootsListChanged(): F[Unit] + + def onServerNotification(listener: ServerNotificationListener[F]): F[Unit] + object McpClient: - inline def apply[F[_], Caps]( + def apply[F[_], Caps]( transport: Transport[F], clientInfo: Implementation, protocolVersion: String = ProtocolVersion.Latest - ): McpClient[F, Caps] = - val wire = CapsBuilder.wire[F, Caps] - DefaultMcpClient.create[F, Caps](transport, clientInfo, protocolVersion, wire) + )(using d: CapsDerive[F, Caps]): McpClient[F, Caps] = + given MonadError[F] = transport.monad + DefaultMcpClient.create[F, Caps](transport, clientInfo, protocolVersion, d.wire, d.handlers) diff --git a/client/src/main/scala/chimp/client/capabilities/CapsDerive.scala b/client/src/main/scala/chimp/client/capabilities/CapsDerive.scala new file mode 100644 index 0000000..261d860 --- /dev/null +++ b/client/src/main/scala/chimp/client/capabilities/CapsDerive.scala @@ -0,0 +1,63 @@ +package chimp.client.capabilities + +import chimp.client.internal.CapabilityHandlers +import chimp.protocol.{ClientCapabilities, ClientRootsCapability} +import io.circe.Json +import sttp.monad.MonadError + +/** Derives the wire-level [[ClientCapabilities]] and the runtime handler table for a `Caps` intersection type. + * + * `Caps = Any` produces empty capabilities; each capability typeclass (`Roots[F]`, `Sampling[F]`, `Elicitation[F]`) listed in + * `Caps` requires a matching `given` instance in scope. + */ +trait CapsDerive[F[_], Caps]: + def wire: ClientCapabilities + def handlers(using MonadError[F]): CapabilityHandlers[F] + +object CapsDerive: + + given empty[F[_]]: CapsDerive[F, Any] with + def wire = ClientCapabilities() + def handlers(using MonadError[F]) = CapabilityHandlers.empty[F] + + given roots[F[_]](using r: Roots[F]): CapsDerive[F, Roots[F]] with + def wire = ClientCapabilities(roots = Some(ClientRootsCapability(listChanged = Some(true)))) + def handlers(using MonadError[F]) = CapabilityHandlers.roots(r) + + given sampling[F[_]](using s: Sampling[F]): CapsDerive[F, Sampling[F]] with + def wire = ClientCapabilities(sampling = Some(Json.obj())) + def handlers(using MonadError[F]) = CapabilityHandlers.sampling(s) + + given elicitation[F[_]](using e: Elicitation[F]): CapsDerive[F, Elicitation[F]] with + def wire = ClientCapabilities(elicitation = Some(Json.obj())) + def handlers(using MonadError[F]) = CapabilityHandlers.elicitation(e) + + given rootsSampling[F[_]](using r: Roots[F], s: Sampling[F]): CapsDerive[F, Roots[F] & Sampling[F]] with + def wire = ClientCapabilities( + roots = Some(ClientRootsCapability(listChanged = Some(true))), + sampling = Some(Json.obj()) + ) + def handlers(using MonadError[F]) = CapabilityHandlers.roots(r) ++ CapabilityHandlers.sampling(s) + + given rootsElicitation[F[_]](using r: Roots[F], e: Elicitation[F]): CapsDerive[F, Roots[F] & Elicitation[F]] with + def wire = ClientCapabilities( + roots = Some(ClientRootsCapability(listChanged = Some(true))), + elicitation = Some(Json.obj()) + ) + def handlers(using MonadError[F]) = CapabilityHandlers.roots(r) ++ CapabilityHandlers.elicitation(e) + + given samplingElicitation[F[_]](using s: Sampling[F], e: Elicitation[F]): CapsDerive[F, Sampling[F] & Elicitation[F]] with + def wire = ClientCapabilities( + sampling = Some(Json.obj()), + elicitation = Some(Json.obj()) + ) + def handlers(using MonadError[F]) = CapabilityHandlers.sampling(s) ++ CapabilityHandlers.elicitation(e) + + given all[F[_]](using r: Roots[F], s: Sampling[F], e: Elicitation[F]): CapsDerive[F, Roots[F] & Sampling[F] & Elicitation[F]] with + def wire = ClientCapabilities( + roots = Some(ClientRootsCapability(listChanged = Some(true))), + sampling = Some(Json.obj()), + elicitation = Some(Json.obj()) + ) + def handlers(using MonadError[F]) = + CapabilityHandlers.roots(r) ++ CapabilityHandlers.sampling(s) ++ CapabilityHandlers.elicitation(e) diff --git a/client/src/main/scala/chimp/client/capabilities/Elicitation.scala b/client/src/main/scala/chimp/client/capabilities/Elicitation.scala new file mode 100644 index 0000000..38e37ae --- /dev/null +++ b/client/src/main/scala/chimp/client/capabilities/Elicitation.scala @@ -0,0 +1,7 @@ +package chimp.client.capabilities + +import chimp.protocol.{ElicitRequest, ElicitResult} + +/** Host-side handler for `elicitation/create` requests from the server. Required when the client advertises the `elicitation` capability. */ +trait Elicitation[F[_]]: + def elicit(req: ElicitRequest): F[ElicitResult] diff --git a/client/src/main/scala/chimp/client/capabilities/Roots.scala b/client/src/main/scala/chimp/client/capabilities/Roots.scala new file mode 100644 index 0000000..0722ca1 --- /dev/null +++ b/client/src/main/scala/chimp/client/capabilities/Roots.scala @@ -0,0 +1,7 @@ +package chimp.client.capabilities + +import chimp.protocol.ListRootsResult + +/** Host-side handler for `roots/list` requests from the server. Required when the client advertises the `roots` capability. */ +trait Roots[F[_]]: + def list(): F[ListRootsResult] diff --git a/client/src/main/scala/chimp/client/capabilities/Sampling.scala b/client/src/main/scala/chimp/client/capabilities/Sampling.scala new file mode 100644 index 0000000..5d54ada --- /dev/null +++ b/client/src/main/scala/chimp/client/capabilities/Sampling.scala @@ -0,0 +1,7 @@ +package chimp.client.capabilities + +import chimp.protocol.{CreateMessageRequest, CreateMessageResult} + +/** Host-side handler for `sampling/createMessage` requests from the server. Required when the client advertises the `sampling` capability. */ +trait Sampling[F[_]]: + def createMessage(req: CreateMessageRequest): F[CreateMessageResult] diff --git a/client/src/main/scala/chimp/client/internal/CapabilityHandlers.scala b/client/src/main/scala/chimp/client/internal/CapabilityHandlers.scala new file mode 100644 index 0000000..371896c --- /dev/null +++ b/client/src/main/scala/chimp/client/internal/CapabilityHandlers.scala @@ -0,0 +1,32 @@ +package chimp.client.internal + +import chimp.client.capabilities.{Elicitation, Roots, Sampling} +import chimp.protocol.{CreateMessageRequest, ElicitRequest} +import io.circe.syntax.* +import io.circe.{Json, parser} +import sttp.monad.MonadError +import sttp.monad.syntax.* + +private[chimp] final case class CapabilityHandlers[F[_]](methods: Map[String, Json => F[Json]]): + def ++(other: CapabilityHandlers[F]): CapabilityHandlers[F] = + CapabilityHandlers(methods ++ other.methods) + +private[chimp] object CapabilityHandlers: + def empty[F[_]]: CapabilityHandlers[F] = CapabilityHandlers(Map.empty) + + def roots[F[_]](r: Roots[F])(using me: MonadError[F]): CapabilityHandlers[F] = + CapabilityHandlers(Map("roots/list" -> (_ => r.list().map(_.asJson)))) + + def sampling[F[_]](s: Sampling[F])(using me: MonadError[F]): CapabilityHandlers[F] = + CapabilityHandlers(Map("sampling/createMessage" -> { params => + params.as[CreateMessageRequest] match + case Right(req) => s.createMessage(req).map(_.asJson) + case Left(e) => me.error(IllegalArgumentException(s"Failed to decode CreateMessageRequest: ${e.getMessage}")) + })) + + def elicitation[F[_]](e: Elicitation[F])(using me: MonadError[F]): CapabilityHandlers[F] = + CapabilityHandlers(Map("elicitation/create" -> { params => + params.as[ElicitRequest] match + case Right(req) => e.elicit(req).map(_.asJson) + case Left(err) => me.error(IllegalArgumentException(s"Failed to decode ElicitRequest: ${err.getMessage}")) + })) diff --git a/client/src/main/scala/chimp/client/internal/CapsBuilder.scala b/client/src/main/scala/chimp/client/internal/CapsBuilder.scala deleted file mode 100644 index ba09ed6..0000000 --- a/client/src/main/scala/chimp/client/internal/CapsBuilder.scala +++ /dev/null @@ -1,6 +0,0 @@ -package chimp.client.internal - -import chimp.protocol.ClientCapabilities - -object CapsBuilder: - inline def wire[F[_], Caps]: ClientCapabilities = ClientCapabilities() diff --git a/client/src/main/scala/chimp/client/notifications/ServerNotification.scala b/client/src/main/scala/chimp/client/notifications/ServerNotification.scala new file mode 100644 index 0000000..c2dac64 --- /dev/null +++ b/client/src/main/scala/chimp/client/notifications/ServerNotification.scala @@ -0,0 +1,32 @@ +package chimp.client.notifications + +import chimp.protocol.* +import io.circe.Json + +/** A parsed, strongly-typed view of an incoming server-to-client notification. */ +enum ServerNotification: + case Progress(params: ProgressParams) + case Cancelled(params: CancelledParams) + case ResourceUpdated(params: ResourceUpdatedParams) + case ToolsListChanged + case PromptsListChanged + case ResourcesListChanged + case LoggingMessage(params: LoggingMessageParams) + case Unknown(method: String, params: Option[Json]) + +object ServerNotification: + def parse(n: JSONRPCMessage.Notification): ServerNotification = + val params = n.params + n.method match + case "notifications/progress" => + params.flatMap(_.as[ProgressParams].toOption).map(Progress(_)).getOrElse(Unknown(n.method, params)) + case "notifications/cancelled" => + params.flatMap(_.as[CancelledParams].toOption).map(Cancelled(_)).getOrElse(Unknown(n.method, params)) + case "notifications/resources/updated" => + params.flatMap(_.as[ResourceUpdatedParams].toOption).map(ResourceUpdated(_)).getOrElse(Unknown(n.method, params)) + case "notifications/tools/list_changed" => ToolsListChanged + case "notifications/prompts/list_changed" => PromptsListChanged + case "notifications/resources/list_changed" => ResourcesListChanged + case "notifications/message" => + params.flatMap(_.as[LoggingMessageParams].toOption).map(LoggingMessage(_)).getOrElse(Unknown(n.method, params)) + case other => Unknown(other, params) diff --git a/client/src/main/scala/chimp/client/notifications/ServerNotificationListener.scala b/client/src/main/scala/chimp/client/notifications/ServerNotificationListener.scala new file mode 100644 index 0000000..8b9591e --- /dev/null +++ b/client/src/main/scala/chimp/client/notifications/ServerNotificationListener.scala @@ -0,0 +1,6 @@ +package chimp.client.notifications + +import chimp.protocol.JSONRPCMessage + +trait ServerNotificationListener[F[_]]: + def onNotification(n: JSONRPCMessage.Notification): F[Unit] diff --git a/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala b/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala new file mode 100644 index 0000000..5730775 --- /dev/null +++ b/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala @@ -0,0 +1,72 @@ +package chimp.client + +import chimp.client.capabilities.{Elicitation, Roots} +import chimp.client.notifications.{ServerNotification, ServerNotificationListener} +import chimp.protocol.* +import io.circe.syntax.* +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers +import sttp.shared.Identity + +class CapabilityDispatchSpec extends AnyFlatSpec with Matchers: + + private val clientInfo = Implementation(name = "chimp-test", version = "0.0.1") + + it should "respond to a server-initiated roots/list with the registered handler's result" in: + given Roots[Identity] = () => ListRootsResult(roots = List(Root(uri = "file:///x", name = Some("x")))) + val t = InMemoryTransport() + val _ = McpClient[Identity, Roots[Identity]](t, clientInfo) + + val req: JSONRPCMessage = JSONRPCMessage.Request(method = "roots/list", id = RequestId("server-1")) + t.simulateIncoming(req) + + t.sent.last match + case JSONRPCMessage.Response(_, _, result) => + val r = result.as[ListRootsResult].toOption.get + r.roots.head.name shouldBe Some("x") + case other => fail(s"Expected Response, got $other") + + it should "respond with MethodNotFound for capabilities the client didn't opt into" in: + val t = InMemoryTransport() + val _ = McpClient[Identity, Any](t, clientInfo) + + val req: JSONRPCMessage = JSONRPCMessage.Request(method = "sampling/createMessage", id = RequestId("server-2")) + t.simulateIncoming(req) + + t.sent.last match + case JSONRPCMessage.Error(_, _, err) => err.code shouldBe JSONRPCErrorCodes.MethodNotFound.code + case other => fail(s"Expected Error, got $other") + + it should "deliver incoming notifications to registered listeners" in: + val t = InMemoryTransport() + val client = McpClient[Identity, Any](t, clientInfo) + var received: Option[ServerNotification] = None + val listener: ServerNotificationListener[Identity] = n => { received = Some(ServerNotification.parse(n)); () } + client.onServerNotification(listener) + + val params = ProgressParams(progressToken = ProgressToken("p1"), progress = 0.42) + val notif: JSONRPCMessage = JSONRPCMessage.Notification(method = "notifications/progress", params = Some(params.asJson)) + t.simulateIncoming(notif) + + received shouldBe Some(ServerNotification.Progress(params)) + + it should "include opted-in capabilities on initialize" in: + given Roots[Identity] = () => ListRootsResult(roots = Nil) + given Elicitation[Identity] = (_: ElicitRequest) => ElicitResult(action = ElicitAction.Cancel) + val t = InMemoryTransport() + val initResult = InitializeResult( + protocolVersion = ProtocolVersion.Latest, + capabilities = ServerCapabilities(), + serverInfo = Implementation(name = "s", version = "1") + ) + t.planResponse(JSONRPCMessage.Response(id = RequestId(1), result = initResult.asJson)) + val client = McpClient[Identity, Roots[Identity] & Elicitation[Identity]](t, clientInfo) + client.initialize() + + t.sent.head match + case r: JSONRPCMessage.Request => + val params = r.params.get.as[InitializeParams].toOption.get + params.capabilities.roots.isDefined shouldBe true + params.capabilities.elicitation.isDefined shouldBe true + params.capabilities.sampling shouldBe None + case other => fail(s"Expected Request, got $other") diff --git a/client/src/test/scala/chimp/client/CapsDeriveSpec.scala b/client/src/test/scala/chimp/client/CapsDeriveSpec.scala new file mode 100644 index 0000000..41b2b81 --- /dev/null +++ b/client/src/test/scala/chimp/client/CapsDeriveSpec.scala @@ -0,0 +1,35 @@ +package chimp.client + +import chimp.client.capabilities.{CapsDerive, Elicitation, Roots, Sampling} +import chimp.protocol.{ClientCapabilities, ElicitRequest, ElicitResult, ListRootsResult} +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers +import sttp.monad.IdentityMonad +import sttp.shared.Identity + +class CapsDeriveSpec extends AnyFlatSpec with Matchers: + + given sttp.monad.MonadError[Identity] = IdentityMonad + + it should "produce empty ClientCapabilities for Caps = Any" in: + val d = summon[CapsDerive[Identity, Any]] + d.wire shouldBe ClientCapabilities() + d.handlers.methods shouldBe Map.empty + + it should "advertise roots when only Roots is provided" in: + given Roots[Identity] = () => ListRootsResult(roots = Nil) + val d = summon[CapsDerive[Identity, Roots[Identity]]] + d.wire.roots.isDefined shouldBe true + d.wire.sampling shouldBe None + d.wire.elicitation shouldBe None + d.handlers.methods.keySet shouldBe Set("roots/list") + + it should "advertise multiple capabilities for an intersection type" in: + given Roots[Identity] = () => ListRootsResult(roots = Nil) + given Elicitation[Identity] = (_: ElicitRequest) => + ElicitResult(action = chimp.protocol.ElicitAction.Cancel) + val d = summon[CapsDerive[Identity, Roots[Identity] & Elicitation[Identity]]] + d.wire.roots.isDefined shouldBe true + d.wire.elicitation.isDefined shouldBe true + d.wire.sampling shouldBe None + d.handlers.methods.keySet shouldBe Set("roots/list", "elicitation/create") diff --git a/client/src/test/scala/chimp/client/InMemoryTransport.scala b/client/src/test/scala/chimp/client/InMemoryTransport.scala new file mode 100644 index 0000000..a042af7 --- /dev/null +++ b/client/src/test/scala/chimp/client/InMemoryTransport.scala @@ -0,0 +1,35 @@ +package chimp.client + +import chimp.client.transport.Transport +import chimp.protocol.JSONRPCMessage +import sttp.monad.{IdentityMonad, MonadError} +import sttp.shared.Identity + +import java.util.concurrent.atomic.AtomicReference +import scala.collection.mutable + +final class InMemoryTransport extends Transport[Identity]: + given monad: MonadError[Identity] = IdentityMonad + + private val incomingHandler = AtomicReference[JSONRPCMessage => Identity[Unit]](_ => ()) + val sent: mutable.ListBuffer[JSONRPCMessage] = mutable.ListBuffer.empty + private val plannedResponses = mutable.Queue[JSONRPCMessage]() + + def planResponse(msg: JSONRPCMessage): Unit = plannedResponses.enqueue(msg) + def simulateIncoming(msg: JSONRPCMessage): Unit = incomingHandler.get()(msg) + def closed: Boolean = closedFlag + + private var closedFlag = false + + override def send(msg: JSONRPCMessage): Identity[Option[JSONRPCMessage]] = + sent.append(msg) + msg match + case _: JSONRPCMessage.Request => + if plannedResponses.nonEmpty then Some(plannedResponses.dequeue()) else None + case _ => None + + override def onIncoming(handler: JSONRPCMessage => Identity[Unit]): Identity[Unit] = + incomingHandler.set(handler) + + override def close(): Identity[Unit] = + closedFlag = true diff --git a/client/src/test/scala/chimp/client/ServerNotificationSpec.scala b/client/src/test/scala/chimp/client/ServerNotificationSpec.scala new file mode 100644 index 0000000..51abced --- /dev/null +++ b/client/src/test/scala/chimp/client/ServerNotificationSpec.scala @@ -0,0 +1,32 @@ +package chimp.client + +import chimp.client.notifications.ServerNotification +import chimp.protocol.* +import io.circe.Json +import io.circe.syntax.* +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers + +class ServerNotificationSpec extends AnyFlatSpec with Matchers: + + it should "parse a progress notification" in: + val params = ProgressParams(progressToken = ProgressToken("t1"), progress = 0.5, total = Some(1.0)) + val n = JSONRPCMessage.Notification(method = "notifications/progress", params = Some(params.asJson)) + ServerNotification.parse(n) shouldBe ServerNotification.Progress(params) + + it should "parse a cancelled notification" in: + val params = CancelledParams(requestId = RequestId(7), reason = Some("user cancelled")) + val n = JSONRPCMessage.Notification(method = "notifications/cancelled", params = Some(params.asJson)) + ServerNotification.parse(n) shouldBe ServerNotification.Cancelled(params) + + it should "parse list_changed notifications without params" in: + val toolsN: JSONRPCMessage.Notification = JSONRPCMessage.Notification(method = "notifications/tools/list_changed") + val resourcesN: JSONRPCMessage.Notification = JSONRPCMessage.Notification(method = "notifications/resources/list_changed") + val promptsN: JSONRPCMessage.Notification = JSONRPCMessage.Notification(method = "notifications/prompts/list_changed") + ServerNotification.parse(toolsN) shouldBe ServerNotification.ToolsListChanged + ServerNotification.parse(resourcesN) shouldBe ServerNotification.ResourcesListChanged + ServerNotification.parse(promptsN) shouldBe ServerNotification.PromptsListChanged + + it should "fall back to Unknown for unrecognised methods" in: + val n: JSONRPCMessage.Notification = JSONRPCMessage.Notification(method = "notifications/unknown", params = Some(Json.obj())) + ServerNotification.parse(n) shouldBe ServerNotification.Unknown("notifications/unknown", Some(Json.obj())) From 7ca3ded41663438450374e31c8ef6fcf53d975bd Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Tue, 12 May 2026 10:34:56 +0200 Subject: [PATCH 06/27] feat: integrate conformance tests into client and server, baseline with expected failures --- build.sbt | 108 +++++++++++++++++- .../bin/chimp-conformance-client | 9 ++ .../src/main/resources/logback.xml | 11 ++ .../scala/chimp/conformance/client/Main.scala | 62 ++++++++++ .../client/transport/HttpTransport.scala | 29 ++++- conformance-baseline.yml | 54 +++++++++ .../src/main/scala/chimp/protocol/Tools.scala | 12 +- project/plugins.sbt | 1 + .../src/main/resources/logback.xml | 11 ++ .../scala/chimp/conformance/server/Main.scala | 43 +++++++ .../main/scala/chimp/server/McpHandler.scala | 16 +-- .../scala/chimp/server/McpHandlerSpec.scala | 5 +- 12 files changed, 345 insertions(+), 16 deletions(-) create mode 100755 client-conformance/bin/chimp-conformance-client create mode 100644 client-conformance/src/main/resources/logback.xml create mode 100644 client-conformance/src/main/scala/chimp/conformance/client/Main.scala create mode 100644 conformance-baseline.yml create mode 100644 server-conformance/src/main/resources/logback.xml create mode 100644 server-conformance/src/main/scala/chimp/conformance/server/Main.scala diff --git a/build.sbt b/build.sbt index 207d3eb..226ca73 100644 --- a/build.sbt +++ b/build.sbt @@ -28,7 +28,9 @@ val scalaTest = "org.scalatest" %% "scalatest" % scalaTestV % Test lazy val rootProject = (project in file(".")) .settings(commonSettings: _*) .settings(publishArtifact := false, name := "chimp") - .aggregate(core, server, client, examples) + .aggregate(core, server, client, examples, serverConformance, clientConformance) + +val conformance = inputKey[Unit]("Run the MCP conformance harness via npx against this subproject. Extra args are passed through.") lazy val core: Project = (project in file("core")) .settings(commonSettings: _*) @@ -82,3 +84,107 @@ lazy val examples = (project in file("examples")) verifyExamplesCompileUsingScalaCli := VerifyExamplesCompileUsingScalaCli(sLog.value, sourceDirectory.value) ) .dependsOn(server) + +import sbtassembly.AssemblyPlugin.autoImport.* + +lazy val assemblySettings = Seq( + assembly / assemblyMergeStrategy := { + case PathList("META-INF", "MANIFEST.MF") => MergeStrategy.discard + case PathList("META-INF", "INDEX.LIST") => MergeStrategy.discard + case PathList("META-INF", "DEPENDENCIES") => MergeStrategy.discard + case PathList("META-INF", "services", _ @ _*) => MergeStrategy.concat + case PathList("META-INF", xs @ _*) if xs.lastOption.exists(s => s.endsWith(".SF") || s.endsWith(".DSA") || s.endsWith(".RSA")) => + MergeStrategy.discard + case PathList("META-INF", _ @ _*) => MergeStrategy.first + case PathList("module-info.class") => MergeStrategy.discard + case _ => MergeStrategy.first + } +) + +lazy val serverConformance = (project in file("server-conformance")) + .enablePlugins(AssemblyPlugin) + .settings(commonSettings: _*) + .settings(assemblySettings: _*) + .settings( + publishArtifact := false, + name := "server-conformance", + Compile / mainClass := Some("chimp.conformance.server.Main"), + assembly / assemblyJarName := "chimp-server-conformance.jar", + libraryDependencies ++= Seq( + "com.softwaremill.sttp.tapir" %% "tapir-netty-server-sync" % tapirV, + "ch.qos.logback" % "logback-classic" % "1.5.32" + ), + conformance := { + import complete.DefaultParsers.* + import scala.sys.process.* + val args = spaceDelimited("").parsed.toList + val jar = assembly.value + val rootDir = (LocalRootProject / baseDirectory).value + val baseline = (rootDir / "conformance-baseline.yml").getAbsolutePath + val log = streams.value.log + + val urlPromise = scala.concurrent.Promise[String]() + val pb = new java.lang.ProcessBuilder("java", "-jar", jar.getAbsolutePath).redirectErrorStream(false) + val proc = pb.start() + val readerThread = new Thread(new Runnable { + def run(): Unit = { + val reader = new java.io.BufferedReader(new java.io.InputStreamReader(proc.getInputStream, "UTF-8")) + try { + val line = reader.readLine() + if (line != null && line.startsWith("http")) urlPromise.trySuccess(line.trim) + else urlPromise.tryFailure(new RuntimeException(s"Server did not print a URL; first line was: $line")) + var more: String = reader.readLine() + while (more != null) { + log.info(s"[server] $more") + more = reader.readLine() + } + } catch { + case t: Throwable => urlPromise.tryFailure(t) + } + } + }) + readerThread.setDaemon(true) + readerThread.start() + + try { + val url = scala.concurrent.Await.result(urlPromise.future, scala.concurrent.duration.Duration("15s")) + log.info(s"Server started at $url") + val cmd = List("npx", "@modelcontextprotocol/conformance") ++ args ++ + List("--url", url, "--expected-failures", baseline) + val rc = Process(cmd, rootDir).! + if (rc != 0) sys.error(s"conformance harness exited with code $rc") + } finally { + proc.destroy() + if (!proc.waitFor(2, java.util.concurrent.TimeUnit.SECONDS)) proc.destroyForcibly() + } + } + ) + .dependsOn(server) + +lazy val clientConformance = (project in file("client-conformance")) + .enablePlugins(AssemblyPlugin) + .settings(commonSettings: _*) + .settings(assemblySettings: _*) + .settings( + publishArtifact := false, + name := "client-conformance", + Compile / mainClass := Some("chimp.conformance.client.Main"), + assembly / assemblyJarName := "chimp-client-conformance.jar", + libraryDependencies ++= Seq( + "ch.qos.logback" % "logback-classic" % "1.5.32" + ), + conformance := { + import complete.DefaultParsers.* + import scala.sys.process.* + val args = spaceDelimited("").parsed.toList + val _ = assembly.value + val baseDir = baseDirectory.value + val rootDir = (LocalRootProject / baseDirectory).value + val wrapper = (baseDir / "bin" / "chimp-conformance-client").getAbsolutePath + val cmd = List("npx", "@modelcontextprotocol/conformance") ++ args ++ + List("--command", wrapper, "--expected-failures", (rootDir / "conformance-baseline.yml").getAbsolutePath) + val rc = Process(cmd, rootDir).! + if (rc != 0) sys.error(s"conformance harness exited with code $rc") + } + ) + .dependsOn(client) diff --git a/client-conformance/bin/chimp-conformance-client b/client-conformance/bin/chimp-conformance-client new file mode 100755 index 0000000..e809765 --- /dev/null +++ b/client-conformance/bin/chimp-conformance-client @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +JAR="${DIR}/../target/scala-3.3.7/chimp-client-conformance.jar" +if [[ ! -f "${JAR}" ]]; then + echo "Fat jar not found at ${JAR}. Run 'sbt clientConformance/assembly' first." >&2 + exit 127 +fi +exec java -jar "${JAR}" "$@" diff --git a/client-conformance/src/main/resources/logback.xml b/client-conformance/src/main/resources/logback.xml new file mode 100644 index 0000000..ed7cd38 --- /dev/null +++ b/client-conformance/src/main/resources/logback.xml @@ -0,0 +1,11 @@ + + + System.err + + %d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n + + + + + + diff --git a/client-conformance/src/main/scala/chimp/conformance/client/Main.scala b/client-conformance/src/main/scala/chimp/conformance/client/Main.scala new file mode 100644 index 0000000..d1d3533 --- /dev/null +++ b/client-conformance/src/main/scala/chimp/conformance/client/Main.scala @@ -0,0 +1,62 @@ +package chimp.conformance.client + +import chimp.client.McpClient +import chimp.client.transport.HttpTransport +import chimp.protocol.* +import io.circe.Json +import sttp.client4.DefaultSyncBackend +import sttp.shared.Identity + +object Main: + + private val clientInfo = Implementation(name = "chimp-conformance-client", version = "0.1.0") + + def main(args: Array[String]): Unit = + if args.isEmpty then + System.err.println("Usage: chimp-conformance-client ") + sys.exit(2) + + val serverUrl = sttp.model.Uri.parse(args.last) match + case Right(u) => u + case Left(e) => System.err.println(s"Invalid server URL: $e"); sys.exit(2) + + val scenario = sys.env.getOrElse("MCP_CONFORMANCE_SCENARIO", "") + val protocolVersion = sys.env.get("MCP_CONFORMANCE_PROTOCOL_VERSION").getOrElse(ProtocolVersion.Latest) + + val backend = DefaultSyncBackend() + val transport = HttpTransport[Identity](backend, serverUrl, protocolVersion) + + val rc: Int = + try + scenario match + case "initialize" => + val client = McpClient[Identity, Any](transport, clientInfo, protocolVersion) + client.initialize() + client.close() + 0 + + case "tools_call" => + val client = McpClient[Identity, Any](transport, clientInfo, protocolVersion) + client.initialize() + client.callTool( + "add_numbers", + Json.obj("a" -> Json.fromInt(2), "b" -> Json.fromInt(3)) + ) + client.close() + 0 + + case s if s == "elicitation-sep1034-client-defaults" || s == "sse-retry" || s.startsWith("auth/") => + 2 + + case other => + System.err.println(s"Scenario not implemented: $other") + 3 + catch + case t: Throwable => + t.printStackTrace() + 1 + finally + try backend.close() + catch case _: Throwable => () + + sys.exit(rc) diff --git a/client/src/main/scala/chimp/client/transport/HttpTransport.scala b/client/src/main/scala/chimp/client/transport/HttpTransport.scala index a718dc7..5bc78e6 100644 --- a/client/src/main/scala/chimp/client/transport/HttpTransport.scala +++ b/client/src/main/scala/chimp/client/transport/HttpTransport.scala @@ -12,6 +12,19 @@ import sttp.monad.syntax.* import java.util.concurrent.atomic.AtomicReference /** Non-streaming Streamable HTTP transport. Works against any sttp `Backend[F]`. */ +object HttpTransport: + private[transport] def extractSingleSseData(body: String): Option[String] = + val blocks: List[String] = body.split("\\r?\\n\\r?\\n", -1).toList + val events: List[sttp.model.sse.ServerSentEvent] = blocks.map: block => + val lines: List[String] = block.split("\\r?\\n", -1).toList + sttp.model.sse.ServerSentEvent.parse(lines) + events.flatMap(_.data).find(_.nonEmpty) + + private[transport] def isAckLike(json: String): Boolean = + parser.parse(json) match + case Right(j) => j.hcursor.downField("id").focus.isEmpty + case Left(_) => false + final class HttpTransport[F[_]]( backend: Backend[F], uri: Uri, @@ -40,9 +53,19 @@ final class HttpTransport[F[_]]( case StatusCode.Ok => response.body match case Right(bodyStr) => - parser.decode[JSONRPCMessage](bodyStr) match - case Right(m) => monad.unit(Some(m)) - case Left(e) => monad.error(McpProtocolException(s"Failed to decode response body: ${e.getMessage}")) + val contentType = response.header("Content-Type").getOrElse("") + val payload = + if contentType.contains("text/event-stream") then HttpTransport.extractSingleSseData(bodyStr) + else if bodyStr.isEmpty then None + else Some(bodyStr) + payload match + case None => monad.unit(None) + case Some(json) => + if HttpTransport.isAckLike(json) then monad.unit(None) + else + parser.decode[JSONRPCMessage](json) match + case Right(m) => monad.unit(Some(m)) + case Left(e) => monad.error(McpProtocolException(s"Failed to decode response body: ${e.getMessage}; payload=$json")) case Left(err) => monad.error(McpTransportException(s"HTTP 200 with empty body: $err")) case StatusCode.Accepted => diff --git a/conformance-baseline.yml b/conformance-baseline.yml new file mode 100644 index 0000000..2eb1a2e --- /dev/null +++ b/conformance-baseline.yml @@ -0,0 +1,54 @@ +server: + - tools-call-image + - tools-call-audio + - tools-call-mixed-content + - tools-call-embedded-resource + - tools-call-with-progress + - tools-call-with-logging + - tools-call-sampling + - tools-call-elicitation + - json-schema-2020-12 + - elicitation-sep1034-defaults + - elicitation-sep1330-enums + - resources-list + - resources-read-text + - resources-read-binary + - resources-templates-read + - resources-subscribe + - resources-unsubscribe + - sep-2164-resource-not-found + - prompts-list + - prompts-get-simple + - prompts-get-with-args + - prompts-get-embedded-resource + - prompts-get-with-image + - logging-set-level + - completion-complete + - server-sse-polling + - server-sse-multiple-streams + - dns-rebinding-protection +client: + - elicitation-sep1034-client-defaults + - sse-retry + - auth/metadata-default + - auth/metadata-var1 + - auth/metadata-var2 + - auth/metadata-var3 + - auth/basic-cimd + - auth/scope-from-www-authenticate + - auth/scope-from-scopes-supported + - auth/scope-omitted-when-undefined + - auth/scope-step-up + - auth/scope-retry-limit + - auth/token-endpoint-auth-basic + - auth/token-endpoint-auth-post + - auth/token-endpoint-auth-none + - auth/pre-registration + - auth/client-credentials-jwt + - auth/client-credentials-basic + - auth/cross-app-access-complete-flow + - auth/2025-03-26-oauth-metadata-backcompat + - auth/2025-03-26-oauth-endpoint-fallback + - auth/resource-mismatch + - auth/offline-access-scope + - auth/offline-access-not-supported diff --git a/core/src/main/scala/chimp/protocol/Tools.scala b/core/src/main/scala/chimp/protocol/Tools.scala index 0c7ef8f..9c7acbc 100644 --- a/core/src/main/scala/chimp/protocol/Tools.scala +++ b/core/src/main/scala/chimp/protocol/Tools.scala @@ -118,6 +118,16 @@ final case class CallToolResult( structuredContent: Option[Json] = None, isError: Boolean = false, _meta: Option[Map[String, Json]] = None -) derives Codec +) + +object CallToolResult: + given Encoder[CallToolResult] = Encoder.AsObject.derived[CallToolResult] + given Decoder[CallToolResult] = Decoder.instance: c => + for + content <- c.downField("content").as[List[ToolContent]] + structuredContent <- c.downField("structuredContent").as[Option[Json]] + isError <- c.downField("isError").as[Option[Boolean]] + meta <- c.downField("_meta").as[Option[Map[String, Json]]] + yield CallToolResult(content, structuredContent, isError.getOrElse(false), meta) final case class ToolListChangedNotification(method: String = "notifications/tools/list_changed") derives Codec diff --git a/project/plugins.sbt b/project/plugins.sbt index bcb67fa..b59b9bc 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -4,3 +4,4 @@ addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-common" % s addSbtPlugin("com.softwaremill.sbt-softwaremill" % "sbt-softwaremill-publish" % sbtSoftwareMillVersion) addSbtPlugin("org.scalameta" % "sbt-mdoc" % "2.9.0") addSbtPlugin("io.spray" % "sbt-revolver" % "0.10.0") +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.3.1") diff --git a/server-conformance/src/main/resources/logback.xml b/server-conformance/src/main/resources/logback.xml new file mode 100644 index 0000000..ed7cd38 --- /dev/null +++ b/server-conformance/src/main/resources/logback.xml @@ -0,0 +1,11 @@ + + + System.err + + %d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n + + + + + + diff --git a/server-conformance/src/main/scala/chimp/conformance/server/Main.scala b/server-conformance/src/main/scala/chimp/conformance/server/Main.scala new file mode 100644 index 0000000..c8465f8 --- /dev/null +++ b/server-conformance/src/main/scala/chimp/conformance/server/Main.scala @@ -0,0 +1,43 @@ +package chimp.conformance.server + +import chimp.server.* +import io.circe.Codec +import ox.supervised +import sttp.tapir.Schema +import sttp.tapir.server.netty.sync.NettySyncServer + +object Main: + + case class AddNumbersInput(a: Double, b: Double) derives Codec, Schema + case class NoInput() derives Codec, Schema + + private val addNumbers = tool("add_numbers") + .description("Adds two numbers and returns the result as text.") + .input[AddNumbersInput] + .handle(in => Right((in.a + in.b).toString)) + + private val simpleText = tool("test_simple_text") + .description("Returns a fixed text string.") + .input[NoInput] + .handle(_ => Right("This is a simple text response for testing.")) + + private val errorTool = tool("test_error_handling") + .description("Always returns an error result.") + .input[NoInput] + .handle(_ => Left("This tool intentionally returns an error for testing")) + + private val tools = List(addNumbers, simpleText, errorTool) + + def main(args: Array[String]): Unit = + val requestedPort = args + .collectFirst { case s"--port=$p" => p.toInt } + .orElse(sys.env.get("CHIMP_CONFORMANCE_PORT").map(_.toInt)) + .getOrElse(0) + + val endpoint = mcpEndpoint(tools, List("mcp"), name = "chimp-conformance-server", version = "0.1.0") + + supervised: + val binding = NettySyncServer().port(requestedPort).addEndpoint(endpoint).start() + println(s"http://127.0.0.1:${binding.port}/mcp") + System.out.flush() + Thread.currentThread.join() diff --git a/server/src/main/scala/chimp/server/McpHandler.scala b/server/src/main/scala/chimp/server/McpHandler.scala index 7195483..9de5ff4 100644 --- a/server/src/main/scala/chimp/server/McpHandler.scala +++ b/server/src/main/scala/chimp/server/McpHandler.scala @@ -93,13 +93,12 @@ class McpHandler[F[_]]( ): F[JSONRPCMessage] = // Extract tool name and arguments in a functional, idiomatic way val toolNameOpt = params.flatMap(_.hcursor.downField("name").as[String].toOption) - val argumentsOpt = params.flatMap(_.hcursor.downField("arguments").focus) - (toolNameOpt, argumentsOpt) match - case (Some(toolName), Some(args)) => + val args = params.flatMap(_.hcursor.downField("arguments").focus).getOrElse(Json.obj()) + toolNameOpt match + case Some(toolName) => toolsByName.get(toolName) match case Some(tool) => - def inputSnippet = args.noSpaces.take(200) // for error reporting - // Use Circe's Decoder for argument decoding + def inputSnippet = args.noSpaces.take(200) tool.inputDecoder.decodeJson(args) match case Right(decodedInput) => handleDecodedInput(tool, decodedInput, id, headers) case Left(decodingError) => @@ -109,9 +108,7 @@ class McpHandler[F[_]]( s"Invalid arguments: ${decodingError.getMessage}. Input: $inputSnippet" ).unit case None => protocolError(id, JSONRPCErrorCodes.MethodNotFound.code, s"Unknown tool: $toolName").unit - case (Some(toolName), None) => - protocolError(id, JSONRPCErrorCodes.InvalidParams.code, s"Missing arguments for tool: $toolName").unit - case (None, _) => + case None => protocolError(id, JSONRPCErrorCodes.InvalidParams.code, "Missing tool name").unit /** Handles a successfully decoded tool input, dispatching to the tool's logic. */ @@ -152,6 +149,9 @@ class McpHandler[F[_]]( case "initialize" => val response = handleInitialize(params, id) McpResponse.JsonResponse((response: JSONRPCMessage).asJson).unit + case "ping" => + val response = JSONRPCMessage.Response(id = id, result = Json.obj()) + McpResponse.JsonResponse((response: JSONRPCMessage).asJson).unit case other => val errorResponse = protocolError(id, JSONRPCErrorCodes.MethodNotFound.code, s"Unknown method: $other") McpResponse.JsonResponse((errorResponse: JSONRPCMessage).asJson).unit diff --git a/server/src/test/scala/chimp/server/McpHandlerSpec.scala b/server/src/test/scala/chimp/server/McpHandlerSpec.scala index af06931..ec2b8c0 100644 --- a/server/src/test/scala/chimp/server/McpHandlerSpec.scala +++ b/server/src/test/scala/chimp/server/McpHandlerSpec.scala @@ -195,11 +195,10 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: error.message should include("Invalid arguments") case _ => fail("Expected Error") - it should "return an error for missing arguments" in: + it should "return an error when required fields are missing (no arguments object)" in: // Given val params = Json.obj( "name" -> Json.fromString("add") - // missing 'arguments' ) val req: JSONRPCMessage = Request(method = "tools/call", params = Some(params), id = RequestId("7")) val json = req.asJson @@ -211,7 +210,7 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: resp match case Error(_, _, error) => error.code shouldBe InvalidParams.code - error.message should include("Missing arguments") + error.message should include("Invalid arguments") case _ => fail("Expected Error") it should "return an error for missing tool name" in: From 323b1e760b3f0e7d22c62dc7732f1f0a45d85ee1 Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Tue, 12 May 2026 12:21:59 +0200 Subject: [PATCH 07/27] feat: MCP version 2025-11-25 (latest) json schema file for model unit tests --- .../resources/schema/2025-11-25/schema.json | 4058 +++++++++++++++++ 1 file changed, 4058 insertions(+) create mode 100644 core/src/test/resources/schema/2025-11-25/schema.json diff --git a/core/src/test/resources/schema/2025-11-25/schema.json b/core/src/test/resources/schema/2025-11-25/schema.json new file mode 100644 index 0000000..9d2e662 --- /dev/null +++ b/core/src/test/resources/schema/2025-11-25/schema.json @@ -0,0 +1,4058 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$defs": { + "Annotations": { + "description": "Optional annotations for the client. The client can use annotations to inform how objects are used or displayed", + "properties": { + "audience": { + "description": "Describes who the intended audience of this object or data is.\n\nIt can include multiple entries to indicate content useful for multiple audiences (e.g., `[\"user\", \"assistant\"]`).", + "items": { + "$ref": "#/$defs/Role" + }, + "type": "array" + }, + "lastModified": { + "description": "The moment the resource was last modified, as an ISO 8601 formatted string.\n\nShould be an ISO 8601 formatted string (e.g., \"2025-01-12T15:00:58Z\").\n\nExamples: last activity timestamp in an open file, timestamp when the resource\nwas attached, etc.", + "type": "string" + }, + "priority": { + "description": "Describes how important this data is for operating the server.\n\nA value of 1 means \"most important,\" and indicates that the data is\neffectively required, while 0 means \"least important,\" and indicates that\nthe data is entirely optional.", + "maximum": 1, + "minimum": 0, + "type": "number" + } + }, + "type": "object" + }, + "AudioContent": { + "description": "Audio provided to or from an LLM.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "annotations": { + "$ref": "#/$defs/Annotations", + "description": "Optional annotations for the client." + }, + "data": { + "description": "The base64-encoded audio data.", + "format": "byte", + "type": "string" + }, + "mimeType": { + "description": "The MIME type of the audio. Different providers may support different audio types.", + "type": "string" + }, + "type": { + "const": "audio", + "type": "string" + } + }, + "required": [ + "data", + "mimeType", + "type" + ], + "type": "object" + }, + "BaseMetadata": { + "description": "Base interface for metadata with name (identifier) and title (display name) properties.", + "properties": { + "name": { + "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", + "type": "string" + }, + "title": { + "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for Tool,\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "BlobResourceContents": { + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "blob": { + "description": "A base64-encoded string representing the binary data of the item.", + "format": "byte", + "type": "string" + }, + "mimeType": { + "description": "The MIME type of this resource, if known.", + "type": "string" + }, + "uri": { + "description": "The URI of this resource.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "blob", + "uri" + ], + "type": "object" + }, + "BooleanSchema": { + "properties": { + "default": { + "type": "boolean" + }, + "description": { + "type": "string" + }, + "title": { + "type": "string" + }, + "type": { + "const": "boolean", + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" + }, + "CallToolRequest": { + "description": "Used by the client to invoke a tool provided by the server.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "tools/call", + "type": "string" + }, + "params": { + "$ref": "#/$defs/CallToolRequestParams" + } + }, + "required": [ + "id", + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "CallToolRequestParams": { + "description": "Parameters for a `tools/call` request.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "properties": { + "progressToken": { + "$ref": "#/$defs/ProgressToken", + "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." + } + }, + "type": "object" + }, + "arguments": { + "additionalProperties": {}, + "description": "Arguments to use for the tool call.", + "type": "object" + }, + "name": { + "description": "The name of the tool.", + "type": "string" + }, + "task": { + "$ref": "#/$defs/TaskMetadata", + "description": "If specified, the caller is requesting task-augmented execution for this request.\nThe request will return a CreateTaskResult immediately, and the actual result can be\nretrieved later via tasks/result.\n\nTask augmentation is subject to capability negotiation - receivers MUST declare support\nfor task augmentation of specific request types in their capabilities." + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "CallToolResult": { + "description": "The server's response to a tool call.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "content": { + "description": "A list of content objects that represent the unstructured result of the tool call.", + "items": { + "$ref": "#/$defs/ContentBlock" + }, + "type": "array" + }, + "isError": { + "description": "Whether the tool call ended in an error.\n\nIf not set, this is assumed to be false (the call was successful).\n\nAny errors that originate from the tool SHOULD be reported inside the result\nobject, with `isError` set to true, _not_ as an MCP protocol-level error\nresponse. Otherwise, the LLM would not be able to see that an error occurred\nand self-correct.\n\nHowever, any errors in _finding_ the tool, an error indicating that the\nserver does not support tool calls, or any other exceptional conditions,\nshould be reported as an MCP error response.", + "type": "boolean" + }, + "structuredContent": { + "additionalProperties": {}, + "description": "An optional JSON object that represents the structured result of the tool call.", + "type": "object" + } + }, + "required": [ + "content" + ], + "type": "object" + }, + "CancelTaskRequest": { + "description": "A request to cancel a task.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "tasks/cancel", + "type": "string" + }, + "params": { + "properties": { + "taskId": { + "description": "The task identifier to cancel.", + "type": "string" + } + }, + "required": [ + "taskId" + ], + "type": "object" + } + }, + "required": [ + "id", + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "CancelTaskResult": { + "allOf": [ + { + "$ref": "#/$defs/Result" + }, + { + "$ref": "#/$defs/Task" + } + ], + "description": "The response to a tasks/cancel request." + }, + "CancelledNotification": { + "description": "This notification can be sent by either side to indicate that it is cancelling a previously-issued request.\n\nThe 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.\n\nThis notification indicates that the result will be unused, so any associated processing SHOULD cease.\n\nA client MUST NOT attempt to cancel its `initialize` request.\n\nFor task cancellation, use the `tasks/cancel` request instead of this notification.", + "properties": { + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "notifications/cancelled", + "type": "string" + }, + "params": { + "$ref": "#/$defs/CancelledNotificationParams" + } + }, + "required": [ + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "CancelledNotificationParams": { + "description": "Parameters for a `notifications/cancelled` notification.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "reason": { + "description": "An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.", + "type": "string" + }, + "requestId": { + "$ref": "#/$defs/RequestId", + "description": "The ID of the request to cancel.\n\nThis MUST correspond to the ID of a request previously issued in the same direction.\nThis MUST be provided for cancelling non-task requests.\nThis MUST NOT be used for cancelling tasks (use the `tasks/cancel` request instead)." + } + }, + "type": "object" + }, + "ClientCapabilities": { + "description": "Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.", + "properties": { + "elicitation": { + "description": "Present if the client supports elicitation from the server.", + "properties": { + "form": { + "additionalProperties": true, + "properties": {}, + "type": "object" + }, + "url": { + "additionalProperties": true, + "properties": {}, + "type": "object" + } + }, + "type": "object" + }, + "experimental": { + "additionalProperties": { + "additionalProperties": true, + "properties": {}, + "type": "object" + }, + "description": "Experimental, non-standard capabilities that the client supports.", + "type": "object" + }, + "roots": { + "description": "Present if the client supports listing roots.", + "properties": { + "listChanged": { + "description": "Whether the client supports notifications for changes to the roots list.", + "type": "boolean" + } + }, + "type": "object" + }, + "sampling": { + "description": "Present if the client supports sampling from an LLM.", + "properties": { + "context": { + "additionalProperties": true, + "description": "Whether the client supports context inclusion via includeContext parameter.\nIf not declared, servers SHOULD only use `includeContext: \"none\"` (or omit it).", + "properties": {}, + "type": "object" + }, + "tools": { + "additionalProperties": true, + "description": "Whether the client supports tool use via tools and toolChoice parameters.", + "properties": {}, + "type": "object" + } + }, + "type": "object" + }, + "tasks": { + "description": "Present if the client supports task-augmented requests.", + "properties": { + "cancel": { + "additionalProperties": true, + "description": "Whether this client supports tasks/cancel.", + "properties": {}, + "type": "object" + }, + "list": { + "additionalProperties": true, + "description": "Whether this client supports tasks/list.", + "properties": {}, + "type": "object" + }, + "requests": { + "description": "Specifies which request types can be augmented with tasks.", + "properties": { + "elicitation": { + "description": "Task support for elicitation-related requests.", + "properties": { + "create": { + "additionalProperties": true, + "description": "Whether the client supports task-augmented elicitation/create requests.", + "properties": {}, + "type": "object" + } + }, + "type": "object" + }, + "sampling": { + "description": "Task support for sampling-related requests.", + "properties": { + "createMessage": { + "additionalProperties": true, + "description": "Whether the client supports task-augmented sampling/createMessage requests.", + "properties": {}, + "type": "object" + } + }, + "type": "object" + } + }, + "type": "object" + } + }, + "type": "object" + } + }, + "type": "object" + }, + "ClientNotification": { + "anyOf": [ + { + "$ref": "#/$defs/CancelledNotification" + }, + { + "$ref": "#/$defs/InitializedNotification" + }, + { + "$ref": "#/$defs/ProgressNotification" + }, + { + "$ref": "#/$defs/TaskStatusNotification" + }, + { + "$ref": "#/$defs/RootsListChangedNotification" + } + ] + }, + "ClientRequest": { + "anyOf": [ + { + "$ref": "#/$defs/InitializeRequest" + }, + { + "$ref": "#/$defs/PingRequest" + }, + { + "$ref": "#/$defs/ListResourcesRequest" + }, + { + "$ref": "#/$defs/ListResourceTemplatesRequest" + }, + { + "$ref": "#/$defs/ReadResourceRequest" + }, + { + "$ref": "#/$defs/SubscribeRequest" + }, + { + "$ref": "#/$defs/UnsubscribeRequest" + }, + { + "$ref": "#/$defs/ListPromptsRequest" + }, + { + "$ref": "#/$defs/GetPromptRequest" + }, + { + "$ref": "#/$defs/ListToolsRequest" + }, + { + "$ref": "#/$defs/CallToolRequest" + }, + { + "$ref": "#/$defs/GetTaskRequest" + }, + { + "$ref": "#/$defs/GetTaskPayloadRequest" + }, + { + "$ref": "#/$defs/CancelTaskRequest" + }, + { + "$ref": "#/$defs/ListTasksRequest" + }, + { + "$ref": "#/$defs/SetLevelRequest" + }, + { + "$ref": "#/$defs/CompleteRequest" + } + ] + }, + "ClientResult": { + "anyOf": [ + { + "$ref": "#/$defs/Result" + }, + { + "$ref": "#/$defs/GetTaskResult", + "description": "The response to a tasks/get request." + }, + { + "$ref": "#/$defs/GetTaskPayloadResult" + }, + { + "$ref": "#/$defs/CancelTaskResult", + "description": "The response to a tasks/cancel request." + }, + { + "$ref": "#/$defs/ListTasksResult" + }, + { + "$ref": "#/$defs/CreateMessageResult" + }, + { + "$ref": "#/$defs/ListRootsResult" + }, + { + "$ref": "#/$defs/ElicitResult" + } + ] + }, + "CompleteRequest": { + "description": "A request from the client to the server, to ask for completion options.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "completion/complete", + "type": "string" + }, + "params": { + "$ref": "#/$defs/CompleteRequestParams" + } + }, + "required": [ + "id", + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "CompleteRequestParams": { + "description": "Parameters for a `completion/complete` request.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "properties": { + "progressToken": { + "$ref": "#/$defs/ProgressToken", + "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." + } + }, + "type": "object" + }, + "argument": { + "description": "The argument's information", + "properties": { + "name": { + "description": "The name of the argument", + "type": "string" + }, + "value": { + "description": "The value of the argument to use for completion matching.", + "type": "string" + } + }, + "required": [ + "name", + "value" + ], + "type": "object" + }, + "context": { + "description": "Additional, optional context for completions", + "properties": { + "arguments": { + "additionalProperties": { + "type": "string" + }, + "description": "Previously-resolved variables in a URI template or prompt.", + "type": "object" + } + }, + "type": "object" + }, + "ref": { + "anyOf": [ + { + "$ref": "#/$defs/PromptReference" + }, + { + "$ref": "#/$defs/ResourceTemplateReference" + } + ] + } + }, + "required": [ + "argument", + "ref" + ], + "type": "object" + }, + "CompleteResult": { + "description": "The server's response to a completion/complete request", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "completion": { + "properties": { + "hasMore": { + "description": "Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.", + "type": "boolean" + }, + "total": { + "description": "The total number of completion options available. This can exceed the number of values actually sent in the response.", + "type": "integer" + }, + "values": { + "description": "An array of completion values. Must not exceed 100 items.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "values" + ], + "type": "object" + } + }, + "required": [ + "completion" + ], + "type": "object" + }, + "ContentBlock": { + "anyOf": [ + { + "$ref": "#/$defs/TextContent" + }, + { + "$ref": "#/$defs/ImageContent" + }, + { + "$ref": "#/$defs/AudioContent" + }, + { + "$ref": "#/$defs/ResourceLink" + }, + { + "$ref": "#/$defs/EmbeddedResource" + } + ] + }, + "CreateMessageRequest": { + "description": "A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "sampling/createMessage", + "type": "string" + }, + "params": { + "$ref": "#/$defs/CreateMessageRequestParams" + } + }, + "required": [ + "id", + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "CreateMessageRequestParams": { + "description": "Parameters for a `sampling/createMessage` request.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "properties": { + "progressToken": { + "$ref": "#/$defs/ProgressToken", + "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." + } + }, + "type": "object" + }, + "includeContext": { + "description": "A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.\nThe client MAY ignore this request.\n\nDefault is \"none\". Values \"thisServer\" and \"allServers\" are soft-deprecated. Servers SHOULD only use these values if the client\ndeclares ClientCapabilities.sampling.context. These values may be removed in future spec releases.", + "enum": [ + "allServers", + "none", + "thisServer" + ], + "type": "string" + }, + "maxTokens": { + "description": "The requested maximum number of tokens to sample (to prevent runaway completions).\n\nThe client MAY choose to sample fewer tokens than the requested maximum.", + "type": "integer" + }, + "messages": { + "items": { + "$ref": "#/$defs/SamplingMessage" + }, + "type": "array" + }, + "metadata": { + "additionalProperties": true, + "description": "Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.", + "properties": {}, + "type": "object" + }, + "modelPreferences": { + "$ref": "#/$defs/ModelPreferences", + "description": "The server's preferences for which model to select. The client MAY ignore these preferences." + }, + "stopSequences": { + "items": { + "type": "string" + }, + "type": "array" + }, + "systemPrompt": { + "description": "An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.", + "type": "string" + }, + "task": { + "$ref": "#/$defs/TaskMetadata", + "description": "If specified, the caller is requesting task-augmented execution for this request.\nThe request will return a CreateTaskResult immediately, and the actual result can be\nretrieved later via tasks/result.\n\nTask augmentation is subject to capability negotiation - receivers MUST declare support\nfor task augmentation of specific request types in their capabilities." + }, + "temperature": { + "type": "number" + }, + "toolChoice": { + "$ref": "#/$defs/ToolChoice", + "description": "Controls how the model uses tools.\nThe client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\nDefault is `{ mode: \"auto\" }`." + }, + "tools": { + "description": "Tools that the model may use during generation.\nThe client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.", + "items": { + "$ref": "#/$defs/Tool" + }, + "type": "array" + } + }, + "required": [ + "maxTokens", + "messages" + ], + "type": "object" + }, + "CreateMessageResult": { + "description": "The client's response to a sampling/createMessage request from the server.\nThe client should inform the user before returning the sampled message, to allow them\nto inspect the response (human in the loop) and decide whether to allow the server to see it.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "content": { + "anyOf": [ + { + "$ref": "#/$defs/TextContent" + }, + { + "$ref": "#/$defs/ImageContent" + }, + { + "$ref": "#/$defs/AudioContent" + }, + { + "$ref": "#/$defs/ToolUseContent" + }, + { + "$ref": "#/$defs/ToolResultContent" + }, + { + "items": { + "$ref": "#/$defs/SamplingMessageContentBlock" + }, + "type": "array" + } + ] + }, + "model": { + "description": "The name of the model that generated the message.", + "type": "string" + }, + "role": { + "$ref": "#/$defs/Role" + }, + "stopReason": { + "description": "The reason why sampling stopped, if known.\n\nStandard values:\n- \"endTurn\": Natural end of the assistant's turn\n- \"stopSequence\": A stop sequence was encountered\n- \"maxTokens\": Maximum token limit was reached\n- \"toolUse\": The model wants to use one or more tools\n\nThis field is an open string to allow for provider-specific stop reasons.", + "type": "string" + } + }, + "required": [ + "content", + "model", + "role" + ], + "type": "object" + }, + "CreateTaskResult": { + "description": "A response to a task-augmented request.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "task": { + "$ref": "#/$defs/Task" + } + }, + "required": [ + "task" + ], + "type": "object" + }, + "Cursor": { + "description": "An opaque token used to represent a cursor for pagination.", + "type": "string" + }, + "ElicitRequest": { + "description": "A request from the server to elicit additional information from the user via the client.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "elicitation/create", + "type": "string" + }, + "params": { + "$ref": "#/$defs/ElicitRequestParams" + } + }, + "required": [ + "id", + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "ElicitRequestFormParams": { + "description": "The parameters for a request to elicit non-sensitive information from the user via a form in the client.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "properties": { + "progressToken": { + "$ref": "#/$defs/ProgressToken", + "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." + } + }, + "type": "object" + }, + "message": { + "description": "The message to present to the user describing what information is being requested.", + "type": "string" + }, + "mode": { + "const": "form", + "description": "The elicitation mode.", + "type": "string" + }, + "requestedSchema": { + "description": "A restricted subset of JSON Schema.\nOnly top-level properties are allowed, without nesting.", + "properties": { + "$schema": { + "type": "string" + }, + "properties": { + "additionalProperties": { + "$ref": "#/$defs/PrimitiveSchemaDefinition" + }, + "type": "object" + }, + "required": { + "items": { + "type": "string" + }, + "type": "array" + }, + "type": { + "const": "object", + "type": "string" + } + }, + "required": [ + "properties", + "type" + ], + "type": "object" + }, + "task": { + "$ref": "#/$defs/TaskMetadata", + "description": "If specified, the caller is requesting task-augmented execution for this request.\nThe request will return a CreateTaskResult immediately, and the actual result can be\nretrieved later via tasks/result.\n\nTask augmentation is subject to capability negotiation - receivers MUST declare support\nfor task augmentation of specific request types in their capabilities." + } + }, + "required": [ + "message", + "requestedSchema" + ], + "type": "object" + }, + "ElicitRequestParams": { + "anyOf": [ + { + "$ref": "#/$defs/ElicitRequestURLParams" + }, + { + "$ref": "#/$defs/ElicitRequestFormParams" + } + ], + "description": "The parameters for a request to elicit additional information from the user via the client." + }, + "ElicitRequestURLParams": { + "description": "The parameters for a request to elicit information from the user via a URL in the client.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "properties": { + "progressToken": { + "$ref": "#/$defs/ProgressToken", + "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." + } + }, + "type": "object" + }, + "elicitationId": { + "description": "The ID of the elicitation, which must be unique within the context of the server.\nThe client MUST treat this ID as an opaque value.", + "type": "string" + }, + "message": { + "description": "The message to present to the user explaining why the interaction is needed.", + "type": "string" + }, + "mode": { + "const": "url", + "description": "The elicitation mode.", + "type": "string" + }, + "task": { + "$ref": "#/$defs/TaskMetadata", + "description": "If specified, the caller is requesting task-augmented execution for this request.\nThe request will return a CreateTaskResult immediately, and the actual result can be\nretrieved later via tasks/result.\n\nTask augmentation is subject to capability negotiation - receivers MUST declare support\nfor task augmentation of specific request types in their capabilities." + }, + "url": { + "description": "The URL that the user should navigate to.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "elicitationId", + "message", + "mode", + "url" + ], + "type": "object" + }, + "ElicitResult": { + "description": "The client's response to an elicitation request.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "action": { + "description": "The user action in response to the elicitation.\n- \"accept\": User submitted the form/confirmed the action\n- \"decline\": User explicitly decline the action\n- \"cancel\": User dismissed without making an explicit choice", + "enum": [ + "accept", + "cancel", + "decline" + ], + "type": "string" + }, + "content": { + "additionalProperties": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": [ + "string", + "integer", + "boolean" + ] + } + ] + }, + "description": "The submitted form data, only present when action is \"accept\" and mode was \"form\".\nContains values matching the requested schema.\nOmitted for out-of-band mode responses.", + "type": "object" + } + }, + "required": [ + "action" + ], + "type": "object" + }, + "ElicitationCompleteNotification": { + "description": "An optional notification from the server to the client, informing it of a completion of a out-of-band elicitation request.", + "properties": { + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "notifications/elicitation/complete", + "type": "string" + }, + "params": { + "properties": { + "elicitationId": { + "description": "The ID of the elicitation that completed.", + "type": "string" + } + }, + "required": [ + "elicitationId" + ], + "type": "object" + } + }, + "required": [ + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "EmbeddedResource": { + "description": "The contents of a resource, embedded into a prompt or tool call result.\n\nIt is up to the client how best to render embedded resources for the benefit\nof the LLM and/or the user.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "annotations": { + "$ref": "#/$defs/Annotations", + "description": "Optional annotations for the client." + }, + "resource": { + "anyOf": [ + { + "$ref": "#/$defs/TextResourceContents" + }, + { + "$ref": "#/$defs/BlobResourceContents" + } + ] + }, + "type": { + "const": "resource", + "type": "string" + } + }, + "required": [ + "resource", + "type" + ], + "type": "object" + }, + "EmptyResult": { + "$ref": "#/$defs/Result" + }, + "EnumSchema": { + "anyOf": [ + { + "$ref": "#/$defs/UntitledSingleSelectEnumSchema" + }, + { + "$ref": "#/$defs/TitledSingleSelectEnumSchema" + }, + { + "$ref": "#/$defs/UntitledMultiSelectEnumSchema" + }, + { + "$ref": "#/$defs/TitledMultiSelectEnumSchema" + }, + { + "$ref": "#/$defs/LegacyTitledEnumSchema" + } + ] + }, + "Error": { + "properties": { + "code": { + "description": "The error type that occurred.", + "type": "integer" + }, + "data": { + "description": "Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.)." + }, + "message": { + "description": "A short description of the error. The message SHOULD be limited to a concise single sentence.", + "type": "string" + } + }, + "required": [ + "code", + "message" + ], + "type": "object" + }, + "GetPromptRequest": { + "description": "Used by the client to get a prompt provided by the server.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "prompts/get", + "type": "string" + }, + "params": { + "$ref": "#/$defs/GetPromptRequestParams" + } + }, + "required": [ + "id", + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "GetPromptRequestParams": { + "description": "Parameters for a `prompts/get` request.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "properties": { + "progressToken": { + "$ref": "#/$defs/ProgressToken", + "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." + } + }, + "type": "object" + }, + "arguments": { + "additionalProperties": { + "type": "string" + }, + "description": "Arguments to use for templating the prompt.", + "type": "object" + }, + "name": { + "description": "The name of the prompt or prompt template.", + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "GetPromptResult": { + "description": "The server's response to a prompts/get request from the client.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "description": { + "description": "An optional description for the prompt.", + "type": "string" + }, + "messages": { + "items": { + "$ref": "#/$defs/PromptMessage" + }, + "type": "array" + } + }, + "required": [ + "messages" + ], + "type": "object" + }, + "GetTaskPayloadRequest": { + "description": "A request to retrieve the result of a completed task.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "tasks/result", + "type": "string" + }, + "params": { + "properties": { + "taskId": { + "description": "The task identifier to retrieve results for.", + "type": "string" + } + }, + "required": [ + "taskId" + ], + "type": "object" + } + }, + "required": [ + "id", + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "GetTaskPayloadResult": { + "additionalProperties": {}, + "description": "The response to a tasks/result request.\nThe structure matches the result type of the original request.\nFor example, a tools/call task would return the CallToolResult structure.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + } + }, + "type": "object" + }, + "GetTaskRequest": { + "description": "A request to retrieve the state of a task.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "tasks/get", + "type": "string" + }, + "params": { + "properties": { + "taskId": { + "description": "The task identifier to query.", + "type": "string" + } + }, + "required": [ + "taskId" + ], + "type": "object" + } + }, + "required": [ + "id", + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "GetTaskResult": { + "allOf": [ + { + "$ref": "#/$defs/Result" + }, + { + "$ref": "#/$defs/Task" + } + ], + "description": "The response to a tasks/get request." + }, + "Icon": { + "description": "An optionally-sized icon that can be displayed in a user interface.", + "properties": { + "mimeType": { + "description": "Optional MIME type override if the source MIME type is missing or generic.\nFor example: `\"image/png\"`, `\"image/jpeg\"`, or `\"image/svg+xml\"`.", + "type": "string" + }, + "sizes": { + "description": "Optional array of strings that specify sizes at which the icon can be used.\nEach string should be in WxH format (e.g., `\"48x48\"`, `\"96x96\"`) or `\"any\"` for scalable formats like SVG.\n\nIf not provided, the client should assume that the icon can be used at any size.", + "items": { + "type": "string" + }, + "type": "array" + }, + "src": { + "description": "A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a\n`data:` URI with Base64-encoded image data.\n\nConsumers SHOULD takes steps to ensure URLs serving icons are from the\nsame domain as the client/server or a trusted domain.\n\nConsumers SHOULD take appropriate precautions when consuming SVGs as they can contain\nexecutable JavaScript.", + "format": "uri", + "type": "string" + }, + "theme": { + "description": "Optional specifier for the theme this icon is designed for. `light` indicates\nthe icon is designed to be used with a light background, and `dark` indicates\nthe icon is designed to be used with a dark background.\n\nIf not provided, the client should assume the icon can be used with any theme.", + "enum": [ + "dark", + "light" + ], + "type": "string" + } + }, + "required": [ + "src" + ], + "type": "object" + }, + "Icons": { + "description": "Base interface to add `icons` property.", + "properties": { + "icons": { + "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)", + "items": { + "$ref": "#/$defs/Icon" + }, + "type": "array" + } + }, + "type": "object" + }, + "ImageContent": { + "description": "An image provided to or from an LLM.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "annotations": { + "$ref": "#/$defs/Annotations", + "description": "Optional annotations for the client." + }, + "data": { + "description": "The base64-encoded image data.", + "format": "byte", + "type": "string" + }, + "mimeType": { + "description": "The MIME type of the image. Different providers may support different image types.", + "type": "string" + }, + "type": { + "const": "image", + "type": "string" + } + }, + "required": [ + "data", + "mimeType", + "type" + ], + "type": "object" + }, + "Implementation": { + "description": "Describes the MCP implementation.", + "properties": { + "description": { + "description": "An optional human-readable description of what this implementation does.\n\nThis can be used by clients or servers to provide context about their purpose\nand capabilities. For example, a server might describe the types of resources\nor tools it provides, while a client might describe its intended use case.", + "type": "string" + }, + "icons": { + "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)", + "items": { + "$ref": "#/$defs/Icon" + }, + "type": "array" + }, + "name": { + "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", + "type": "string" + }, + "title": { + "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for Tool,\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", + "type": "string" + }, + "version": { + "type": "string" + }, + "websiteUrl": { + "description": "An optional URL of the website for this implementation.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "name", + "version" + ], + "type": "object" + }, + "InitializeRequest": { + "description": "This request is sent from the client to the server when it first connects, asking it to begin initialization.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "initialize", + "type": "string" + }, + "params": { + "$ref": "#/$defs/InitializeRequestParams" + } + }, + "required": [ + "id", + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "InitializeRequestParams": { + "description": "Parameters for an `initialize` request.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "properties": { + "progressToken": { + "$ref": "#/$defs/ProgressToken", + "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." + } + }, + "type": "object" + }, + "capabilities": { + "$ref": "#/$defs/ClientCapabilities" + }, + "clientInfo": { + "$ref": "#/$defs/Implementation" + }, + "protocolVersion": { + "description": "The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.", + "type": "string" + } + }, + "required": [ + "capabilities", + "clientInfo", + "protocolVersion" + ], + "type": "object" + }, + "InitializeResult": { + "description": "After receiving an initialize request from the client, the server sends this response.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "capabilities": { + "$ref": "#/$defs/ServerCapabilities" + }, + "instructions": { + "description": "Instructions describing how to use the server and its features.\n\nThis can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a \"hint\" to the model. For example, this information MAY be added to the system prompt.", + "type": "string" + }, + "protocolVersion": { + "description": "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.", + "type": "string" + }, + "serverInfo": { + "$ref": "#/$defs/Implementation" + } + }, + "required": [ + "capabilities", + "protocolVersion", + "serverInfo" + ], + "type": "object" + }, + "InitializedNotification": { + "description": "This notification is sent from the client to the server after initialization has finished.", + "properties": { + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "notifications/initialized", + "type": "string" + }, + "params": { + "$ref": "#/$defs/NotificationParams" + } + }, + "required": [ + "jsonrpc", + "method" + ], + "type": "object" + }, + "JSONRPCErrorResponse": { + "description": "A response to a request that indicates an error occurred.", + "properties": { + "error": { + "$ref": "#/$defs/Error" + }, + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + } + }, + "required": [ + "error", + "jsonrpc" + ], + "type": "object" + }, + "JSONRPCMessage": { + "anyOf": [ + { + "$ref": "#/$defs/JSONRPCRequest" + }, + { + "$ref": "#/$defs/JSONRPCNotification" + }, + { + "$ref": "#/$defs/JSONRPCResultResponse" + }, + { + "$ref": "#/$defs/JSONRPCErrorResponse" + } + ], + "description": "Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent." + }, + "JSONRPCNotification": { + "description": "A notification which does not expect a response.", + "properties": { + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "type": "string" + }, + "params": { + "additionalProperties": {}, + "type": "object" + } + }, + "required": [ + "jsonrpc", + "method" + ], + "type": "object" + }, + "JSONRPCRequest": { + "description": "A request that expects a response.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "type": "string" + }, + "params": { + "additionalProperties": {}, + "type": "object" + } + }, + "required": [ + "id", + "jsonrpc", + "method" + ], + "type": "object" + }, + "JSONRPCResponse": { + "anyOf": [ + { + "$ref": "#/$defs/JSONRPCResultResponse" + }, + { + "$ref": "#/$defs/JSONRPCErrorResponse" + } + ], + "description": "A response to a request, containing either the result or error." + }, + "JSONRPCResultResponse": { + "description": "A successful (non-error) response to a request.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "result": { + "$ref": "#/$defs/Result" + } + }, + "required": [ + "id", + "jsonrpc", + "result" + ], + "type": "object" + }, + "LegacyTitledEnumSchema": { + "description": "Use TitledSingleSelectEnumSchema instead.\nThis interface will be removed in a future version.", + "properties": { + "default": { + "type": "string" + }, + "description": { + "type": "string" + }, + "enum": { + "items": { + "type": "string" + }, + "type": "array" + }, + "enumNames": { + "description": "(Legacy) Display names for enum values.\nNon-standard according to JSON schema 2020-12.", + "items": { + "type": "string" + }, + "type": "array" + }, + "title": { + "type": "string" + }, + "type": { + "const": "string", + "type": "string" + } + }, + "required": [ + "enum", + "type" + ], + "type": "object" + }, + "ListPromptsRequest": { + "description": "Sent from the client to request a list of prompts and prompt templates the server has.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "prompts/list", + "type": "string" + }, + "params": { + "$ref": "#/$defs/PaginatedRequestParams" + } + }, + "required": [ + "id", + "jsonrpc", + "method" + ], + "type": "object" + }, + "ListPromptsResult": { + "description": "The server's response to a prompts/list request from the client.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "nextCursor": { + "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", + "type": "string" + }, + "prompts": { + "items": { + "$ref": "#/$defs/Prompt" + }, + "type": "array" + } + }, + "required": [ + "prompts" + ], + "type": "object" + }, + "ListResourceTemplatesRequest": { + "description": "Sent from the client to request a list of resource templates the server has.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "resources/templates/list", + "type": "string" + }, + "params": { + "$ref": "#/$defs/PaginatedRequestParams" + } + }, + "required": [ + "id", + "jsonrpc", + "method" + ], + "type": "object" + }, + "ListResourceTemplatesResult": { + "description": "The server's response to a resources/templates/list request from the client.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "nextCursor": { + "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", + "type": "string" + }, + "resourceTemplates": { + "items": { + "$ref": "#/$defs/ResourceTemplate" + }, + "type": "array" + } + }, + "required": [ + "resourceTemplates" + ], + "type": "object" + }, + "ListResourcesRequest": { + "description": "Sent from the client to request a list of resources the server has.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "resources/list", + "type": "string" + }, + "params": { + "$ref": "#/$defs/PaginatedRequestParams" + } + }, + "required": [ + "id", + "jsonrpc", + "method" + ], + "type": "object" + }, + "ListResourcesResult": { + "description": "The server's response to a resources/list request from the client.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "nextCursor": { + "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", + "type": "string" + }, + "resources": { + "items": { + "$ref": "#/$defs/Resource" + }, + "type": "array" + } + }, + "required": [ + "resources" + ], + "type": "object" + }, + "ListRootsRequest": { + "description": "Sent from the server to request a list of root URIs from the client. Roots allow\nservers to ask for specific directories or files to operate on. A common example\nfor roots is providing a set of repositories or directories a server should operate\non.\n\nThis request is typically used when the server needs to understand the file system\nstructure or access specific locations that the client has permission to read from.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "roots/list", + "type": "string" + }, + "params": { + "$ref": "#/$defs/RequestParams" + } + }, + "required": [ + "id", + "jsonrpc", + "method" + ], + "type": "object" + }, + "ListRootsResult": { + "description": "The client's response to a roots/list request from the server.\nThis result contains an array of Root objects, each representing a root directory\nor file that the server can operate on.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "roots": { + "items": { + "$ref": "#/$defs/Root" + }, + "type": "array" + } + }, + "required": [ + "roots" + ], + "type": "object" + }, + "ListTasksRequest": { + "description": "A request to retrieve a list of tasks.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "tasks/list", + "type": "string" + }, + "params": { + "$ref": "#/$defs/PaginatedRequestParams" + } + }, + "required": [ + "id", + "jsonrpc", + "method" + ], + "type": "object" + }, + "ListTasksResult": { + "description": "The response to a tasks/list request.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "nextCursor": { + "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", + "type": "string" + }, + "tasks": { + "items": { + "$ref": "#/$defs/Task" + }, + "type": "array" + } + }, + "required": [ + "tasks" + ], + "type": "object" + }, + "ListToolsRequest": { + "description": "Sent from the client to request a list of tools the server has.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "tools/list", + "type": "string" + }, + "params": { + "$ref": "#/$defs/PaginatedRequestParams" + } + }, + "required": [ + "id", + "jsonrpc", + "method" + ], + "type": "object" + }, + "ListToolsResult": { + "description": "The server's response to a tools/list request from the client.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "nextCursor": { + "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", + "type": "string" + }, + "tools": { + "items": { + "$ref": "#/$defs/Tool" + }, + "type": "array" + } + }, + "required": [ + "tools" + ], + "type": "object" + }, + "LoggingLevel": { + "description": "The severity of a log message.\n\nThese map to syslog message severities, as specified in RFC-5424:\nhttps://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1", + "enum": [ + "alert", + "critical", + "debug", + "emergency", + "error", + "info", + "notice", + "warning" + ], + "type": "string" + }, + "LoggingMessageNotification": { + "description": "JSONRPCNotification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically.", + "properties": { + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "notifications/message", + "type": "string" + }, + "params": { + "$ref": "#/$defs/LoggingMessageNotificationParams" + } + }, + "required": [ + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "LoggingMessageNotificationParams": { + "description": "Parameters for a `notifications/message` notification.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "data": { + "description": "The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here." + }, + "level": { + "$ref": "#/$defs/LoggingLevel", + "description": "The severity of this log message." + }, + "logger": { + "description": "An optional name of the logger issuing this message.", + "type": "string" + } + }, + "required": [ + "data", + "level" + ], + "type": "object" + }, + "ModelHint": { + "description": "Hints to use for model selection.\n\nKeys not declared here are currently left unspecified by the spec and are up\nto the client to interpret.", + "properties": { + "name": { + "description": "A hint for a model name.\n\nThe client SHOULD treat this as a substring of a model name; for example:\n - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022`\n - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc.\n - `claude` should match any Claude model\n\nThe client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example:\n - `gemini-1.5-flash` could match `claude-3-haiku-20240307`", + "type": "string" + } + }, + "type": "object" + }, + "ModelPreferences": { + "description": "The server's preferences for model selection, requested of the client during sampling.\n\nBecause LLMs can vary along multiple dimensions, choosing the \"best\" model is\nrarely straightforward. Different models excel in different areas—some are\nfaster but less capable, others are more capable but more expensive, and so\non. This interface allows servers to express their priorities across multiple\ndimensions to help clients make an appropriate selection for their use case.\n\nThese preferences are always advisory. The client MAY ignore them. It is also\nup to the client to decide how to interpret these preferences and how to\nbalance them against other considerations.", + "properties": { + "costPriority": { + "description": "How much to prioritize cost when selecting a model. A value of 0 means cost\nis not important, while a value of 1 means cost is the most important\nfactor.", + "maximum": 1, + "minimum": 0, + "type": "number" + }, + "hints": { + "description": "Optional hints to use for model selection.\n\nIf multiple hints are specified, the client MUST evaluate them in order\n(such that the first match is taken).\n\nThe client SHOULD prioritize these hints over the numeric priorities, but\nMAY still use the priorities to select from ambiguous matches.", + "items": { + "$ref": "#/$defs/ModelHint" + }, + "type": "array" + }, + "intelligencePriority": { + "description": "How much to prioritize intelligence and capabilities when selecting a\nmodel. A value of 0 means intelligence is not important, while a value of 1\nmeans intelligence is the most important factor.", + "maximum": 1, + "minimum": 0, + "type": "number" + }, + "speedPriority": { + "description": "How much to prioritize sampling speed (latency) when selecting a model. A\nvalue of 0 means speed is not important, while a value of 1 means speed is\nthe most important factor.", + "maximum": 1, + "minimum": 0, + "type": "number" + } + }, + "type": "object" + }, + "MultiSelectEnumSchema": { + "anyOf": [ + { + "$ref": "#/$defs/UntitledMultiSelectEnumSchema" + }, + { + "$ref": "#/$defs/TitledMultiSelectEnumSchema" + } + ] + }, + "Notification": { + "properties": { + "method": { + "type": "string" + }, + "params": { + "additionalProperties": {}, + "type": "object" + } + }, + "required": [ + "method" + ], + "type": "object" + }, + "NotificationParams": { + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + } + }, + "type": "object" + }, + "NumberSchema": { + "properties": { + "default": { + "type": "integer" + }, + "description": { + "type": "string" + }, + "maximum": { + "type": "integer" + }, + "minimum": { + "type": "integer" + }, + "title": { + "type": "string" + }, + "type": { + "enum": [ + "integer", + "number" + ], + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" + }, + "PaginatedRequest": { + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "type": "string" + }, + "params": { + "$ref": "#/$defs/PaginatedRequestParams" + } + }, + "required": [ + "id", + "jsonrpc", + "method" + ], + "type": "object" + }, + "PaginatedRequestParams": { + "description": "Common parameters for paginated requests.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "properties": { + "progressToken": { + "$ref": "#/$defs/ProgressToken", + "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." + } + }, + "type": "object" + }, + "cursor": { + "description": "An opaque token representing the current pagination position.\nIf provided, the server should return results starting after this cursor.", + "type": "string" + } + }, + "type": "object" + }, + "PaginatedResult": { + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "nextCursor": { + "description": "An opaque token representing the pagination position after the last returned result.\nIf present, there may be more results available.", + "type": "string" + } + }, + "type": "object" + }, + "PingRequest": { + "description": "A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "ping", + "type": "string" + }, + "params": { + "$ref": "#/$defs/RequestParams" + } + }, + "required": [ + "id", + "jsonrpc", + "method" + ], + "type": "object" + }, + "PrimitiveSchemaDefinition": { + "anyOf": [ + { + "$ref": "#/$defs/StringSchema" + }, + { + "$ref": "#/$defs/NumberSchema" + }, + { + "$ref": "#/$defs/BooleanSchema" + }, + { + "$ref": "#/$defs/UntitledSingleSelectEnumSchema" + }, + { + "$ref": "#/$defs/TitledSingleSelectEnumSchema" + }, + { + "$ref": "#/$defs/UntitledMultiSelectEnumSchema" + }, + { + "$ref": "#/$defs/TitledMultiSelectEnumSchema" + }, + { + "$ref": "#/$defs/LegacyTitledEnumSchema" + } + ], + "description": "Restricted schema definitions that only allow primitive types\nwithout nested objects or arrays." + }, + "ProgressNotification": { + "description": "An out-of-band notification used to inform the receiver of a progress update for a long-running request.", + "properties": { + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "notifications/progress", + "type": "string" + }, + "params": { + "$ref": "#/$defs/ProgressNotificationParams" + } + }, + "required": [ + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "ProgressNotificationParams": { + "description": "Parameters for a `notifications/progress` notification.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "message": { + "description": "An optional message describing the current progress.", + "type": "string" + }, + "progress": { + "description": "The progress thus far. This should increase every time progress is made, even if the total is unknown.", + "type": "number" + }, + "progressToken": { + "$ref": "#/$defs/ProgressToken", + "description": "The progress token which was given in the initial request, used to associate this notification with the request that is proceeding." + }, + "total": { + "description": "Total number of items to process (or total progress required), if known.", + "type": "number" + } + }, + "required": [ + "progress", + "progressToken" + ], + "type": "object" + }, + "ProgressToken": { + "description": "A progress token, used to associate progress notifications with the original request.", + "type": [ + "string", + "integer" + ] + }, + "Prompt": { + "description": "A prompt or prompt template that the server offers.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "arguments": { + "description": "A list of arguments to use for templating the prompt.", + "items": { + "$ref": "#/$defs/PromptArgument" + }, + "type": "array" + }, + "description": { + "description": "An optional description of what this prompt provides", + "type": "string" + }, + "icons": { + "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)", + "items": { + "$ref": "#/$defs/Icon" + }, + "type": "array" + }, + "name": { + "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", + "type": "string" + }, + "title": { + "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for Tool,\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "PromptArgument": { + "description": "Describes an argument that a prompt can accept.", + "properties": { + "description": { + "description": "A human-readable description of the argument.", + "type": "string" + }, + "name": { + "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", + "type": "string" + }, + "required": { + "description": "Whether this argument must be provided.", + "type": "boolean" + }, + "title": { + "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for Tool,\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "PromptListChangedNotification": { + "description": "An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.", + "properties": { + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "notifications/prompts/list_changed", + "type": "string" + }, + "params": { + "$ref": "#/$defs/NotificationParams" + } + }, + "required": [ + "jsonrpc", + "method" + ], + "type": "object" + }, + "PromptMessage": { + "description": "Describes a message returned as part of a prompt.\n\nThis is similar to `SamplingMessage`, but also supports the embedding of\nresources from the MCP server.", + "properties": { + "content": { + "$ref": "#/$defs/ContentBlock" + }, + "role": { + "$ref": "#/$defs/Role" + } + }, + "required": [ + "content", + "role" + ], + "type": "object" + }, + "PromptReference": { + "description": "Identifies a prompt.", + "properties": { + "name": { + "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", + "type": "string" + }, + "title": { + "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for Tool,\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", + "type": "string" + }, + "type": { + "const": "ref/prompt", + "type": "string" + } + }, + "required": [ + "name", + "type" + ], + "type": "object" + }, + "ReadResourceRequest": { + "description": "Sent from the client to the server, to read a specific resource URI.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "resources/read", + "type": "string" + }, + "params": { + "$ref": "#/$defs/ReadResourceRequestParams" + } + }, + "required": [ + "id", + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "ReadResourceRequestParams": { + "description": "Parameters for a `resources/read` request.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "properties": { + "progressToken": { + "$ref": "#/$defs/ProgressToken", + "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." + } + }, + "type": "object" + }, + "uri": { + "description": "The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "uri" + ], + "type": "object" + }, + "ReadResourceResult": { + "description": "The server's response to a resources/read request from the client.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "contents": { + "items": { + "anyOf": [ + { + "$ref": "#/$defs/TextResourceContents" + }, + { + "$ref": "#/$defs/BlobResourceContents" + } + ] + }, + "type": "array" + } + }, + "required": [ + "contents" + ], + "type": "object" + }, + "RelatedTaskMetadata": { + "description": "Metadata for associating messages with a task.\nInclude this in the `_meta` field under the key `io.modelcontextprotocol/related-task`.", + "properties": { + "taskId": { + "description": "The task identifier this message is associated with.", + "type": "string" + } + }, + "required": [ + "taskId" + ], + "type": "object" + }, + "Request": { + "properties": { + "method": { + "type": "string" + }, + "params": { + "additionalProperties": {}, + "type": "object" + } + }, + "required": [ + "method" + ], + "type": "object" + }, + "RequestId": { + "description": "A uniquely identifying ID for a request in JSON-RPC.", + "type": [ + "string", + "integer" + ] + }, + "RequestParams": { + "description": "Common params for any request.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "properties": { + "progressToken": { + "$ref": "#/$defs/ProgressToken", + "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." + } + }, + "type": "object" + } + }, + "type": "object" + }, + "Resource": { + "description": "A known resource that the server is capable of reading.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "annotations": { + "$ref": "#/$defs/Annotations", + "description": "Optional annotations for the client." + }, + "description": { + "description": "A description of what this resource represents.\n\nThis can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.", + "type": "string" + }, + "icons": { + "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)", + "items": { + "$ref": "#/$defs/Icon" + }, + "type": "array" + }, + "mimeType": { + "description": "The MIME type of this resource, if known.", + "type": "string" + }, + "name": { + "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", + "type": "string" + }, + "size": { + "description": "The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n\nThis can be used by Hosts to display file sizes and estimate context window usage.", + "type": "integer" + }, + "title": { + "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for Tool,\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", + "type": "string" + }, + "uri": { + "description": "The URI of this resource.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "name", + "uri" + ], + "type": "object" + }, + "ResourceContents": { + "description": "The contents of a specific resource or sub-resource.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "mimeType": { + "description": "The MIME type of this resource, if known.", + "type": "string" + }, + "uri": { + "description": "The URI of this resource.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "uri" + ], + "type": "object" + }, + "ResourceLink": { + "description": "A resource that the server is capable of reading, included in a prompt or tool call result.\n\nNote: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "annotations": { + "$ref": "#/$defs/Annotations", + "description": "Optional annotations for the client." + }, + "description": { + "description": "A description of what this resource represents.\n\nThis can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.", + "type": "string" + }, + "icons": { + "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)", + "items": { + "$ref": "#/$defs/Icon" + }, + "type": "array" + }, + "mimeType": { + "description": "The MIME type of this resource, if known.", + "type": "string" + }, + "name": { + "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", + "type": "string" + }, + "size": { + "description": "The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n\nThis can be used by Hosts to display file sizes and estimate context window usage.", + "type": "integer" + }, + "title": { + "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for Tool,\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", + "type": "string" + }, + "type": { + "const": "resource_link", + "type": "string" + }, + "uri": { + "description": "The URI of this resource.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "name", + "type", + "uri" + ], + "type": "object" + }, + "ResourceListChangedNotification": { + "description": "An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.", + "properties": { + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "notifications/resources/list_changed", + "type": "string" + }, + "params": { + "$ref": "#/$defs/NotificationParams" + } + }, + "required": [ + "jsonrpc", + "method" + ], + "type": "object" + }, + "ResourceRequestParams": { + "description": "Common parameters when working with resources.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "properties": { + "progressToken": { + "$ref": "#/$defs/ProgressToken", + "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." + } + }, + "type": "object" + }, + "uri": { + "description": "The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "uri" + ], + "type": "object" + }, + "ResourceTemplate": { + "description": "A template description for resources available on the server.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "annotations": { + "$ref": "#/$defs/Annotations", + "description": "Optional annotations for the client." + }, + "description": { + "description": "A description of what this template is for.\n\nThis can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.", + "type": "string" + }, + "icons": { + "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)", + "items": { + "$ref": "#/$defs/Icon" + }, + "type": "array" + }, + "mimeType": { + "description": "The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.", + "type": "string" + }, + "name": { + "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", + "type": "string" + }, + "title": { + "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for Tool,\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", + "type": "string" + }, + "uriTemplate": { + "description": "A URI template (according to RFC 6570) that can be used to construct resource URIs.", + "format": "uri-template", + "type": "string" + } + }, + "required": [ + "name", + "uriTemplate" + ], + "type": "object" + }, + "ResourceTemplateReference": { + "description": "A reference to a resource or resource template definition.", + "properties": { + "type": { + "const": "ref/resource", + "type": "string" + }, + "uri": { + "description": "The URI or URI template of the resource.", + "format": "uri-template", + "type": "string" + } + }, + "required": [ + "type", + "uri" + ], + "type": "object" + }, + "ResourceUpdatedNotification": { + "description": "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.", + "properties": { + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "notifications/resources/updated", + "type": "string" + }, + "params": { + "$ref": "#/$defs/ResourceUpdatedNotificationParams" + } + }, + "required": [ + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "ResourceUpdatedNotificationParams": { + "description": "Parameters for a `notifications/resources/updated` notification.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "uri": { + "description": "The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "uri" + ], + "type": "object" + }, + "Result": { + "additionalProperties": {}, + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + } + }, + "type": "object" + }, + "Role": { + "description": "The sender or recipient of messages and data in a conversation.", + "enum": [ + "assistant", + "user" + ], + "type": "string" + }, + "Root": { + "description": "Represents a root directory or file that the server can operate on.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "name": { + "description": "An optional name for the root. This can be used to provide a human-readable\nidentifier for the root, which may be useful for display purposes or for\nreferencing the root in other parts of the application.", + "type": "string" + }, + "uri": { + "description": "The URI identifying the root. This *must* start with file:// for now.\nThis restriction may be relaxed in future versions of the protocol to allow\nother URI schemes.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "uri" + ], + "type": "object" + }, + "RootsListChangedNotification": { + "description": "A notification from the client to the server, informing it that the list of roots has changed.\nThis notification should be sent whenever the client adds, removes, or modifies any root.\nThe server should then request an updated list of roots using the ListRootsRequest.", + "properties": { + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "notifications/roots/list_changed", + "type": "string" + }, + "params": { + "$ref": "#/$defs/NotificationParams" + } + }, + "required": [ + "jsonrpc", + "method" + ], + "type": "object" + }, + "SamplingMessage": { + "description": "Describes a message issued to or received from an LLM API.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "content": { + "anyOf": [ + { + "$ref": "#/$defs/TextContent" + }, + { + "$ref": "#/$defs/ImageContent" + }, + { + "$ref": "#/$defs/AudioContent" + }, + { + "$ref": "#/$defs/ToolUseContent" + }, + { + "$ref": "#/$defs/ToolResultContent" + }, + { + "items": { + "$ref": "#/$defs/SamplingMessageContentBlock" + }, + "type": "array" + } + ] + }, + "role": { + "$ref": "#/$defs/Role" + } + }, + "required": [ + "content", + "role" + ], + "type": "object" + }, + "SamplingMessageContentBlock": { + "anyOf": [ + { + "$ref": "#/$defs/TextContent" + }, + { + "$ref": "#/$defs/ImageContent" + }, + { + "$ref": "#/$defs/AudioContent" + }, + { + "$ref": "#/$defs/ToolUseContent" + }, + { + "$ref": "#/$defs/ToolResultContent" + } + ] + }, + "ServerCapabilities": { + "description": "Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.", + "properties": { + "completions": { + "additionalProperties": true, + "description": "Present if the server supports argument autocompletion suggestions.", + "properties": {}, + "type": "object" + }, + "experimental": { + "additionalProperties": { + "additionalProperties": true, + "properties": {}, + "type": "object" + }, + "description": "Experimental, non-standard capabilities that the server supports.", + "type": "object" + }, + "logging": { + "additionalProperties": true, + "description": "Present if the server supports sending log messages to the client.", + "properties": {}, + "type": "object" + }, + "prompts": { + "description": "Present if the server offers any prompt templates.", + "properties": { + "listChanged": { + "description": "Whether this server supports notifications for changes to the prompt list.", + "type": "boolean" + } + }, + "type": "object" + }, + "resources": { + "description": "Present if the server offers any resources to read.", + "properties": { + "listChanged": { + "description": "Whether this server supports notifications for changes to the resource list.", + "type": "boolean" + }, + "subscribe": { + "description": "Whether this server supports subscribing to resource updates.", + "type": "boolean" + } + }, + "type": "object" + }, + "tasks": { + "description": "Present if the server supports task-augmented requests.", + "properties": { + "cancel": { + "additionalProperties": true, + "description": "Whether this server supports tasks/cancel.", + "properties": {}, + "type": "object" + }, + "list": { + "additionalProperties": true, + "description": "Whether this server supports tasks/list.", + "properties": {}, + "type": "object" + }, + "requests": { + "description": "Specifies which request types can be augmented with tasks.", + "properties": { + "tools": { + "description": "Task support for tool-related requests.", + "properties": { + "call": { + "additionalProperties": true, + "description": "Whether the server supports task-augmented tools/call requests.", + "properties": {}, + "type": "object" + } + }, + "type": "object" + } + }, + "type": "object" + } + }, + "type": "object" + }, + "tools": { + "description": "Present if the server offers any tools to call.", + "properties": { + "listChanged": { + "description": "Whether this server supports notifications for changes to the tool list.", + "type": "boolean" + } + }, + "type": "object" + } + }, + "type": "object" + }, + "ServerNotification": { + "anyOf": [ + { + "$ref": "#/$defs/CancelledNotification" + }, + { + "$ref": "#/$defs/ProgressNotification" + }, + { + "$ref": "#/$defs/ResourceListChangedNotification" + }, + { + "$ref": "#/$defs/ResourceUpdatedNotification" + }, + { + "$ref": "#/$defs/PromptListChangedNotification" + }, + { + "$ref": "#/$defs/ToolListChangedNotification" + }, + { + "$ref": "#/$defs/TaskStatusNotification" + }, + { + "$ref": "#/$defs/LoggingMessageNotification" + }, + { + "$ref": "#/$defs/ElicitationCompleteNotification" + } + ] + }, + "ServerRequest": { + "anyOf": [ + { + "$ref": "#/$defs/PingRequest" + }, + { + "$ref": "#/$defs/GetTaskRequest" + }, + { + "$ref": "#/$defs/GetTaskPayloadRequest" + }, + { + "$ref": "#/$defs/CancelTaskRequest" + }, + { + "$ref": "#/$defs/ListTasksRequest" + }, + { + "$ref": "#/$defs/CreateMessageRequest" + }, + { + "$ref": "#/$defs/ListRootsRequest" + }, + { + "$ref": "#/$defs/ElicitRequest" + } + ] + }, + "ServerResult": { + "anyOf": [ + { + "$ref": "#/$defs/Result" + }, + { + "$ref": "#/$defs/InitializeResult" + }, + { + "$ref": "#/$defs/ListResourcesResult" + }, + { + "$ref": "#/$defs/ListResourceTemplatesResult" + }, + { + "$ref": "#/$defs/ReadResourceResult" + }, + { + "$ref": "#/$defs/ListPromptsResult" + }, + { + "$ref": "#/$defs/GetPromptResult" + }, + { + "$ref": "#/$defs/ListToolsResult" + }, + { + "$ref": "#/$defs/CallToolResult" + }, + { + "$ref": "#/$defs/GetTaskResult", + "description": "The response to a tasks/get request." + }, + { + "$ref": "#/$defs/GetTaskPayloadResult" + }, + { + "$ref": "#/$defs/CancelTaskResult", + "description": "The response to a tasks/cancel request." + }, + { + "$ref": "#/$defs/ListTasksResult" + }, + { + "$ref": "#/$defs/CompleteResult" + } + ] + }, + "SetLevelRequest": { + "description": "A request from the client to the server, to enable or adjust logging.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "logging/setLevel", + "type": "string" + }, + "params": { + "$ref": "#/$defs/SetLevelRequestParams" + } + }, + "required": [ + "id", + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "SetLevelRequestParams": { + "description": "Parameters for a `logging/setLevel` request.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "properties": { + "progressToken": { + "$ref": "#/$defs/ProgressToken", + "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." + } + }, + "type": "object" + }, + "level": { + "$ref": "#/$defs/LoggingLevel", + "description": "The 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." + } + }, + "required": [ + "level" + ], + "type": "object" + }, + "SingleSelectEnumSchema": { + "anyOf": [ + { + "$ref": "#/$defs/UntitledSingleSelectEnumSchema" + }, + { + "$ref": "#/$defs/TitledSingleSelectEnumSchema" + } + ] + }, + "StringSchema": { + "properties": { + "default": { + "type": "string" + }, + "description": { + "type": "string" + }, + "format": { + "enum": [ + "date", + "date-time", + "email", + "uri" + ], + "type": "string" + }, + "maxLength": { + "type": "integer" + }, + "minLength": { + "type": "integer" + }, + "title": { + "type": "string" + }, + "type": { + "const": "string", + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" + }, + "SubscribeRequest": { + "description": "Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "resources/subscribe", + "type": "string" + }, + "params": { + "$ref": "#/$defs/SubscribeRequestParams" + } + }, + "required": [ + "id", + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "SubscribeRequestParams": { + "description": "Parameters for a `resources/subscribe` request.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "properties": { + "progressToken": { + "$ref": "#/$defs/ProgressToken", + "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." + } + }, + "type": "object" + }, + "uri": { + "description": "The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "uri" + ], + "type": "object" + }, + "Task": { + "description": "Data associated with a task.", + "properties": { + "createdAt": { + "description": "ISO 8601 timestamp when the task was created.", + "type": "string" + }, + "lastUpdatedAt": { + "description": "ISO 8601 timestamp when the task was last updated.", + "type": "string" + }, + "pollInterval": { + "description": "Suggested polling interval in milliseconds.", + "type": "integer" + }, + "status": { + "$ref": "#/$defs/TaskStatus", + "description": "Current task state." + }, + "statusMessage": { + "description": "Optional human-readable message describing the current task state.\nThis can provide context for any status, including:\n- Reasons for \"cancelled\" status\n- Summaries for \"completed\" status\n- Diagnostic information for \"failed\" status (e.g., error details, what went wrong)", + "type": "string" + }, + "taskId": { + "description": "The task identifier.", + "type": "string" + }, + "ttl": { + "description": "Actual retention duration from creation in milliseconds, null for unlimited.", + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "createdAt", + "lastUpdatedAt", + "status", + "taskId", + "ttl" + ], + "type": "object" + }, + "TaskAugmentedRequestParams": { + "description": "Common params for any task-augmented request.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "properties": { + "progressToken": { + "$ref": "#/$defs/ProgressToken", + "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." + } + }, + "type": "object" + }, + "task": { + "$ref": "#/$defs/TaskMetadata", + "description": "If specified, the caller is requesting task-augmented execution for this request.\nThe request will return a CreateTaskResult immediately, and the actual result can be\nretrieved later via tasks/result.\n\nTask augmentation is subject to capability negotiation - receivers MUST declare support\nfor task augmentation of specific request types in their capabilities." + } + }, + "type": "object" + }, + "TaskMetadata": { + "description": "Metadata for augmenting a request with task execution.\nInclude this in the `task` field of the request parameters.", + "properties": { + "ttl": { + "description": "Requested duration in milliseconds to retain task from creation.", + "type": "integer" + } + }, + "type": "object" + }, + "TaskStatus": { + "description": "The status of a task.", + "enum": [ + "cancelled", + "completed", + "failed", + "input_required", + "working" + ], + "type": "string" + }, + "TaskStatusNotification": { + "description": "An optional notification from the receiver to the requestor, informing them that a task's status has changed. Receivers are not required to send these notifications.", + "properties": { + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "notifications/tasks/status", + "type": "string" + }, + "params": { + "$ref": "#/$defs/TaskStatusNotificationParams" + } + }, + "required": [ + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "TaskStatusNotificationParams": { + "allOf": [ + { + "$ref": "#/$defs/NotificationParams" + }, + { + "$ref": "#/$defs/Task" + } + ], + "description": "Parameters for a `notifications/tasks/status` notification." + }, + "TextContent": { + "description": "Text provided to or from an LLM.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "annotations": { + "$ref": "#/$defs/Annotations", + "description": "Optional annotations for the client." + }, + "text": { + "description": "The text content of the message.", + "type": "string" + }, + "type": { + "const": "text", + "type": "string" + } + }, + "required": [ + "text", + "type" + ], + "type": "object" + }, + "TextResourceContents": { + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "mimeType": { + "description": "The MIME type of this resource, if known.", + "type": "string" + }, + "text": { + "description": "The text of the item. This must only be set if the item can actually be represented as text (not binary data).", + "type": "string" + }, + "uri": { + "description": "The URI of this resource.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "text", + "uri" + ], + "type": "object" + }, + "TitledMultiSelectEnumSchema": { + "description": "Schema for multiple-selection enumeration with display titles for each option.", + "properties": { + "default": { + "description": "Optional default value.", + "items": { + "type": "string" + }, + "type": "array" + }, + "description": { + "description": "Optional description for the enum field.", + "type": "string" + }, + "items": { + "description": "Schema for array items with enum options and display labels.", + "properties": { + "anyOf": { + "description": "Array of enum options with values and display labels.", + "items": { + "properties": { + "const": { + "description": "The constant enum value.", + "type": "string" + }, + "title": { + "description": "Display title for this option.", + "type": "string" + } + }, + "required": [ + "const", + "title" + ], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "anyOf" + ], + "type": "object" + }, + "maxItems": { + "description": "Maximum number of items to select.", + "type": "integer" + }, + "minItems": { + "description": "Minimum number of items to select.", + "type": "integer" + }, + "title": { + "description": "Optional title for the enum field.", + "type": "string" + }, + "type": { + "const": "array", + "type": "string" + } + }, + "required": [ + "items", + "type" + ], + "type": "object" + }, + "TitledSingleSelectEnumSchema": { + "description": "Schema for single-selection enumeration with display titles for each option.", + "properties": { + "default": { + "description": "Optional default value.", + "type": "string" + }, + "description": { + "description": "Optional description for the enum field.", + "type": "string" + }, + "oneOf": { + "description": "Array of enum options with values and display labels.", + "items": { + "properties": { + "const": { + "description": "The enum value.", + "type": "string" + }, + "title": { + "description": "Display label for this option.", + "type": "string" + } + }, + "required": [ + "const", + "title" + ], + "type": "object" + }, + "type": "array" + }, + "title": { + "description": "Optional title for the enum field.", + "type": "string" + }, + "type": { + "const": "string", + "type": "string" + } + }, + "required": [ + "oneOf", + "type" + ], + "type": "object" + }, + "Tool": { + "description": "Definition for a tool the client can call.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "annotations": { + "$ref": "#/$defs/ToolAnnotations", + "description": "Optional additional tool information.\n\nDisplay name precedence order is: title, annotations.title, then name." + }, + "description": { + "description": "A human-readable description of the tool.\n\nThis can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a \"hint\" to the model.", + "type": "string" + }, + "execution": { + "$ref": "#/$defs/ToolExecution", + "description": "Execution-related properties for this tool." + }, + "icons": { + "description": "Optional set of sized icons that the client can display in a user interface.\n\nClients that support rendering icons MUST support at least the following MIME types:\n- `image/png` - PNG images (safe, universal compatibility)\n- `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n\nClients that support rendering icons SHOULD also support:\n- `image/svg+xml` - SVG images (scalable but requires security precautions)\n- `image/webp` - WebP images (modern, efficient format)", + "items": { + "$ref": "#/$defs/Icon" + }, + "type": "array" + }, + "inputSchema": { + "description": "A JSON Schema object defining the expected parameters for the tool.", + "properties": { + "$schema": { + "type": "string" + }, + "properties": { + "additionalProperties": { + "additionalProperties": true, + "properties": {}, + "type": "object" + }, + "type": "object" + }, + "required": { + "items": { + "type": "string" + }, + "type": "array" + }, + "type": { + "const": "object", + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" + }, + "name": { + "description": "Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).", + "type": "string" + }, + "outputSchema": { + "description": "An optional JSON Schema object defining the structure of the tool's output returned in\nthe structuredContent field of a CallToolResult.\n\nDefaults to JSON Schema 2020-12 when no explicit $schema is provided.\nCurrently restricted to type: \"object\" at the root level.", + "properties": { + "$schema": { + "type": "string" + }, + "properties": { + "additionalProperties": { + "additionalProperties": true, + "properties": {}, + "type": "object" + }, + "type": "object" + }, + "required": { + "items": { + "type": "string" + }, + "type": "array" + }, + "type": { + "const": "object", + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object" + }, + "title": { + "description": "Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\neven by those unfamiliar with domain-specific terminology.\n\nIf not provided, the name should be used for display (except for Tool,\nwhere `annotations.title` should be given precedence over using `name`,\nif present).", + "type": "string" + } + }, + "required": [ + "inputSchema", + "name" + ], + "type": "object" + }, + "ToolAnnotations": { + "description": "Additional properties describing a Tool to clients.\n\nNOTE: all properties in ToolAnnotations are **hints**.\nThey are not guaranteed to provide a faithful description of\ntool behavior (including descriptive properties like `title`).\n\nClients should never make tool use decisions based on ToolAnnotations\nreceived from untrusted servers.", + "properties": { + "destructiveHint": { + "description": "If true, the tool may perform destructive updates to its environment.\nIf false, the tool performs only additive updates.\n\n(This property is meaningful only when `readOnlyHint == false`)\n\nDefault: true", + "type": "boolean" + }, + "idempotentHint": { + "description": "If true, calling the tool repeatedly with the same arguments\nwill have no additional effect on its environment.\n\n(This property is meaningful only when `readOnlyHint == false`)\n\nDefault: false", + "type": "boolean" + }, + "openWorldHint": { + "description": "If true, this tool may interact with an \"open world\" of external\nentities. If false, the tool's domain of interaction is closed.\nFor example, the world of a web search tool is open, whereas that\nof a memory tool is not.\n\nDefault: true", + "type": "boolean" + }, + "readOnlyHint": { + "description": "If true, the tool does not modify its environment.\n\nDefault: false", + "type": "boolean" + }, + "title": { + "description": "A human-readable title for the tool.", + "type": "string" + } + }, + "type": "object" + }, + "ToolChoice": { + "description": "Controls tool selection behavior for sampling requests.", + "properties": { + "mode": { + "description": "Controls the tool use ability of the model:\n- \"auto\": Model decides whether to use tools (default)\n- \"required\": Model MUST use at least one tool before completing\n- \"none\": Model MUST NOT use any tools", + "enum": [ + "auto", + "none", + "required" + ], + "type": "string" + } + }, + "type": "object" + }, + "ToolExecution": { + "description": "Execution-related properties for a tool.", + "properties": { + "taskSupport": { + "description": "Indicates whether this tool supports task-augmented execution.\nThis allows clients to handle long-running operations through polling\nthe task system.\n\n- \"forbidden\": Tool does not support task-augmented execution (default when absent)\n- \"optional\": Tool may support task-augmented execution\n- \"required\": Tool requires task-augmented execution\n\nDefault: \"forbidden\"", + "enum": [ + "forbidden", + "optional", + "required" + ], + "type": "string" + } + }, + "type": "object" + }, + "ToolListChangedNotification": { + "description": "An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.", + "properties": { + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "notifications/tools/list_changed", + "type": "string" + }, + "params": { + "$ref": "#/$defs/NotificationParams" + } + }, + "required": [ + "jsonrpc", + "method" + ], + "type": "object" + }, + "ToolResultContent": { + "description": "The result of a tool use, provided by the user back to the assistant.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "Optional metadata about the tool result. Clients SHOULD preserve this field when\nincluding tool results in subsequent sampling requests to enable caching optimizations.\n\nSee [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "content": { + "description": "The unstructured result content of the tool use.\n\nThis has the same format as CallToolResult.content and can include text, images,\naudio, resource links, and embedded resources.", + "items": { + "$ref": "#/$defs/ContentBlock" + }, + "type": "array" + }, + "isError": { + "description": "Whether the tool use resulted in an error.\n\nIf true, the content typically describes the error that occurred.\nDefault: false", + "type": "boolean" + }, + "structuredContent": { + "additionalProperties": {}, + "description": "An optional structured result object.\n\nIf the tool defined an outputSchema, this SHOULD conform to that schema.", + "type": "object" + }, + "toolUseId": { + "description": "The ID of the tool use this result corresponds to.\n\nThis MUST match the ID from a previous ToolUseContent.", + "type": "string" + }, + "type": { + "const": "tool_result", + "type": "string" + } + }, + "required": [ + "content", + "toolUseId", + "type" + ], + "type": "object" + }, + "ToolUseContent": { + "description": "A request from the assistant to call a tool.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "Optional metadata about the tool use. Clients SHOULD preserve this field when\nincluding tool uses in subsequent sampling requests to enable caching optimizations.\n\nSee [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "type": "object" + }, + "id": { + "description": "A unique identifier for this tool use.\n\nThis ID is used to match tool results to their corresponding tool uses.", + "type": "string" + }, + "input": { + "additionalProperties": {}, + "description": "The arguments to pass to the tool, conforming to the tool's input schema.", + "type": "object" + }, + "name": { + "description": "The name of the tool to call.", + "type": "string" + }, + "type": { + "const": "tool_use", + "type": "string" + } + }, + "required": [ + "id", + "input", + "name", + "type" + ], + "type": "object" + }, + "URLElicitationRequiredError": { + "description": "An error response that indicates that the server requires the client to provide additional information via an elicitation request.", + "properties": { + "error": { + "allOf": [ + { + "$ref": "#/$defs/Error" + }, + { + "properties": { + "code": { + "const": -32042, + "type": "integer" + }, + "data": { + "additionalProperties": {}, + "properties": { + "elicitations": { + "items": { + "$ref": "#/$defs/ElicitRequestURLParams" + }, + "type": "array" + } + }, + "required": [ + "elicitations" + ], + "type": "object" + } + }, + "required": [ + "code", + "data" + ], + "type": "object" + } + ] + }, + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + } + }, + "required": [ + "error", + "jsonrpc" + ], + "type": "object" + }, + "UnsubscribeRequest": { + "description": "Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.", + "properties": { + "id": { + "$ref": "#/$defs/RequestId" + }, + "jsonrpc": { + "const": "2.0", + "type": "string" + }, + "method": { + "const": "resources/unsubscribe", + "type": "string" + }, + "params": { + "$ref": "#/$defs/UnsubscribeRequestParams" + } + }, + "required": [ + "id", + "jsonrpc", + "method", + "params" + ], + "type": "object" + }, + "UnsubscribeRequestParams": { + "description": "Parameters for a `resources/unsubscribe` request.", + "properties": { + "_meta": { + "additionalProperties": {}, + "description": "See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.", + "properties": { + "progressToken": { + "$ref": "#/$defs/ProgressToken", + "description": "If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications." + } + }, + "type": "object" + }, + "uri": { + "description": "The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it.", + "format": "uri", + "type": "string" + } + }, + "required": [ + "uri" + ], + "type": "object" + }, + "UntitledMultiSelectEnumSchema": { + "description": "Schema for multiple-selection enumeration without display titles for options.", + "properties": { + "default": { + "description": "Optional default value.", + "items": { + "type": "string" + }, + "type": "array" + }, + "description": { + "description": "Optional description for the enum field.", + "type": "string" + }, + "items": { + "description": "Schema for the array items.", + "properties": { + "enum": { + "description": "Array of enum values to choose from.", + "items": { + "type": "string" + }, + "type": "array" + }, + "type": { + "const": "string", + "type": "string" + } + }, + "required": [ + "enum", + "type" + ], + "type": "object" + }, + "maxItems": { + "description": "Maximum number of items to select.", + "type": "integer" + }, + "minItems": { + "description": "Minimum number of items to select.", + "type": "integer" + }, + "title": { + "description": "Optional title for the enum field.", + "type": "string" + }, + "type": { + "const": "array", + "type": "string" + } + }, + "required": [ + "items", + "type" + ], + "type": "object" + }, + "UntitledSingleSelectEnumSchema": { + "description": "Schema for single-selection enumeration without display titles for options.", + "properties": { + "default": { + "description": "Optional default value.", + "type": "string" + }, + "description": { + "description": "Optional description for the enum field.", + "type": "string" + }, + "enum": { + "description": "Array of enum values to choose from.", + "items": { + "type": "string" + }, + "type": "array" + }, + "title": { + "description": "Optional title for the enum field.", + "type": "string" + }, + "type": { + "const": "string", + "type": "string" + } + }, + "required": [ + "enum", + "type" + ], + "type": "object" + } + } +} + From d72b95f25f004b70fecc976fa0b74054a637b81d Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Tue, 12 May 2026 12:43:12 +0200 Subject: [PATCH 08/27] feat: validate core model against actual json schema, fix found issues --- build.sbt | 3 +- .../scala/chimp/protocol/Completion.scala | 15 +- .../protocol/SchemaConformanceSpec.scala | 258 ++++++++++++++++++ 3 files changed, 273 insertions(+), 3 deletions(-) create mode 100644 core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala diff --git a/build.sbt b/build.sbt index 226ca73..b7deded 100644 --- a/build.sbt +++ b/build.sbt @@ -41,7 +41,8 @@ lazy val core: Project = (project in file("core")) "io.circe" %% "circe-core" % circeV, "io.circe" %% "circe-generic" % circeV, "io.circe" %% "circe-parser" % circeV, - "org.slf4j" % "slf4j-api" % "2.0.17" + "org.slf4j" % "slf4j-api" % "2.0.17", + "com.networknt" % "json-schema-validator" % "3.0.2" % Test ) ) diff --git a/core/src/main/scala/chimp/protocol/Completion.scala b/core/src/main/scala/chimp/protocol/Completion.scala index 9ae661e..3b8c097 100644 --- a/core/src/main/scala/chimp/protocol/Completion.scala +++ b/core/src/main/scala/chimp/protocol/Completion.scala @@ -1,11 +1,22 @@ package chimp.protocol -import io.circe.{Codec, Json} +import io.circe.syntax.* +import io.circe.{Codec, Decoder, DecodingFailure, Encoder, Json} -enum CompleteRef derives Codec: +enum CompleteRef: case Prompt(prompt: PromptReference) case Resource(resource: ResourceReference) +object CompleteRef: + given Encoder[CompleteRef] = Encoder.instance: + case Prompt(p) => p.asJson + case Resource(r) => r.asJson + given Decoder[CompleteRef] = Decoder.instance: c => + c.downField("type").as[String].flatMap: + case "ref/prompt" => c.as[PromptReference].map(Prompt(_)) + case "ref/resource" => c.as[ResourceReference].map(Resource(_)) + case other => Left(DecodingFailure(s"Unknown CompleteRef type: $other", c.history)) + final case class CompleteArgument(name: String, value: String) derives Codec final case class CompleteContext(arguments: Option[Map[String, String]] = None) derives Codec diff --git a/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala b/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala new file mode 100644 index 0000000..4a8598a --- /dev/null +++ b/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala @@ -0,0 +1,258 @@ +package chimp.protocol + +import com.networknt.schema.{InputFormat, SchemaRegistry, SpecificationVersion} +import io.circe.Encoder +import io.circe.syntax.* +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers + +import scala.jdk.CollectionConverters.* + +class SchemaConformanceSpec extends AnyFlatSpec with Matchers: + + private val registry = SchemaRegistry.withDefaultDialect(SpecificationVersion.DRAFT_2020_12) + + private val rootSchemaText: String = + val stream = getClass.getResourceAsStream("/schema/2025-11-25/schema.json") + assert(stream != null, "MCP schema not found on the classpath at /schema/2025-11-25/schema.json") + val text = String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8) + stream.close() + text + + private val defsText: String = + val rootJson = io.circe.parser.parse(rootSchemaText).getOrElse( + throw RuntimeException("Could not parse the bundled MCP schema as JSON") + ) + rootJson.hcursor.downField("$defs").focus + .getOrElse(throw RuntimeException("Schema root is missing $defs object")) + .noSpaces + + private def validate[T: Encoder](defName: String, value: T): Unit = + val encoded = value.asJson.deepDropNullValues.noSpaces + val wrapper = + s"""{"$$schema":"https://json-schema.org/draft/2020-12/schema","$$ref":"#/$$defs/$defName","$$defs":$defsText}""" + val schema = registry.getSchema(wrapper, InputFormat.JSON) + val errors = schema.validate(encoded, InputFormat.JSON).asScala.toList + withClue(s"Encoded JSON ($defName):\n$encoded\nViolations:\n${errors.mkString("\n")}\n"): + errors shouldBe empty + + // --- Lifecycle --- + + it should "produce InitializeRequestParams that match the spec schema" in: + validate("InitializeRequestParams", InitializeParams( + protocolVersion = ProtocolVersion.Latest, + capabilities = ClientCapabilities(), + clientInfo = Implementation(name = "chimp-test", version = "0.0.1") + )) + + it should "produce InitializeResult that match the spec schema" in: + validate("InitializeResult", InitializeResult( + protocolVersion = ProtocolVersion.Latest, + capabilities = ServerCapabilities(tools = Some(ServerToolsCapability(listChanged = Some(false)))), + serverInfo = Implementation(name = "chimp-test", version = "0.0.1"), + instructions = Some("welcome") + )) + + it should "produce Implementation that match the spec schema" in: + validate("Implementation", Implementation(name = "chimp", version = "1.0", title = Some("Chimp"))) + + it should "produce ClientCapabilities (full) that match the spec schema" in: + validate("ClientCapabilities", ClientCapabilities( + roots = Some(ClientRootsCapability(listChanged = Some(true))), + sampling = Some(io.circe.Json.obj()), + elicitation = Some(io.circe.Json.obj()) + )) + + it should "produce ServerCapabilities (full) that match the spec schema" in: + validate("ServerCapabilities", ServerCapabilities( + tools = Some(ServerToolsCapability(listChanged = Some(true))), + resources = Some(ServerResourcesCapability(subscribe = Some(true), listChanged = Some(false))), + prompts = Some(ServerPromptsCapability(listChanged = Some(true))), + logging = Some(io.circe.Json.obj()), + completions = Some(io.circe.Json.obj()) + )) + + // --- Tools --- + + it should "produce a Tool definition that matches the spec schema" in: + validate("Tool", ToolDefinition( + name = "add_numbers", + title = Some("Add numbers"), + description = Some("Adds two numbers"), + inputSchema = io.circe.Json.obj("type" -> "object".asJson), + annotations = Some(ToolAnnotations(title = Some("Add"), idempotentHint = Some(true))) + )) + + it should "produce CallToolRequestParams that match the spec schema" in: + validate("CallToolRequestParams", CallToolParams( + name = "add_numbers", + arguments = io.circe.Json.obj("a" -> 1.asJson, "b" -> 2.asJson) + )) + + it should "produce CallToolResult (text) that match the spec schema" in: + validate("CallToolResult", CallToolResult(content = List(ToolContent.Text(text = "hello")))) + + it should "produce CallToolResult (error) that match the spec schema" in: + validate("CallToolResult", CallToolResult(content = List(ToolContent.Text(text = "boom")), isError = true)) + + it should "produce ListToolsResult that match the spec schema" in: + val tool = ToolDefinition(name = "t", inputSchema = io.circe.Json.obj("type" -> "object".asJson)) + validate("ListToolsResult", ListToolsResponse(tools = List(tool), nextCursor = Some("c"))) + + // --- ContentBlock variants --- + + it should "produce TextContent that match the spec schema" in: + validate("TextContent", ToolContent.Text(text = "hi")) + + it should "produce ImageContent that match the spec schema" in: + validate("ImageContent", ToolContent.Image(data = "AAAA", mimeType = "image/png")) + + it should "produce AudioContent that match the spec schema" in: + validate("AudioContent", ToolContent.Audio(data = "AAAA", mimeType = "audio/wav")) + + // --- Resources --- + + it should "produce Resource that match the spec schema" in: + validate("Resource", Resource( + uri = "file:///x", + name = "x", + title = Some("X"), + mimeType = Some("text/plain") + )) + + it should "produce TextResourceContents that match the spec schema" in: + validate("TextResourceContents", ResourceContents.Text(uri = "file:///x", text = "body", mimeType = Some("text/plain"))) + + it should "produce BlobResourceContents that match the spec schema" in: + validate("BlobResourceContents", ResourceContents.Blob(uri = "file:///x", blob = "AAAA", mimeType = Some("application/octet-stream"))) + + it should "produce ListResourcesResult that match the spec schema" in: + validate("ListResourcesResult", ListResourcesResult(resources = List(Resource(uri = "file:///x", name = "x")))) + + it should "produce ReadResourceResult that match the spec schema" in: + validate("ReadResourceResult", ReadResourceResult(contents = List(ResourceContents.Text(uri = "file:///x", text = "y")))) + + it should "produce ResourceTemplate that match the spec schema" in: + validate("ResourceTemplate", ResourceTemplate(uriTemplate = "file:///{path}", name = "tpl")) + + // --- Prompts --- + + it should "produce Prompt that match the spec schema" in: + validate("Prompt", Prompt( + name = "greet", + title = Some("Greet"), + description = Some("Greet the user"), + arguments = Some(List(PromptArgument(name = "who", required = Some(true)))) + )) + + it should "produce PromptMessage that match the spec schema" in: + validate("PromptMessage", PromptMessage(role = Role.User, content = ToolContent.Text(text = "hi"))) + + it should "produce ListPromptsResult that match the spec schema" in: + validate("ListPromptsResult", ListPromptsResult(prompts = List(Prompt(name = "p")))) + + it should "produce GetPromptResult that match the spec schema" in: + validate("GetPromptResult", GetPromptResult(messages = List(PromptMessage(Role.Assistant, ToolContent.Text(text = "yo"))))) + + // --- Sampling --- + + it should "produce CreateMessageRequestParams that match the spec schema" in: + validate("CreateMessageRequestParams", CreateMessageParams( + messages = List(SamplingMessage(role = Role.User, content = ToolContent.Text(text = "say hi"))), + maxTokens = 100, + systemPrompt = Some("you are helpful"), + includeContext = Some(IncludeContext.None), + temperature = Some(0.5), + stopSequences = Some(List("\n\n")) + )) + + it should "produce CreateMessageResult that match the spec schema" in: + validate("CreateMessageResult", CreateMessageResult( + role = Role.Assistant, + content = ToolContent.Text(text = "hi"), + model = "claude-test", + stopReason = Some("endTurn") + )) + + // --- Elicitation --- + + it should "produce ElicitRequestParams (form variant) that match the spec schema" in: + validate("ElicitRequestParams", ElicitParams( + message = "what is your name?", + requestedSchema = io.circe.Json.obj( + "type" -> "object".asJson, + "properties" -> io.circe.Json.obj("name" -> io.circe.Json.obj("type" -> "string".asJson)) + ) + )) + + it should "produce ElicitResult that match the spec schema" in: + validate("ElicitResult", ElicitResult( + action = ElicitAction.Accept, + content = Some(Map("name" -> "Alice".asJson)) + )) + + // --- Roots --- + + it should "produce Root that match the spec schema" in: + validate("Root", Root(uri = "file:///workspace", name = Some("workspace"))) + + it should "produce ListRootsResult that match the spec schema" in: + validate("ListRootsResult", ListRootsResult(roots = List(Root(uri = "file:///workspace")))) + + // --- Completion --- + + it should "produce CompleteRequestParams that match the spec schema" in: + validate("CompleteRequestParams", CompleteParams( + ref = CompleteRef.Prompt(PromptReference(name = "greet")), + argument = CompleteArgument(name = "who", value = "al") + )) + + it should "produce CompleteResult that match the spec schema" in: + validate("CompleteResult", CompleteResult(completion = Completion(values = List("Alice", "Alex"), total = Some(2), hasMore = Some(false)))) + + // --- Logging --- + + it should "produce SetLevelRequestParams that match the spec schema" in: + validate("SetLevelRequestParams", SetLevelParams(level = LoggingLevel.Info)) + + it should "produce LoggingMessageNotificationParams that match the spec schema" in: + validate("LoggingMessageNotificationParams", LoggingMessageParams( + level = LoggingLevel.Warning, + data = io.circe.Json.fromString("something happened"), + logger = Some("chimp") + )) + + // --- Progress / Cancellation --- + + it should "produce ProgressNotificationParams that match the spec schema" in: + validate("ProgressNotificationParams", ProgressParams( + progressToken = ProgressToken("t1"), + progress = 0.5, + total = Some(1.0), + message = Some("halfway") + )) + + it should "produce CancelledNotificationParams that match the spec schema" in: + validate("CancelledNotificationParams", CancelledParams(requestId = RequestId("r1"), reason = Some("user cancelled"))) + + // --- JSON-RPC envelope --- + + it should "produce a JSON-RPC Request envelope that match the spec schema" in: + val msg: JSONRPCMessage = + JSONRPCMessage.Request(method = "tools/list", params = Some(io.circe.Json.obj()), id = RequestId(1)) + validate("JSONRPCRequest", msg) + + it should "produce a JSON-RPC Notification envelope that match the spec schema" in: + val msg: JSONRPCMessage = + JSONRPCMessage.Notification(method = "notifications/initialized", params = Some(io.circe.Json.obj())) + validate("JSONRPCNotification", msg) + + it should "produce a JSON-RPC Response envelope that match the spec schema" in: + val msg: JSONRPCMessage = + JSONRPCMessage.Response(id = RequestId(1), result = io.circe.Json.obj()) + validate("JSONRPCResultResponse", msg) + + it should "produce a JSON-RPC Error envelope that match the spec schema" in: + val msg: JSONRPCMessage = + JSONRPCMessage.Error(id = RequestId(1), error = JSONRPCErrorObject(code = -32601, message = "not found")) + validate("JSONRPCErrorResponse", msg) From 20c35eaf1cedd93a6418778fc573e84d80c1691b Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Tue, 12 May 2026 12:52:45 +0200 Subject: [PATCH 09/27] feat: test encode decode round trip in single spec --- .../test/scala/chimp/protocol/ModelSpec.scala | 180 ------------------ .../protocol/SchemaConformanceSpec.scala | 17 +- 2 files changed, 12 insertions(+), 185 deletions(-) delete mode 100644 core/src/test/scala/chimp/protocol/ModelSpec.scala diff --git a/core/src/test/scala/chimp/protocol/ModelSpec.scala b/core/src/test/scala/chimp/protocol/ModelSpec.scala deleted file mode 100644 index c5d26c5..0000000 --- a/core/src/test/scala/chimp/protocol/ModelSpec.scala +++ /dev/null @@ -1,180 +0,0 @@ -package chimp.protocol - -import io.circe.Json -import io.circe.parser.* -import io.circe.syntax.* -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers - -class ModelSpec extends AnyFlatSpec with Matchers { - import JSONRPCMessage.* - import chimp.protocol.JSONRPCErrorCodes.* - - // Helper function to parse JSON strings - private def parseJson(str: String): Json = parse(str).getOrElse(throw new RuntimeException("Invalid JSON")) - - "JSONRPCMessage" should "handle Request messages according to JSON-RPC 2.0 spec" in { - // Given - val request: JSONRPCMessage = Request( - method = "test/method", - params = Some(Json.obj("param1" -> Json.fromString("value1"))), - id = RequestId("123") - ) - val expectedJson = parseJson(""" - { - "jsonrpc": "2.0", - "method": "test/method", - "params": {"param1": "value1"}, - "id": "123" - } - """) - - // When - val json = request.asJson - val decoded = json.as[JSONRPCMessage].getOrElse(fail("Failed to decode JSON")) - - // Then - json shouldBe expectedJson - decoded shouldBe request - } - - it should "handle Notification messages according to JSON-RPC 2.0 spec" in { - // Given - val notification: JSONRPCMessage = Notification( - method = "test/notification", - params = Some(Json.obj("param1" -> Json.fromString("value1"))) - ) - val expectedJson = parseJson(""" - { - "jsonrpc": "2.0", - "method": "test/notification", - "params": {"param1": "value1"} - } - """) - - // When - val json = notification.asJson - val decoded = json.as[JSONRPCMessage].getOrElse(fail("Failed to decode JSON")) - - // Then - json shouldBe expectedJson - decoded shouldBe notification - } - - it should "handle Response messages according to JSON-RPC 2.0 spec" in { - // Given - val response: JSONRPCMessage = Response( - id = RequestId(123), - result = Json.obj("result" -> Json.fromString("success")) - ) - val expectedJson = parseJson(""" - { - "jsonrpc": "2.0", - "id": 123, - "result": {"result": "success"} - } - """) - - // When - val json = response.asJson - val decoded = json.as[JSONRPCMessage].getOrElse(fail("Failed to decode JSON")) - - // Then - json shouldBe expectedJson - decoded shouldBe response - } - - it should "handle Error messages according to JSON-RPC 2.0 spec" in { - // Given - val error: JSONRPCMessage = Error( - id = RequestId("error-123"), - error = JSONRPCErrorObject( - code = InvalidRequest.code, - message = "Invalid request", - data = Some(Json.obj("details" -> Json.fromString("More info"))) - ) - ) - val expectedJson = parseJson(""" - { - "jsonrpc": "2.0", - "id": "error-123", - "error": { - "code": -32600, - "message": "Invalid request", - "data": {"details": "More info"} - } - } - """) - - // When - val json = error.asJson - val decoded = json.as[JSONRPCMessage].getOrElse(fail("Failed to decode JSON")) - - // Then - json shouldBe expectedJson - decoded shouldBe error - } - - it should "handle both numeric and string request IDs according to JSON-RPC 2.0 spec" in { - // Given - val numericRequest: JSONRPCMessage = Request(method = "test", id = RequestId(123)) - val stringRequest: JSONRPCMessage = Request(method = "test", id = RequestId("abc")) - - // When - val numericJson = numericRequest.asJson - val stringJson = stringRequest.asJson - val decodedNumeric = numericJson.as[JSONRPCMessage].getOrElse(fail()) - val decodedString = stringJson.as[JSONRPCMessage].getOrElse(fail()) - - // Then - decodedNumeric shouldBe numericRequest - decodedString shouldBe stringRequest - } - - it should "handle optional parameters according to JSON-RPC 2.0 spec" in { - // Given - val requestWithParams: JSONRPCMessage = Request( - method = "test", - params = Some(Json.obj("param" -> Json.fromString("value"))), - id = RequestId(1) - ) - val requestWithoutParams: JSONRPCMessage = Request(method = "test", id = RequestId(2)) - - // When - val jsonWithParams = requestWithParams.asJson - val jsonWithoutParams = requestWithoutParams.asJson - val decodedWithParams = jsonWithParams.as[JSONRPCMessage].getOrElse(fail()) - val decodedWithoutParams = jsonWithoutParams.as[JSONRPCMessage].getOrElse(fail()) - - // Then - decodedWithParams shouldBe requestWithParams - decodedWithoutParams shouldBe requestWithoutParams - } - - it should "handle all standard JSON-RPC error codes according to spec" in { - // Given - val errorCodes = List( - ParseError, - InvalidRequest, - MethodNotFound, - InvalidParams, - InternalError - ) - - // When/Then - errorCodes.foreach { code => - // Given - val error: JSONRPCMessage = Error( - id = RequestId("test"), - error = JSONRPCErrorObject(code = code.code, message = "Test error") - ) - - // When - val json = error.asJson - val decoded = json.as[JSONRPCMessage].getOrElse(fail()) - - // Then - decoded shouldBe error - } - } -} diff --git a/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala b/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala index 4a8598a..7495de9 100644 --- a/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala +++ b/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala @@ -1,7 +1,7 @@ package chimp.protocol import com.networknt.schema.{InputFormat, SchemaRegistry, SpecificationVersion} -import io.circe.Encoder +import io.circe.{Decoder, Encoder} import io.circe.syntax.* import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers @@ -27,14 +27,21 @@ class SchemaConformanceSpec extends AnyFlatSpec with Matchers: .getOrElse(throw RuntimeException("Schema root is missing $defs object")) .noSpaces - private def validate[T: Encoder](defName: String, value: T): Unit = - val encoded = value.asJson.deepDropNullValues.noSpaces + private def validate[T: Encoder: Decoder](defName: String, value: T): Unit = + val encodedJson = value.asJson.deepDropNullValues + val encodedStr = encodedJson.noSpaces val wrapper = s"""{"$$schema":"https://json-schema.org/draft/2020-12/schema","$$ref":"#/$$defs/$defName","$$defs":$defsText}""" val schema = registry.getSchema(wrapper, InputFormat.JSON) - val errors = schema.validate(encoded, InputFormat.JSON).asScala.toList - withClue(s"Encoded JSON ($defName):\n$encoded\nViolations:\n${errors.mkString("\n")}\n"): + val errors = schema.validate(encodedStr, InputFormat.JSON).asScala.toList + withClue(s"Encoded JSON ($defName):\n$encodedStr\nViolations:\n${errors.mkString("\n")}\n"): errors shouldBe empty + val _ = encodedJson.as[T] match + case Right(decoded) => + withClue(s"Round-trip mismatch ($defName):\nencoded: $encodedStr\n"): + decoded shouldBe value + case Left(err) => + fail(s"Decode round-trip failed for $defName:\nencoded: $encodedStr\nerror: ${err.getMessage}") // --- Lifecycle --- From c6125cb2882f7e1042376ce19eb821f635d403e9 Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Tue, 12 May 2026 14:25:49 +0200 Subject: [PATCH 10/27] feat: fill in missing model tests --- .../scala/chimp/protocol/Elicitation.scala | 10 ------ .../protocol/SchemaConformanceSpec.scala | 35 ++++++++++++++++++- 2 files changed, 34 insertions(+), 11 deletions(-) diff --git a/core/src/main/scala/chimp/protocol/Elicitation.scala b/core/src/main/scala/chimp/protocol/Elicitation.scala index e42cba1..56d4af6 100644 --- a/core/src/main/scala/chimp/protocol/Elicitation.scala +++ b/core/src/main/scala/chimp/protocol/Elicitation.scala @@ -29,13 +29,3 @@ final case class ElicitResult( content: Option[Map[String, Json]] = None, _meta: Option[Map[String, Json]] = None ) derives Codec - -object Elicitation: - def applyDefaults(requestedSchema: Json, provided: Map[String, Json]): Map[String, Json] = - val propsOpt = requestedSchema.hcursor.downField("properties").focus.flatMap(_.asObject) - propsOpt match - case None => provided - case Some(props) => - val withDefaults = props.toMap.flatMap: (key, schema) => - schema.hcursor.downField("default").focus.map(d => key -> d) - withDefaults ++ provided diff --git a/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala b/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala index 7495de9..c781d15 100644 --- a/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala +++ b/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala @@ -102,6 +102,9 @@ class SchemaConformanceSpec extends AnyFlatSpec with Matchers: it should "produce CallToolResult (error) that match the spec schema" in: validate("CallToolResult", CallToolResult(content = List(ToolContent.Text(text = "boom")), isError = true)) + it should "produce ListToolsParams that match the spec schema (PaginatedRequestParams)" in: + validate("PaginatedRequestParams", ListToolsParams(cursor = Some("c"))) + it should "produce ListToolsResult that match the spec schema" in: val tool = ToolDefinition(name = "t", inputSchema = io.circe.Json.obj("type" -> "object".asJson)) validate("ListToolsResult", ListToolsResponse(tools = List(tool), nextCursor = Some("c"))) @@ -133,15 +136,33 @@ class SchemaConformanceSpec extends AnyFlatSpec with Matchers: it should "produce BlobResourceContents that match the spec schema" in: validate("BlobResourceContents", ResourceContents.Blob(uri = "file:///x", blob = "AAAA", mimeType = Some("application/octet-stream"))) + it should "produce ListResourcesParams that match the spec schema (PaginatedRequestParams)" in: + validate("PaginatedRequestParams", ListResourcesParams(cursor = Some("c"))) + it should "produce ListResourcesResult that match the spec schema" in: validate("ListResourcesResult", ListResourcesResult(resources = List(Resource(uri = "file:///x", name = "x")))) + it should "produce ListResourceTemplatesParams that match the spec schema (PaginatedRequestParams)" in: + validate("PaginatedRequestParams", ListResourceTemplatesParams(cursor = Some("c"))) + + it should "produce ReadResourceRequestParams that match the spec schema" in: + validate("ReadResourceRequestParams", ReadResourceParams(uri = "file:///x")) + it should "produce ReadResourceResult that match the spec schema" in: validate("ReadResourceResult", ReadResourceResult(contents = List(ResourceContents.Text(uri = "file:///x", text = "y")))) it should "produce ResourceTemplate that match the spec schema" in: validate("ResourceTemplate", ResourceTemplate(uriTemplate = "file:///{path}", name = "tpl")) + it should "produce SubscribeRequestParams that match the spec schema" in: + validate("SubscribeRequestParams", SubscribeParams(uri = "file:///x")) + + it should "produce UnsubscribeRequestParams that match the spec schema" in: + validate("UnsubscribeRequestParams", UnsubscribeParams(uri = "file:///x")) + + it should "produce ResourceUpdatedNotificationParams that match the spec schema" in: + validate("ResourceUpdatedNotificationParams", ResourceUpdatedParams(uri = "file:///x")) + // --- Prompts --- it should "produce Prompt that match the spec schema" in: @@ -155,9 +176,15 @@ class SchemaConformanceSpec extends AnyFlatSpec with Matchers: it should "produce PromptMessage that match the spec schema" in: validate("PromptMessage", PromptMessage(role = Role.User, content = ToolContent.Text(text = "hi"))) + it should "produce ListPromptsParams that match the spec schema (PaginatedRequestParams)" in: + validate("PaginatedRequestParams", ListPromptsParams(cursor = Some("c"))) + it should "produce ListPromptsResult that match the spec schema" in: validate("ListPromptsResult", ListPromptsResult(prompts = List(Prompt(name = "p")))) + it should "produce GetPromptRequestParams that match the spec schema" in: + validate("GetPromptRequestParams", GetPromptParams(name = "greet", arguments = Some(Map("who" -> "Alice")))) + it should "produce GetPromptResult that match the spec schema" in: validate("GetPromptResult", GetPromptResult(messages = List(PromptMessage(Role.Assistant, ToolContent.Text(text = "yo"))))) @@ -208,12 +235,18 @@ class SchemaConformanceSpec extends AnyFlatSpec with Matchers: // --- Completion --- - it should "produce CompleteRequestParams that match the spec schema" in: + it should "produce CompleteRequestParams (prompt ref) that match the spec schema" in: validate("CompleteRequestParams", CompleteParams( ref = CompleteRef.Prompt(PromptReference(name = "greet")), argument = CompleteArgument(name = "who", value = "al") )) + it should "produce CompleteRequestParams (resource template ref) that match the spec schema" in: + validate("CompleteRequestParams", CompleteParams( + ref = CompleteRef.Resource(ResourceReference(uri = "file:///{path}")), + argument = CompleteArgument(name = "path", value = "src/") + )) + it should "produce CompleteResult that match the spec schema" in: validate("CompleteResult", CompleteResult(completion = Completion(values = List("Alice", "Alex"), total = Some(2), hasMore = Some(false)))) From 55878861a2c1ed1d521a8aa2e6765f675b4b8988 Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Tue, 12 May 2026 14:49:31 +0200 Subject: [PATCH 11/27] fix: stricter compilation settings, resolve warnings --- build.sbt | 3 ++- .../src/main/scala/chimp/conformance/client/Main.scala | 6 +++--- .../scala/chimp/client/internal/CapabilityHandlers.scala | 2 +- .../scala/chimp/client/transport/StdioTransport.scala | 8 ++++---- .../chimp/client/transport/StreamingHttpTransport.scala | 6 +++--- .../chimp/client/transport/StreamingStdioTransport.scala | 8 ++++---- .../test/scala/chimp/client/CapabilityDispatchSpec.scala | 2 +- client/src/test/scala/chimp/client/CapsDeriveSpec.scala | 2 +- core/src/main/scala/chimp/protocol/Prompts.scala | 2 +- 9 files changed, 20 insertions(+), 19 deletions(-) diff --git a/build.sbt b/build.sbt index b7deded..6aca25a 100644 --- a/build.sbt +++ b/build.sbt @@ -20,7 +20,8 @@ lazy val commonSettings = commonSmlBuildSettings ++ ossPublishSettings ++ Seq( } }.value, Test / scalacOptions += "-Wconf:msg=unused value of type org.scalatest.Assertion:s", - Test / scalacOptions += "-Wconf:msg=unused value of type org.scalatest.compatible.Assertion:s" + Test / scalacOptions += "-Wconf:msg=unused value of type org.scalatest.compatible.Assertion:s", + scalacOptions ++= Seq("-Wunused:all", "-Werror") ) val scalaTest = "org.scalatest" %% "scalatest" % scalaTestV % Test diff --git a/client-conformance/src/main/scala/chimp/conformance/client/Main.scala b/client-conformance/src/main/scala/chimp/conformance/client/Main.scala index d1d3533..14f18e7 100644 --- a/client-conformance/src/main/scala/chimp/conformance/client/Main.scala +++ b/client-conformance/src/main/scala/chimp/conformance/client/Main.scala @@ -31,14 +31,14 @@ object Main: scenario match case "initialize" => val client = McpClient[Identity, Any](transport, clientInfo, protocolVersion) - client.initialize() + val _ = client.initialize() client.close() 0 case "tools_call" => val client = McpClient[Identity, Any](transport, clientInfo, protocolVersion) - client.initialize() - client.callTool( + val _ = client.initialize() + val _ = client.callTool( "add_numbers", Json.obj("a" -> Json.fromInt(2), "b" -> Json.fromInt(3)) ) diff --git a/client/src/main/scala/chimp/client/internal/CapabilityHandlers.scala b/client/src/main/scala/chimp/client/internal/CapabilityHandlers.scala index 371896c..dd7fc6b 100644 --- a/client/src/main/scala/chimp/client/internal/CapabilityHandlers.scala +++ b/client/src/main/scala/chimp/client/internal/CapabilityHandlers.scala @@ -3,7 +3,7 @@ package chimp.client.internal import chimp.client.capabilities.{Elicitation, Roots, Sampling} import chimp.protocol.{CreateMessageRequest, ElicitRequest} import io.circe.syntax.* -import io.circe.{Json, parser} +import io.circe.Json import sttp.monad.MonadError import sttp.monad.syntax.* diff --git a/client/src/main/scala/chimp/client/transport/StdioTransport.scala b/client/src/main/scala/chimp/client/transport/StdioTransport.scala index 52177bf..5d75747 100644 --- a/client/src/main/scala/chimp/client/transport/StdioTransport.scala +++ b/client/src/main/scala/chimp/client/transport/StdioTransport.scala @@ -78,10 +78,10 @@ final class StdioTransport( private def dispatch(msg: JSONRPCMessage): Unit = msg match case r: JSONRPCMessage.Response => val q = pending.remove(r.id) - if q != null then q.offer(r, 1, TimeUnit.SECONDS) + if q != null then { val _ = q.offer(r, 1, TimeUnit.SECONDS) } case e: JSONRPCMessage.Error => val q = pending.remove(e.id) - if q != null then q.offer(e, 1, TimeUnit.SECONDS) + if q != null then { val _ = q.offer(e, 1, TimeUnit.SECONDS) } case other => incomingHandler.get()(other) @@ -93,7 +93,7 @@ final class StdioTransport( id = entry.getKey, error = chimp.protocol.JSONRPCErrorObject(code = -32000, message = "Transport closed") ) - entry.getValue.offer(poison, 100, TimeUnit.MILLISECONDS) + val _ = entry.getValue.offer(poison, 100, TimeUnit.MILLISECONDS) it.remove() override def send(msg: JSONRPCMessage): Identity[Option[JSONRPCMessage]] = @@ -122,6 +122,6 @@ final class StdioTransport( try writer.close() catch case _: Exception => () if proc.isAlive then if !proc.waitFor(2, TimeUnit.SECONDS) then proc.destroy() - if !proc.waitFor(2, TimeUnit.SECONDS) then proc.destroyForcibly() + if !proc.waitFor(2, TimeUnit.SECONDS) then { val _ = proc.destroyForcibly() } readerThread.interrupt() stderrThread.interrupt() diff --git a/client/src/main/scala/chimp/client/transport/StreamingHttpTransport.scala b/client/src/main/scala/chimp/client/transport/StreamingHttpTransport.scala index 7e55e4f..4eeffa3 100644 --- a/client/src/main/scala/chimp/client/transport/StreamingHttpTransport.scala +++ b/client/src/main/scala/chimp/client/transport/StreamingHttpTransport.scala @@ -10,7 +10,7 @@ import sttp.model.Uri * resumability via `Last-Event-ID`, and bidirectional server-initiated dispatch over a long-lived GET. */ abstract class StreamingHttpTransport[F[_], S]( - backend: StreamBackend[F, S], - uri: Uri, - streams: Streams[S] + protected val backend: StreamBackend[F, S], + protected val uri: Uri, + protected val streams: Streams[S] ) extends Transport[F] diff --git a/client/src/main/scala/chimp/client/transport/StreamingStdioTransport.scala b/client/src/main/scala/chimp/client/transport/StreamingStdioTransport.scala index a710810..7b0b39b 100644 --- a/client/src/main/scala/chimp/client/transport/StreamingStdioTransport.scala +++ b/client/src/main/scala/chimp/client/transport/StreamingStdioTransport.scala @@ -10,8 +10,8 @@ import java.io.File * `readLine` reads with non-blocking stream consumption tied to the effect's runtime. */ abstract class StreamingStdioTransport[F[_], S]( - command: List[String], - env: Map[String, String] = Map.empty, - workDir: Option[File] = None, - streams: Streams[S] + protected val command: List[String], + protected val env: Map[String, String] = Map.empty, + protected val workDir: Option[File] = None, + protected val streams: Streams[S] ) extends Transport[F] diff --git a/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala b/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala index 5730775..e03fa64 100644 --- a/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala +++ b/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala @@ -61,7 +61,7 @@ class CapabilityDispatchSpec extends AnyFlatSpec with Matchers: ) t.planResponse(JSONRPCMessage.Response(id = RequestId(1), result = initResult.asJson)) val client = McpClient[Identity, Roots[Identity] & Elicitation[Identity]](t, clientInfo) - client.initialize() + val _ = client.initialize() t.sent.head match case r: JSONRPCMessage.Request => diff --git a/client/src/test/scala/chimp/client/CapsDeriveSpec.scala b/client/src/test/scala/chimp/client/CapsDeriveSpec.scala index 41b2b81..22e3ecb 100644 --- a/client/src/test/scala/chimp/client/CapsDeriveSpec.scala +++ b/client/src/test/scala/chimp/client/CapsDeriveSpec.scala @@ -1,6 +1,6 @@ package chimp.client -import chimp.client.capabilities.{CapsDerive, Elicitation, Roots, Sampling} +import chimp.client.capabilities.{CapsDerive, Elicitation, Roots} import chimp.protocol.{ClientCapabilities, ElicitRequest, ElicitResult, ListRootsResult} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers diff --git a/core/src/main/scala/chimp/protocol/Prompts.scala b/core/src/main/scala/chimp/protocol/Prompts.scala index f83e00f..8db10a3 100644 --- a/core/src/main/scala/chimp/protocol/Prompts.scala +++ b/core/src/main/scala/chimp/protocol/Prompts.scala @@ -1,6 +1,6 @@ package chimp.protocol -import io.circe.{Codec, Decoder, DecodingFailure, Encoder, Json} +import io.circe.{Codec, Decoder, Encoder, Json} enum Role: case User, Assistant From e053362708d8e54ef8dfd32f94844d6d12f954ae Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Tue, 12 May 2026 16:20:26 +0200 Subject: [PATCH 12/27] fix: simplify client capabilities --- .../scala/chimp/conformance/client/Main.scala | 4 +- .../scala/chimp/client/DefaultMcpClient.scala | 54 ++++++++++++---- .../main/scala/chimp/client/McpClient.scala | 29 ++++++--- .../client/capabilities/CapsDerive.scala | 63 ------------------- .../client/capabilities/Elicitation.scala | 7 --- .../chimp/client/capabilities/Roots.scala | 7 --- .../chimp/client/capabilities/Sampling.scala | 7 --- .../client/internal/CapabilityHandlers.scala | 32 ---------- .../chimp/client/CapabilityDispatchSpec.scala | 23 ++++--- .../scala/chimp/client/CapsDeriveSpec.scala | 35 ----------- .../scala/chimp/client/McpClientSpec.scala | 4 +- 11 files changed, 79 insertions(+), 186 deletions(-) delete mode 100644 client/src/main/scala/chimp/client/capabilities/CapsDerive.scala delete mode 100644 client/src/main/scala/chimp/client/capabilities/Elicitation.scala delete mode 100644 client/src/main/scala/chimp/client/capabilities/Roots.scala delete mode 100644 client/src/main/scala/chimp/client/capabilities/Sampling.scala delete mode 100644 client/src/main/scala/chimp/client/internal/CapabilityHandlers.scala delete mode 100644 client/src/test/scala/chimp/client/CapsDeriveSpec.scala diff --git a/client-conformance/src/main/scala/chimp/conformance/client/Main.scala b/client-conformance/src/main/scala/chimp/conformance/client/Main.scala index 14f18e7..0c6d626 100644 --- a/client-conformance/src/main/scala/chimp/conformance/client/Main.scala +++ b/client-conformance/src/main/scala/chimp/conformance/client/Main.scala @@ -30,13 +30,13 @@ object Main: try scenario match case "initialize" => - val client = McpClient[Identity, Any](transport, clientInfo, protocolVersion) + val client = McpClient[Identity](transport, clientInfo, protocolVersion = protocolVersion) val _ = client.initialize() client.close() 0 case "tools_call" => - val client = McpClient[Identity, Any](transport, clientInfo, protocolVersion) + val client = McpClient[Identity](transport, clientInfo, protocolVersion = protocolVersion) val _ = client.initialize() val _ = client.callTool( "add_numbers", diff --git a/client/src/main/scala/chimp/client/DefaultMcpClient.scala b/client/src/main/scala/chimp/client/DefaultMcpClient.scala index 75ce645..0aa6758 100644 --- a/client/src/main/scala/chimp/client/DefaultMcpClient.scala +++ b/client/src/main/scala/chimp/client/DefaultMcpClient.scala @@ -1,6 +1,6 @@ package chimp.client -import chimp.client.internal.{CapabilityHandlers, Correlator} +import chimp.client.internal.Correlator import chimp.client.notifications.ServerNotificationListener import chimp.client.transport.Transport import chimp.protocol.* @@ -12,34 +12,64 @@ import sttp.monad.syntax.* import java.util.concurrent.atomic.AtomicReference object DefaultMcpClient: - def create[F[_], Caps]( + def create[F[_]]( transport: Transport[F], clientInfo: Implementation, protocolVersion: String, - wireCaps: ClientCapabilities, - handlers: CapabilityHandlers[F] - ): McpClient[F, Caps] = - val impl = new Impl[F, Caps](transport, clientInfo, protocolVersion, wireCaps, handlers) + rootsHandler: Option[() => F[ListRootsResult]], + samplingHandler: Option[CreateMessageRequest => F[CreateMessageResult]], + elicitationHandler: Option[ElicitRequest => F[ElicitResult]] + ): McpClient[F] = + val impl = new Impl[F](transport, clientInfo, protocolVersion, rootsHandler, samplingHandler, elicitationHandler) impl.installIncoming() impl - private final class Impl[F[_], Caps]( + private final class Impl[F[_]]( transport: Transport[F], clientInfo: Implementation, protocolVersion: String, - wireCaps: ClientCapabilities, - handlers: CapabilityHandlers[F] - ) extends McpClient[F, Caps]: + rootsHandler: Option[() => F[ListRootsResult]], + samplingHandler: Option[CreateMessageRequest => F[CreateMessageResult]], + elicitationHandler: Option[ElicitRequest => F[ElicitResult]] + ) extends McpClient[F]: private given MonadError[F] = transport.monad private val correlator = Correlator() private val listeners = AtomicReference[List[ServerNotificationListener[F]]](Nil) + private val wireCaps: ClientCapabilities = ClientCapabilities( + roots = rootsHandler.map(_ => ClientRootsCapability(listChanged = Some(true))), + sampling = samplingHandler.map(_ => Json.obj()), + elicitation = elicitationHandler.map(_ => Json.obj()) + ) + + private val dispatch: Map[String, Json => F[Json]] = + val entries = List( + rootsHandler.map(fn => + "roots/list" -> ((_: Json) => fn().map(_.asJson)) + ), + samplingHandler.map(fn => + "sampling/createMessage" -> ((params: Json) => + params.as[CreateMessageRequest] match + case Right(req) => fn(req).map(_.asJson) + case Left(e) => summon[MonadError[F]].error(IllegalArgumentException(s"Failed to decode CreateMessageRequest: ${e.getMessage}")) + ) + ), + elicitationHandler.map(fn => + "elicitation/create" -> ((params: Json) => + params.as[ElicitRequest] match + case Right(req) => fn(req).map(_.asJson) + case Left(e) => summon[MonadError[F]].error(IllegalArgumentException(s"Failed to decode ElicitRequest: ${e.getMessage}")) + ) + ) + ).flatten + entries.toMap + def installIncoming(): Unit = val _ = transport.onIncoming(handleIncoming) private def handleIncoming(msg: JSONRPCMessage): F[Unit] = msg match case JSONRPCMessage.Request(_, method, params, id) => - handlers.methods.get(method) match + dispatch.get(method) match case Some(h) => val rawParams = params.getOrElse(Json.obj()) h(rawParams).flatMap(result => @@ -129,7 +159,7 @@ object DefaultMcpClient: sendNotification("notifications/roots/list_changed", None) override def onServerNotification(listener: ServerNotificationListener[F]): F[Unit] = - listeners.updateAndGet(ls => ls :+ listener) + val _ = listeners.updateAndGet(ls => ls :+ listener) summon[MonadError[F]].unit(()) private def sendRequest[R: Decoder](method: String, params: Option[Json]): F[R] = diff --git a/client/src/main/scala/chimp/client/McpClient.scala b/client/src/main/scala/chimp/client/McpClient.scala index cf3679d..f8447ac 100644 --- a/client/src/main/scala/chimp/client/McpClient.scala +++ b/client/src/main/scala/chimp/client/McpClient.scala @@ -1,17 +1,17 @@ package chimp.client -import chimp.client.capabilities.CapsDerive import chimp.client.notifications.ServerNotificationListener import chimp.client.transport.Transport import chimp.protocol.* import io.circe.Json -import sttp.monad.MonadError -/** An MCP client. The `Caps` type parameter is an intersection of capability typeclasses (`Roots[F]`, `Sampling[F]`, `Elicitation[F]`) - * the host application opts into; each one is advertised on `initialize` and routed to the corresponding `given` handler when the - * server invokes it. +/** An MCP client. + * + * Server-initiated requests (`roots/list`, `sampling/createMessage`, `elicitation/create`) are dispatched to the optional + * handler functions supplied at construction. Each handler that is `Some` causes the corresponding capability to be advertised + * on `initialize`; capabilities the host application doesn't opt into are answered with `MethodNotFound`. */ -trait McpClient[F[_], +Caps]: +trait McpClient[F[_]]: def initialize(): F[InitializeResult] def ping(): F[Unit] def close(): F[Unit] @@ -39,10 +39,19 @@ trait McpClient[F[_], +Caps]: def onServerNotification(listener: ServerNotificationListener[F]): F[Unit] object McpClient: - def apply[F[_], Caps]( + def apply[F[_]]( transport: Transport[F], clientInfo: Implementation, + rootsHandler: Option[() => F[ListRootsResult]] = None, + samplingHandler: Option[CreateMessageRequest => F[CreateMessageResult]] = None, + elicitationHandler: Option[ElicitRequest => F[ElicitResult]] = None, protocolVersion: String = ProtocolVersion.Latest - )(using d: CapsDerive[F, Caps]): McpClient[F, Caps] = - given MonadError[F] = transport.monad - DefaultMcpClient.create[F, Caps](transport, clientInfo, protocolVersion, d.wire, d.handlers) + ): McpClient[F] = + DefaultMcpClient.create( + transport, + clientInfo, + protocolVersion, + rootsHandler, + samplingHandler, + elicitationHandler + ) diff --git a/client/src/main/scala/chimp/client/capabilities/CapsDerive.scala b/client/src/main/scala/chimp/client/capabilities/CapsDerive.scala deleted file mode 100644 index 261d860..0000000 --- a/client/src/main/scala/chimp/client/capabilities/CapsDerive.scala +++ /dev/null @@ -1,63 +0,0 @@ -package chimp.client.capabilities - -import chimp.client.internal.CapabilityHandlers -import chimp.protocol.{ClientCapabilities, ClientRootsCapability} -import io.circe.Json -import sttp.monad.MonadError - -/** Derives the wire-level [[ClientCapabilities]] and the runtime handler table for a `Caps` intersection type. - * - * `Caps = Any` produces empty capabilities; each capability typeclass (`Roots[F]`, `Sampling[F]`, `Elicitation[F]`) listed in - * `Caps` requires a matching `given` instance in scope. - */ -trait CapsDerive[F[_], Caps]: - def wire: ClientCapabilities - def handlers(using MonadError[F]): CapabilityHandlers[F] - -object CapsDerive: - - given empty[F[_]]: CapsDerive[F, Any] with - def wire = ClientCapabilities() - def handlers(using MonadError[F]) = CapabilityHandlers.empty[F] - - given roots[F[_]](using r: Roots[F]): CapsDerive[F, Roots[F]] with - def wire = ClientCapabilities(roots = Some(ClientRootsCapability(listChanged = Some(true)))) - def handlers(using MonadError[F]) = CapabilityHandlers.roots(r) - - given sampling[F[_]](using s: Sampling[F]): CapsDerive[F, Sampling[F]] with - def wire = ClientCapabilities(sampling = Some(Json.obj())) - def handlers(using MonadError[F]) = CapabilityHandlers.sampling(s) - - given elicitation[F[_]](using e: Elicitation[F]): CapsDerive[F, Elicitation[F]] with - def wire = ClientCapabilities(elicitation = Some(Json.obj())) - def handlers(using MonadError[F]) = CapabilityHandlers.elicitation(e) - - given rootsSampling[F[_]](using r: Roots[F], s: Sampling[F]): CapsDerive[F, Roots[F] & Sampling[F]] with - def wire = ClientCapabilities( - roots = Some(ClientRootsCapability(listChanged = Some(true))), - sampling = Some(Json.obj()) - ) - def handlers(using MonadError[F]) = CapabilityHandlers.roots(r) ++ CapabilityHandlers.sampling(s) - - given rootsElicitation[F[_]](using r: Roots[F], e: Elicitation[F]): CapsDerive[F, Roots[F] & Elicitation[F]] with - def wire = ClientCapabilities( - roots = Some(ClientRootsCapability(listChanged = Some(true))), - elicitation = Some(Json.obj()) - ) - def handlers(using MonadError[F]) = CapabilityHandlers.roots(r) ++ CapabilityHandlers.elicitation(e) - - given samplingElicitation[F[_]](using s: Sampling[F], e: Elicitation[F]): CapsDerive[F, Sampling[F] & Elicitation[F]] with - def wire = ClientCapabilities( - sampling = Some(Json.obj()), - elicitation = Some(Json.obj()) - ) - def handlers(using MonadError[F]) = CapabilityHandlers.sampling(s) ++ CapabilityHandlers.elicitation(e) - - given all[F[_]](using r: Roots[F], s: Sampling[F], e: Elicitation[F]): CapsDerive[F, Roots[F] & Sampling[F] & Elicitation[F]] with - def wire = ClientCapabilities( - roots = Some(ClientRootsCapability(listChanged = Some(true))), - sampling = Some(Json.obj()), - elicitation = Some(Json.obj()) - ) - def handlers(using MonadError[F]) = - CapabilityHandlers.roots(r) ++ CapabilityHandlers.sampling(s) ++ CapabilityHandlers.elicitation(e) diff --git a/client/src/main/scala/chimp/client/capabilities/Elicitation.scala b/client/src/main/scala/chimp/client/capabilities/Elicitation.scala deleted file mode 100644 index 38e37ae..0000000 --- a/client/src/main/scala/chimp/client/capabilities/Elicitation.scala +++ /dev/null @@ -1,7 +0,0 @@ -package chimp.client.capabilities - -import chimp.protocol.{ElicitRequest, ElicitResult} - -/** Host-side handler for `elicitation/create` requests from the server. Required when the client advertises the `elicitation` capability. */ -trait Elicitation[F[_]]: - def elicit(req: ElicitRequest): F[ElicitResult] diff --git a/client/src/main/scala/chimp/client/capabilities/Roots.scala b/client/src/main/scala/chimp/client/capabilities/Roots.scala deleted file mode 100644 index 0722ca1..0000000 --- a/client/src/main/scala/chimp/client/capabilities/Roots.scala +++ /dev/null @@ -1,7 +0,0 @@ -package chimp.client.capabilities - -import chimp.protocol.ListRootsResult - -/** Host-side handler for `roots/list` requests from the server. Required when the client advertises the `roots` capability. */ -trait Roots[F[_]]: - def list(): F[ListRootsResult] diff --git a/client/src/main/scala/chimp/client/capabilities/Sampling.scala b/client/src/main/scala/chimp/client/capabilities/Sampling.scala deleted file mode 100644 index 5d54ada..0000000 --- a/client/src/main/scala/chimp/client/capabilities/Sampling.scala +++ /dev/null @@ -1,7 +0,0 @@ -package chimp.client.capabilities - -import chimp.protocol.{CreateMessageRequest, CreateMessageResult} - -/** Host-side handler for `sampling/createMessage` requests from the server. Required when the client advertises the `sampling` capability. */ -trait Sampling[F[_]]: - def createMessage(req: CreateMessageRequest): F[CreateMessageResult] diff --git a/client/src/main/scala/chimp/client/internal/CapabilityHandlers.scala b/client/src/main/scala/chimp/client/internal/CapabilityHandlers.scala deleted file mode 100644 index dd7fc6b..0000000 --- a/client/src/main/scala/chimp/client/internal/CapabilityHandlers.scala +++ /dev/null @@ -1,32 +0,0 @@ -package chimp.client.internal - -import chimp.client.capabilities.{Elicitation, Roots, Sampling} -import chimp.protocol.{CreateMessageRequest, ElicitRequest} -import io.circe.syntax.* -import io.circe.Json -import sttp.monad.MonadError -import sttp.monad.syntax.* - -private[chimp] final case class CapabilityHandlers[F[_]](methods: Map[String, Json => F[Json]]): - def ++(other: CapabilityHandlers[F]): CapabilityHandlers[F] = - CapabilityHandlers(methods ++ other.methods) - -private[chimp] object CapabilityHandlers: - def empty[F[_]]: CapabilityHandlers[F] = CapabilityHandlers(Map.empty) - - def roots[F[_]](r: Roots[F])(using me: MonadError[F]): CapabilityHandlers[F] = - CapabilityHandlers(Map("roots/list" -> (_ => r.list().map(_.asJson)))) - - def sampling[F[_]](s: Sampling[F])(using me: MonadError[F]): CapabilityHandlers[F] = - CapabilityHandlers(Map("sampling/createMessage" -> { params => - params.as[CreateMessageRequest] match - case Right(req) => s.createMessage(req).map(_.asJson) - case Left(e) => me.error(IllegalArgumentException(s"Failed to decode CreateMessageRequest: ${e.getMessage}")) - })) - - def elicitation[F[_]](e: Elicitation[F])(using me: MonadError[F]): CapabilityHandlers[F] = - CapabilityHandlers(Map("elicitation/create" -> { params => - params.as[ElicitRequest] match - case Right(req) => e.elicit(req).map(_.asJson) - case Left(err) => me.error(IllegalArgumentException(s"Failed to decode ElicitRequest: ${err.getMessage}")) - })) diff --git a/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala b/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala index e03fa64..9622271 100644 --- a/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala +++ b/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala @@ -1,6 +1,5 @@ package chimp.client -import chimp.client.capabilities.{Elicitation, Roots} import chimp.client.notifications.{ServerNotification, ServerNotificationListener} import chimp.protocol.* import io.circe.syntax.* @@ -13,9 +12,12 @@ class CapabilityDispatchSpec extends AnyFlatSpec with Matchers: private val clientInfo = Implementation(name = "chimp-test", version = "0.0.1") it should "respond to a server-initiated roots/list with the registered handler's result" in: - given Roots[Identity] = () => ListRootsResult(roots = List(Root(uri = "file:///x", name = Some("x")))) val t = InMemoryTransport() - val _ = McpClient[Identity, Roots[Identity]](t, clientInfo) + val _ = McpClient[Identity]( + t, + clientInfo, + rootsHandler = Some(() => ListRootsResult(roots = List(Root(uri = "file:///x", name = Some("x"))))) + ) val req: JSONRPCMessage = JSONRPCMessage.Request(method = "roots/list", id = RequestId("server-1")) t.simulateIncoming(req) @@ -28,7 +30,7 @@ class CapabilityDispatchSpec extends AnyFlatSpec with Matchers: it should "respond with MethodNotFound for capabilities the client didn't opt into" in: val t = InMemoryTransport() - val _ = McpClient[Identity, Any](t, clientInfo) + val _ = McpClient[Identity](t, clientInfo) val req: JSONRPCMessage = JSONRPCMessage.Request(method = "sampling/createMessage", id = RequestId("server-2")) t.simulateIncoming(req) @@ -39,10 +41,10 @@ class CapabilityDispatchSpec extends AnyFlatSpec with Matchers: it should "deliver incoming notifications to registered listeners" in: val t = InMemoryTransport() - val client = McpClient[Identity, Any](t, clientInfo) + val client = McpClient[Identity](t, clientInfo) var received: Option[ServerNotification] = None val listener: ServerNotificationListener[Identity] = n => { received = Some(ServerNotification.parse(n)); () } - client.onServerNotification(listener) + val _ = client.onServerNotification(listener) val params = ProgressParams(progressToken = ProgressToken("p1"), progress = 0.42) val notif: JSONRPCMessage = JSONRPCMessage.Notification(method = "notifications/progress", params = Some(params.asJson)) @@ -51,8 +53,6 @@ class CapabilityDispatchSpec extends AnyFlatSpec with Matchers: received shouldBe Some(ServerNotification.Progress(params)) it should "include opted-in capabilities on initialize" in: - given Roots[Identity] = () => ListRootsResult(roots = Nil) - given Elicitation[Identity] = (_: ElicitRequest) => ElicitResult(action = ElicitAction.Cancel) val t = InMemoryTransport() val initResult = InitializeResult( protocolVersion = ProtocolVersion.Latest, @@ -60,7 +60,12 @@ class CapabilityDispatchSpec extends AnyFlatSpec with Matchers: serverInfo = Implementation(name = "s", version = "1") ) t.planResponse(JSONRPCMessage.Response(id = RequestId(1), result = initResult.asJson)) - val client = McpClient[Identity, Roots[Identity] & Elicitation[Identity]](t, clientInfo) + val client = McpClient[Identity]( + t, + clientInfo, + rootsHandler = Some(() => ListRootsResult(roots = Nil)), + elicitationHandler = Some((_: ElicitRequest) => ElicitResult(action = ElicitAction.Cancel)) + ) val _ = client.initialize() t.sent.head match diff --git a/client/src/test/scala/chimp/client/CapsDeriveSpec.scala b/client/src/test/scala/chimp/client/CapsDeriveSpec.scala deleted file mode 100644 index 22e3ecb..0000000 --- a/client/src/test/scala/chimp/client/CapsDeriveSpec.scala +++ /dev/null @@ -1,35 +0,0 @@ -package chimp.client - -import chimp.client.capabilities.{CapsDerive, Elicitation, Roots} -import chimp.protocol.{ClientCapabilities, ElicitRequest, ElicitResult, ListRootsResult} -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers -import sttp.monad.IdentityMonad -import sttp.shared.Identity - -class CapsDeriveSpec extends AnyFlatSpec with Matchers: - - given sttp.monad.MonadError[Identity] = IdentityMonad - - it should "produce empty ClientCapabilities for Caps = Any" in: - val d = summon[CapsDerive[Identity, Any]] - d.wire shouldBe ClientCapabilities() - d.handlers.methods shouldBe Map.empty - - it should "advertise roots when only Roots is provided" in: - given Roots[Identity] = () => ListRootsResult(roots = Nil) - val d = summon[CapsDerive[Identity, Roots[Identity]]] - d.wire.roots.isDefined shouldBe true - d.wire.sampling shouldBe None - d.wire.elicitation shouldBe None - d.handlers.methods.keySet shouldBe Set("roots/list") - - it should "advertise multiple capabilities for an intersection type" in: - given Roots[Identity] = () => ListRootsResult(roots = Nil) - given Elicitation[Identity] = (_: ElicitRequest) => - ElicitResult(action = chimp.protocol.ElicitAction.Cancel) - val d = summon[CapsDerive[Identity, Roots[Identity] & Elicitation[Identity]]] - d.wire.roots.isDefined shouldBe true - d.wire.elicitation.isDefined shouldBe true - d.wire.sampling shouldBe None - d.handlers.methods.keySet shouldBe Set("roots/list", "elicitation/create") diff --git a/client/src/test/scala/chimp/client/McpClientSpec.scala b/client/src/test/scala/chimp/client/McpClientSpec.scala index 675d5db..f22018c 100644 --- a/client/src/test/scala/chimp/client/McpClientSpec.scala +++ b/client/src/test/scala/chimp/client/McpClientSpec.scala @@ -24,7 +24,7 @@ class McpClientSpec extends AnyFlatSpec with Matchers: val backend = SyncBackendStub.whenAnyRequest.thenRespondAdjust(responseEnvelope) val t = HttpTransport[Identity](backend, mcpUri) - val client = McpClient[Identity, Any](t, clientInfo) + val client = McpClient[Identity](t, clientInfo) val result = client.initialize() result.protocolVersion shouldBe ProtocolVersion.Latest result.serverInfo.name shouldBe "test-server" @@ -36,7 +36,7 @@ class McpClientSpec extends AnyFlatSpec with Matchers: val backend = SyncBackendStub.whenAnyRequest.thenRespondAdjust(responseEnvelope) val t = HttpTransport[Identity](backend, mcpUri) - val client = McpClient[Identity, Any](t, clientInfo) + val client = McpClient[Identity](t, clientInfo) val r = client.callTool("echo", io.circe.Json.obj("message" -> io.circe.Json.fromString("hi"))) r.isError shouldBe false r.content.head shouldBe ToolContent.Text("text", "hi") From fa42cfb9c993956979468ef1a1c2ca2084901ed4 Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Wed, 13 May 2026 09:13:19 +0200 Subject: [PATCH 13/27] feat: separated client and server examples, first client example --- build.sbt | 2 +- examples/docker-compose.yml | 9 ++++ .../scala/chimp/client/everythingClient.scala | 46 +++++++++++++++++++ .../chimp/{ => server}/AdderMcpZio.scala | 5 +- .../scala/chimp/{ => server}/adderMcp.scala | 5 +- .../chimp/{ => server}/adderWithAuthMcp.scala | 5 +- .../chimp/{ => server}/twoToolsMcp.scala | 5 +- .../scala/chimp/{ => server}/weatherMcp.scala | 5 +- 8 files changed, 66 insertions(+), 16 deletions(-) create mode 100644 examples/docker-compose.yml create mode 100644 examples/src/main/scala/chimp/client/everythingClient.scala rename examples/src/main/scala/chimp/{ => server}/AdderMcpZio.scala (92%) rename examples/src/main/scala/chimp/{ => server}/adderMcp.scala (89%) rename examples/src/main/scala/chimp/{ => server}/adderWithAuthMcp.scala (92%) rename examples/src/main/scala/chimp/{ => server}/twoToolsMcp.scala (95%) rename examples/src/main/scala/chimp/{ => server}/weatherMcp.scala (97%) diff --git a/build.sbt b/build.sbt index 6aca25a..feb1496 100644 --- a/build.sbt +++ b/build.sbt @@ -85,7 +85,7 @@ lazy val examples = (project in file("examples")) ), verifyExamplesCompileUsingScalaCli := VerifyExamplesCompileUsingScalaCli(sLog.value, sourceDirectory.value) ) - .dependsOn(server) + .dependsOn(server, client) import sbtassembly.AssemblyPlugin.autoImport.* diff --git a/examples/docker-compose.yml b/examples/docker-compose.yml new file mode 100644 index 0000000..d62fd17 --- /dev/null +++ b/examples/docker-compose.yml @@ -0,0 +1,9 @@ +services: + mcp-everything: + image: node:lts-alpine + command: ["npx", "-y", "@modelcontextprotocol/server-everything", "streamableHttp"] + ports: + - "3001:3001" + environment: + PORT: "3001" + restart: unless-stopped diff --git a/examples/src/main/scala/chimp/client/everythingClient.scala b/examples/src/main/scala/chimp/client/everythingClient.scala new file mode 100644 index 0000000..de6c4d2 --- /dev/null +++ b/examples/src/main/scala/chimp/client/everythingClient.scala @@ -0,0 +1,46 @@ +//> using dep com.softwaremill.chimp::chimp-client:0.2.0 +//> using dep com.softwaremill.sttp.client4::core:4.0.23 +//> using dep ch.qos.logback:logback-classic:1.5.32 + +// Start the bundled mcp/everything server before running this example: +// cd examples && docker compose up -d + +package chimp.client + +import chimp.client.transport.HttpTransport +import chimp.protocol.* +import io.circe.Json +import sttp.client4.DefaultSyncBackend +import sttp.model.Uri.UriContext +import sttp.shared.Identity + +@main def everythingClient(): Unit = + val backend = DefaultSyncBackend() + val transport = HttpTransport[Identity](backend, uri"http://localhost:3001/mcp") + val client = McpClient[Identity]( + transport, + clientInfo = Implementation(name = "chimp-everything-client", version = "0.1.0") + ) + + try + val init = client.initialize() + println(s"Connected to ${init.serverInfo.name} ${init.serverInfo.version} (MCP ${init.protocolVersion})") + + val tools = client.listTools().tools + println(s"Available tools (${tools.size}):") + tools.foreach(t => println(s" - ${t.name}: ${t.description.getOrElse("")}")) + + println("\n--- calling echo ---") + val echoResult = client.callTool("echo", Json.obj("message" -> Json.fromString("hello chimp"))) + echoResult.content.foreach: + case ToolContent.Text(_, text) => println(text) + case other => println(s"(non-text content: $other)") + + println("\n--- calling get-sum ---") + val sumResult = client.callTool("get-sum", Json.obj("a" -> Json.fromInt(7), "b" -> Json.fromInt(35))) + sumResult.content.foreach: + case ToolContent.Text(_, text) => println(text) + case other => println(s"(non-text content: $other)") + finally + client.close() + backend.close() diff --git a/examples/src/main/scala/chimp/AdderMcpZio.scala b/examples/src/main/scala/chimp/server/AdderMcpZio.scala similarity index 92% rename from examples/src/main/scala/chimp/AdderMcpZio.scala rename to examples/src/main/scala/chimp/server/AdderMcpZio.scala index b5e7cb9..52a0086 100644 --- a/examples/src/main/scala/chimp/AdderMcpZio.scala +++ b/examples/src/main/scala/chimp/server/AdderMcpZio.scala @@ -1,10 +1,9 @@ -//> using dep com.softwaremill.chimp::core:0.1.7 +//> using dep com.softwaremill.chimp::chimp-server:0.2.0 //> using dep com.softwaremill.sttp.tapir::tapir-zio-http-server:1.11.50 //> using dep ch.qos.logback:logback-classic:1.5.20 -package chimp +package chimp.server -import chimp.server.* import io.circe.Codec import sttp.tapir.* import sttp.tapir.server.ziohttp.ZioHttpInterpreter diff --git a/examples/src/main/scala/chimp/adderMcp.scala b/examples/src/main/scala/chimp/server/adderMcp.scala similarity index 89% rename from examples/src/main/scala/chimp/adderMcp.scala rename to examples/src/main/scala/chimp/server/adderMcp.scala index 880a261..117642d 100644 --- a/examples/src/main/scala/chimp/adderMcp.scala +++ b/examples/src/main/scala/chimp/server/adderMcp.scala @@ -1,10 +1,9 @@ -//> using dep com.softwaremill.chimp::core:0.1.7 +//> using dep com.softwaremill.chimp::chimp-server:0.2.0 //> using dep com.softwaremill.sttp.tapir::tapir-netty-server-sync:1.11.50 //> using dep ch.qos.logback:logback-classic:1.5.20 -package chimp +package chimp.server -import chimp.server.* import io.circe.Codec import sttp.tapir.* import sttp.tapir.server.netty.sync.NettySyncServer diff --git a/examples/src/main/scala/chimp/adderWithAuthMcp.scala b/examples/src/main/scala/chimp/server/adderWithAuthMcp.scala similarity index 92% rename from examples/src/main/scala/chimp/adderWithAuthMcp.scala rename to examples/src/main/scala/chimp/server/adderWithAuthMcp.scala index 5f6b0fb..f548566 100644 --- a/examples/src/main/scala/chimp/adderWithAuthMcp.scala +++ b/examples/src/main/scala/chimp/server/adderWithAuthMcp.scala @@ -1,10 +1,9 @@ -//> using dep com.softwaremill.chimp::core:0.1.7 +//> using dep com.softwaremill.chimp::chimp-server:0.2.0 //> using dep com.softwaremill.sttp.tapir::tapir-netty-server-sync:1.11.50 //> using dep ch.qos.logback:logback-classic:1.5.20 -package chimp +package chimp.server -import chimp.server.* import io.circe.Codec import sttp.model.Header import sttp.tapir.* diff --git a/examples/src/main/scala/chimp/twoToolsMcp.scala b/examples/src/main/scala/chimp/server/twoToolsMcp.scala similarity index 95% rename from examples/src/main/scala/chimp/twoToolsMcp.scala rename to examples/src/main/scala/chimp/server/twoToolsMcp.scala index b066d10..03a2fca 100644 --- a/examples/src/main/scala/chimp/twoToolsMcp.scala +++ b/examples/src/main/scala/chimp/server/twoToolsMcp.scala @@ -1,10 +1,9 @@ -//> using dep com.softwaremill.chimp::core:0.1.7 +//> using dep com.softwaremill.chimp::chimp-server:0.2.0 //> using dep com.softwaremill.sttp.tapir::tapir-netty-server-sync:1.11.50 //> using dep ch.qos.logback:logback-classic:1.5.20 -package chimp +package chimp.server -import chimp.server.* import io.circe.Codec import sttp.tapir.* import sttp.tapir.server.netty.sync.NettySyncServer diff --git a/examples/src/main/scala/chimp/weatherMcp.scala b/examples/src/main/scala/chimp/server/weatherMcp.scala similarity index 97% rename from examples/src/main/scala/chimp/weatherMcp.scala rename to examples/src/main/scala/chimp/server/weatherMcp.scala index 27663e2..bbc0821 100644 --- a/examples/src/main/scala/chimp/weatherMcp.scala +++ b/examples/src/main/scala/chimp/server/weatherMcp.scala @@ -1,11 +1,10 @@ -//> using dep com.softwaremill.chimp::core:0.1.7 +//> using dep com.softwaremill.chimp::chimp-server:0.2.0 //> using dep com.softwaremill.sttp.client4::core:4.0.8 //> using dep com.softwaremill.sttp.tapir::tapir-netty-server-sync:1.11.50 //> using dep ch.qos.logback:logback-classic:1.5.20 -package chimp +package chimp.server -import chimp.server.* import io.circe.Codec import io.circe.parser.decode import ox.either From 98918cf6a7753c5903715257b119f8cee845eabf Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Wed, 13 May 2026 09:14:14 +0200 Subject: [PATCH 14/27] misc: rename root project --- build.sbt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.sbt b/build.sbt index feb1496..e135a57 100644 --- a/build.sbt +++ b/build.sbt @@ -26,7 +26,7 @@ lazy val commonSettings = commonSmlBuildSettings ++ ossPublishSettings ++ Seq( val scalaTest = "org.scalatest" %% "scalatest" % scalaTestV % Test -lazy val rootProject = (project in file(".")) +lazy val root = (project in file(".")) .settings(commonSettings: _*) .settings(publishArtifact := false, name := "chimp") .aggregate(core, server, client, examples, serverConformance, clientConformance) From 158da52308f3144013ae833761d7f88491230490 Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Wed, 13 May 2026 09:17:01 +0200 Subject: [PATCH 15/27] fix: formatting --- .../scala/chimp/client/DefaultMcpClient.scala | 59 +++-- .../main/scala/chimp/client/McpClient.scala | 6 +- .../notifications/ServerNotification.scala | 2 +- .../client/transport/HttpTransport.scala | 6 +- .../client/transport/StdioTransport.scala | 3 +- .../transport/StreamingHttpTransport.scala | 4 +- .../transport/StreamingStdioTransport.scala | 4 +- .../chimp/client/transport/Transport.scala | 8 +- .../chimp/client/CapabilityDispatchSpec.scala | 2 +- .../chimp/client/HttpTransportSpec.scala | 2 +- .../scala/chimp/protocol/Completion.scala | 10 +- .../main/scala/chimp/protocol/JsonRpc.scala | 32 +-- .../main/scala/chimp/protocol/Resources.scala | 28 +- .../src/main/scala/chimp/protocol/Tools.scala | 74 +++--- .../protocol/SchemaConformanceSpec.scala | 243 +++++++++++------- .../scala/chimp/server/McpHandlerSpec.scala | 1 - 16 files changed, 274 insertions(+), 210 deletions(-) diff --git a/client/src/main/scala/chimp/client/DefaultMcpClient.scala b/client/src/main/scala/chimp/client/DefaultMcpClient.scala index 0aa6758..1c388ef 100644 --- a/client/src/main/scala/chimp/client/DefaultMcpClient.scala +++ b/client/src/main/scala/chimp/client/DefaultMcpClient.scala @@ -37,21 +37,20 @@ object DefaultMcpClient: private val listeners = AtomicReference[List[ServerNotificationListener[F]]](Nil) private val wireCaps: ClientCapabilities = ClientCapabilities( - roots = rootsHandler.map(_ => ClientRootsCapability(listChanged = Some(true))), - sampling = samplingHandler.map(_ => Json.obj()), + roots = rootsHandler.map(_ => ClientRootsCapability(listChanged = Some(true))), + sampling = samplingHandler.map(_ => Json.obj()), elicitation = elicitationHandler.map(_ => Json.obj()) ) private val dispatch: Map[String, Json => F[Json]] = val entries = List( - rootsHandler.map(fn => - "roots/list" -> ((_: Json) => fn().map(_.asJson)) - ), + rootsHandler.map(fn => "roots/list" -> ((_: Json) => fn().map(_.asJson))), samplingHandler.map(fn => "sampling/createMessage" -> ((params: Json) => params.as[CreateMessageRequest] match case Right(req) => fn(req).map(_.asJson) - case Left(e) => summon[MonadError[F]].error(IllegalArgumentException(s"Failed to decode CreateMessageRequest: ${e.getMessage}")) + case Left(e) => + summon[MonadError[F]].error(IllegalArgumentException(s"Failed to decode CreateMessageRequest: ${e.getMessage}")) ) ), elicitationHandler.map(fn => @@ -72,14 +71,16 @@ object DefaultMcpClient: dispatch.get(method) match case Some(h) => val rawParams = params.getOrElse(Json.obj()) - h(rawParams).flatMap(result => - transport.send(JSONRPCMessage.Response(id = id, result = result)).map(_ => ()) - ).handleError { case t => - val err = JSONRPCMessage.Error( - id = id, - error = JSONRPCErrorObject(code = JSONRPCErrorCodes.InternalError.code, message = Option(t.getMessage).getOrElse("internal error")) - ) - transport.send(err).map(_ => ()) + h(rawParams).flatMap(result => transport.send(JSONRPCMessage.Response(id = id, result = result)).map(_ => ())).handleError { + case t => + val err = JSONRPCMessage.Error( + id = id, + error = JSONRPCErrorObject( + code = JSONRPCErrorCodes.InternalError.code, + message = Option(t.getMessage).getOrElse("internal error") + ) + ) + transport.send(err).map(_ => ()) } case None => val err = JSONRPCMessage.Error( @@ -88,8 +89,10 @@ object DefaultMcpClient: ) transport.send(err).map(_ => ()) case n: JSONRPCMessage.Notification => - listeners.get().foldLeft(summon[MonadError[F]].unit(())): (acc, l) => - acc.flatMap(_ => l.onNotification(n).handleError(_ => summon[MonadError[F]].unit(()))) + listeners + .get() + .foldLeft(summon[MonadError[F]].unit(())): (acc, l) => + acc.flatMap(_ => l.onNotification(n).handleError(_ => summon[MonadError[F]].unit(()))) case _ => summon[MonadError[F]].unit(()) @@ -164,17 +167,19 @@ object DefaultMcpClient: private def sendRequest[R: Decoder](method: String, params: Option[Json]): F[R] = val req = JSONRPCMessage.Request(method = method, params = params, id = correlator.nextId()) - transport.send(req).flatMap: - case Some(JSONRPCMessage.Response(_, _, result)) => - result.as[R] match - case Right(r) => summon[MonadError[F]].unit(r) - case Left(e) => summon[MonadError[F]].error(McpProtocolException(s"Failed to decode $method result: ${e.getMessage}")) - case Some(JSONRPCMessage.Error(_, _, error)) => - summon[MonadError[F]].error(McpProtocolException(s"$method failed: ${error.code} ${error.message}")) - case Some(other) => - summon[MonadError[F]].error(McpProtocolException(s"Unexpected response to $method: $other")) - case None => - summon[MonadError[F]].error(McpProtocolException(s"No response received for request $method")) + transport + .send(req) + .flatMap: + case Some(JSONRPCMessage.Response(_, _, result)) => + result.as[R] match + case Right(r) => summon[MonadError[F]].unit(r) + case Left(e) => summon[MonadError[F]].error(McpProtocolException(s"Failed to decode $method result: ${e.getMessage}")) + case Some(JSONRPCMessage.Error(_, _, error)) => + summon[MonadError[F]].error(McpProtocolException(s"$method failed: ${error.code} ${error.message}")) + case Some(other) => + summon[MonadError[F]].error(McpProtocolException(s"Unexpected response to $method: $other")) + case None => + summon[MonadError[F]].error(McpProtocolException(s"No response received for request $method")) private def sendNotification(method: String, params: Option[Json]): F[Unit] = val n = JSONRPCMessage.Notification(method = method, params = params) diff --git a/client/src/main/scala/chimp/client/McpClient.scala b/client/src/main/scala/chimp/client/McpClient.scala index f8447ac..c62b0e0 100644 --- a/client/src/main/scala/chimp/client/McpClient.scala +++ b/client/src/main/scala/chimp/client/McpClient.scala @@ -7,9 +7,9 @@ import io.circe.Json /** An MCP client. * - * Server-initiated requests (`roots/list`, `sampling/createMessage`, `elicitation/create`) are dispatched to the optional - * handler functions supplied at construction. Each handler that is `Some` causes the corresponding capability to be advertised - * on `initialize`; capabilities the host application doesn't opt into are answered with `MethodNotFound`. + * Server-initiated requests (`roots/list`, `sampling/createMessage`, `elicitation/create`) are dispatched to the optional handler + * functions supplied at construction. Each handler that is `Some` causes the corresponding capability to be advertised on `initialize`; + * capabilities the host application doesn't opt into are answered with `MethodNotFound`. */ trait McpClient[F[_]]: def initialize(): F[InitializeResult] diff --git a/client/src/main/scala/chimp/client/notifications/ServerNotification.scala b/client/src/main/scala/chimp/client/notifications/ServerNotification.scala index c2dac64..c6bab1e 100644 --- a/client/src/main/scala/chimp/client/notifications/ServerNotification.scala +++ b/client/src/main/scala/chimp/client/notifications/ServerNotification.scala @@ -27,6 +27,6 @@ object ServerNotification: case "notifications/tools/list_changed" => ToolsListChanged case "notifications/prompts/list_changed" => PromptsListChanged case "notifications/resources/list_changed" => ResourcesListChanged - case "notifications/message" => + case "notifications/message" => params.flatMap(_.as[LoggingMessageParams].toOption).map(LoggingMessage(_)).getOrElse(Unknown(n.method, params)) case other => Unknown(other, params) diff --git a/client/src/main/scala/chimp/client/transport/HttpTransport.scala b/client/src/main/scala/chimp/client/transport/HttpTransport.scala index 5bc78e6..95da87a 100644 --- a/client/src/main/scala/chimp/client/transport/HttpTransport.scala +++ b/client/src/main/scala/chimp/client/transport/HttpTransport.scala @@ -4,7 +4,7 @@ import chimp.client.{McpAuthorizationException, McpProtocolException, McpSession import chimp.protocol.{JSONRPCMessage, ProtocolVersion} import io.circe.parser import io.circe.syntax.* -import sttp.client4.{Backend, Response, basicRequest} +import sttp.client4.{basicRequest, Backend, Response} import sttp.model.{MediaType, StatusCode, Uri} import sttp.monad.MonadError import sttp.monad.syntax.* @@ -59,7 +59,7 @@ final class HttpTransport[F[_]]( else if bodyStr.isEmpty then None else Some(bodyStr) payload match - case None => monad.unit(None) + case None => monad.unit(None) case Some(json) => if HttpTransport.isAckLike(json) then monad.unit(None) else @@ -85,7 +85,7 @@ final class HttpTransport[F[_]]( override def close(): F[Unit] = sessionId.get() match - case None => monad.unit(()) + case None => monad.unit(()) case Some(id) => val req = basicRequest .delete(uri) diff --git a/client/src/main/scala/chimp/client/transport/StdioTransport.scala b/client/src/main/scala/chimp/client/transport/StdioTransport.scala index 5d75747..7581a59 100644 --- a/client/src/main/scala/chimp/client/transport/StdioTransport.scala +++ b/client/src/main/scala/chimp/client/transport/StdioTransport.scala @@ -119,7 +119,8 @@ final class StdioTransport( override def close(): Identity[Unit] = if closed.compareAndSet(false, true) then - try writer.close() catch case _: Exception => () + try writer.close() + catch case _: Exception => () if proc.isAlive then if !proc.waitFor(2, TimeUnit.SECONDS) then proc.destroy() if !proc.waitFor(2, TimeUnit.SECONDS) then { val _ = proc.destroyForcibly() } diff --git a/client/src/main/scala/chimp/client/transport/StreamingHttpTransport.scala b/client/src/main/scala/chimp/client/transport/StreamingHttpTransport.scala index 4eeffa3..13056ef 100644 --- a/client/src/main/scala/chimp/client/transport/StreamingHttpTransport.scala +++ b/client/src/main/scala/chimp/client/transport/StreamingHttpTransport.scala @@ -6,8 +6,8 @@ import sttp.model.Uri /** Abstract Streamable HTTP transport using a Streams-capable sttp backend. * - * Concrete implementations live in per-effect chimp client subprojects (`client-zio`, `client-fs2`) and provide SSE parsing, - * resumability via `Last-Event-ID`, and bidirectional server-initiated dispatch over a long-lived GET. + * Concrete implementations live in per-effect chimp client subprojects (`client-zio`, `client-fs2`) and provide SSE parsing, resumability + * via `Last-Event-ID`, and bidirectional server-initiated dispatch over a long-lived GET. */ abstract class StreamingHttpTransport[F[_], S]( protected val backend: StreamBackend[F, S], diff --git a/client/src/main/scala/chimp/client/transport/StreamingStdioTransport.scala b/client/src/main/scala/chimp/client/transport/StreamingStdioTransport.scala index 7b0b39b..5d28a3c 100644 --- a/client/src/main/scala/chimp/client/transport/StreamingStdioTransport.scala +++ b/client/src/main/scala/chimp/client/transport/StreamingStdioTransport.scala @@ -6,8 +6,8 @@ import java.io.File /** Abstract async stdio transport using a Streams-capable effect. * - * Concrete implementations live in per-effect chimp client subprojects (`client-zio`, `client-fs2`) and replace blocking - * `readLine` reads with non-blocking stream consumption tied to the effect's runtime. + * Concrete implementations live in per-effect chimp client subprojects (`client-zio`, `client-fs2`) and replace blocking `readLine` reads + * with non-blocking stream consumption tied to the effect's runtime. */ abstract class StreamingStdioTransport[F[_], S]( protected val command: List[String], diff --git a/client/src/main/scala/chimp/client/transport/Transport.scala b/client/src/main/scala/chimp/client/transport/Transport.scala index 1147bb0..ecd9876 100644 --- a/client/src/main/scala/chimp/client/transport/Transport.scala +++ b/client/src/main/scala/chimp/client/transport/Transport.scala @@ -5,10 +5,10 @@ import sttp.monad.MonadError /** A bidirectional transport carrying JSON-RPC messages for an MCP client. * - * - `send(req)` for a `Request` returns the matching `Response` or `Error` from the peer. - * - `send(notif)` for a `Notification` returns `None` once the message has been delivered. - * - `onIncoming(handler)` registers a callback for server-initiated requests and notifications. - * HTTP non-streaming transports never invoke it; stdio and streaming transports do. + * - `send(req)` for a `Request` returns the matching `Response` or `Error` from the peer. + * - `send(notif)` for a `Notification` returns `None` once the message has been delivered. + * - `onIncoming(handler)` registers a callback for server-initiated requests and notifications. HTTP non-streaming transports never + * invoke it; stdio and streaming transports do. */ trait Transport[F[_]]: given monad: MonadError[F] diff --git a/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala b/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala index 9622271..e2042e7 100644 --- a/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala +++ b/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala @@ -37,7 +37,7 @@ class CapabilityDispatchSpec extends AnyFlatSpec with Matchers: t.sent.last match case JSONRPCMessage.Error(_, _, err) => err.code shouldBe JSONRPCErrorCodes.MethodNotFound.code - case other => fail(s"Expected Error, got $other") + case other => fail(s"Expected Error, got $other") it should "deliver incoming notifications to registered listeners" in: val t = InMemoryTransport() diff --git a/client/src/test/scala/chimp/client/HttpTransportSpec.scala b/client/src/test/scala/chimp/client/HttpTransportSpec.scala index 1e7c55b..65e1a3c 100644 --- a/client/src/test/scala/chimp/client/HttpTransportSpec.scala +++ b/client/src/test/scala/chimp/client/HttpTransportSpec.scala @@ -27,7 +27,7 @@ class HttpTransportSpec extends AnyFlatSpec with Matchers: val req: JSONRPCMessage = JSONRPCMessage.Request(method = "x", params = None, id = RequestId(1)) t.send(req) match case Some(JSONRPCMessage.Response(_, _, r)) => r shouldBe expectedResult - case other => fail(s"Expected Response, got: $other") + case other => fail(s"Expected Response, got: $other") it should "return None for 202 Accepted (notification ack)" in: val backend = SyncBackendStub.whenAnyRequest.thenRespondAdjust("", StatusCode.Accepted) diff --git a/core/src/main/scala/chimp/protocol/Completion.scala b/core/src/main/scala/chimp/protocol/Completion.scala index 3b8c097..e107b7e 100644 --- a/core/src/main/scala/chimp/protocol/Completion.scala +++ b/core/src/main/scala/chimp/protocol/Completion.scala @@ -12,10 +12,12 @@ object CompleteRef: case Prompt(p) => p.asJson case Resource(r) => r.asJson given Decoder[CompleteRef] = Decoder.instance: c => - c.downField("type").as[String].flatMap: - case "ref/prompt" => c.as[PromptReference].map(Prompt(_)) - case "ref/resource" => c.as[ResourceReference].map(Resource(_)) - case other => Left(DecodingFailure(s"Unknown CompleteRef type: $other", c.history)) + c.downField("type") + .as[String] + .flatMap: + case "ref/prompt" => c.as[PromptReference].map(Prompt(_)) + case "ref/resource" => c.as[ResourceReference].map(Resource(_)) + case other => Left(DecodingFailure(s"Unknown CompleteRef type: $other", c.history)) final case class CompleteArgument(name: String, value: String) derives Codec diff --git a/core/src/main/scala/chimp/protocol/JsonRpc.scala b/core/src/main/scala/chimp/protocol/JsonRpc.scala index 616bf87..598e26e 100644 --- a/core/src/main/scala/chimp/protocol/JsonRpc.scala +++ b/core/src/main/scala/chimp/protocol/JsonRpc.scala @@ -12,56 +12,56 @@ enum JSONRPCMessage: object JSONRPCMessage: given Decoder[JSONRPCMessage] = Decoder.instance: c => - val jsonrpc = c.downField("jsonrpc").as[String].getOrElse("2.0") + val jsonrpc = c.downField("jsonrpc").as[String].getOrElse("2.0") val methodOpt = c.downField("method").as[String].toOption - val idOpt = c.downField("id").as[RequestId].toOption + val idOpt = c.downField("id").as[RequestId].toOption val paramsOpt = c.downField("params").focus val resultOpt = c.downField("result").focus - val errorOpt = c.downField("error").as[JSONRPCErrorObject].toOption + val errorOpt = c.downField("error").as[JSONRPCErrorObject].toOption (methodOpt, idOpt, resultOpt, errorOpt) match case (Some(method), Some(id), None, None) => Right(Request(jsonrpc, method, paramsOpt, id)) case (Some(method), None, None, None) => Right(Notification(jsonrpc, method, paramsOpt)) case (None, Some(id), Some(result), None) => Right(Response(jsonrpc, id, result)) case (None, Some(id), None, Some(error)) => Right(Error(jsonrpc, id, error)) - case _ => Left(DecodingFailure("type JSONRPCMessage could not be decoded from JSON", c.history)) + case _ => Left(DecodingFailure("type JSONRPCMessage could not be decoded from JSON", c.history)) given Encoder[JSONRPCMessage] = Encoder.instance: case Request(jsonrpc, method, params, id) => Json .obj( "jsonrpc" -> Json.fromString(jsonrpc), - "method" -> Json.fromString(method), - "params" -> params.getOrElse(Json.Null), - "id" -> id.asJson + "method" -> Json.fromString(method), + "params" -> params.getOrElse(Json.Null), + "id" -> id.asJson ) .dropNullValues case Notification(jsonrpc, method, params) => Json .obj( "jsonrpc" -> Json.fromString(jsonrpc), - "method" -> Json.fromString(method), - "params" -> params.getOrElse(Json.Null) + "method" -> Json.fromString(method), + "params" -> params.getOrElse(Json.Null) ) .dropNullValues case Response(jsonrpc, id, result) => Json.obj( "jsonrpc" -> Json.fromString(jsonrpc), - "id" -> id.asJson, - "result" -> result + "id" -> id.asJson, + "result" -> result ) case Error(jsonrpc, id, error) => Json.obj( "jsonrpc" -> Json.fromString(jsonrpc), - "id" -> id.asJson, - "error" -> error.asJson + "id" -> id.asJson, + "error" -> error.asJson ) final case class JSONRPCErrorObject(code: Int, message: String, data: Option[Json] = None) derives Codec enum JSONRPCErrorCodes(val code: Int): - case ParseError extends JSONRPCErrorCodes(-32700) + case ParseError extends JSONRPCErrorCodes(-32700) case InvalidRequest extends JSONRPCErrorCodes(-32600) case MethodNotFound extends JSONRPCErrorCodes(-32601) - case InvalidParams extends JSONRPCErrorCodes(-32602) - case InternalError extends JSONRPCErrorCodes(-32603) + case InvalidParams extends JSONRPCErrorCodes(-32602) + case InternalError extends JSONRPCErrorCodes(-32603) diff --git a/core/src/main/scala/chimp/protocol/Resources.scala b/core/src/main/scala/chimp/protocol/Resources.scala index 7b45b61..59901de 100644 --- a/core/src/main/scala/chimp/protocol/Resources.scala +++ b/core/src/main/scala/chimp/protocol/Resources.scala @@ -31,34 +31,34 @@ object ResourceContents: case Text(uri, text, mimeType, meta) => Json .obj( - "uri" -> Json.fromString(uri), - "text" -> Json.fromString(text), + "uri" -> Json.fromString(uri), + "text" -> Json.fromString(text), "mimeType" -> mimeType.map(Json.fromString).getOrElse(Json.Null), - "_meta" -> meta.map(_.asJson).getOrElse(Json.Null) + "_meta" -> meta.map(_.asJson).getOrElse(Json.Null) ) .dropNullValues case Blob(uri, blob, mimeType, meta) => Json .obj( - "uri" -> Json.fromString(uri), - "blob" -> Json.fromString(blob), + "uri" -> Json.fromString(uri), + "blob" -> Json.fromString(blob), "mimeType" -> mimeType.map(Json.fromString).getOrElse(Json.Null), - "_meta" -> meta.map(_.asJson).getOrElse(Json.Null) + "_meta" -> meta.map(_.asJson).getOrElse(Json.Null) ) .dropNullValues given Decoder[ResourceContents] = Decoder.instance: (c: HCursor) => - val uri = c.downField("uri").as[String] + val uri = c.downField("uri").as[String] val mimeType = c.downField("mimeType").as[Option[String]] - val meta = c.downField("_meta").as[Option[Map[String, Json]]] - val textOpt = c.downField("text").as[Option[String]] - val blobOpt = c.downField("blob").as[Option[String]] + val meta = c.downField("_meta").as[Option[Map[String, Json]]] + val textOpt = c.downField("text").as[Option[String]] + val blobOpt = c.downField("blob").as[Option[String]] for - u <- uri + u <- uri mt <- mimeType - m <- meta - t <- textOpt - b <- blobOpt + m <- meta + t <- textOpt + b <- blobOpt r <- (t, b) match case (Some(text), None) => Right(Text(u, text, mt, m)) case (None, Some(blob)) => Right(Blob(u, blob, mt, m)) diff --git a/core/src/main/scala/chimp/protocol/Tools.scala b/core/src/main/scala/chimp/protocol/Tools.scala index 9c7acbc..4934942 100644 --- a/core/src/main/scala/chimp/protocol/Tools.scala +++ b/core/src/main/scala/chimp/protocol/Tools.scala @@ -53,57 +53,59 @@ object ToolContent: ) case Image(_, data, mimeType) => Json.obj( - "type" -> Json.fromString("image"), - "data" -> Json.fromString(data), + "type" -> Json.fromString("image"), + "data" -> Json.fromString(data), "mimeType" -> Json.fromString(mimeType) ) case Audio(_, data, mimeType) => Json.obj( - "type" -> Json.fromString("audio"), - "data" -> Json.fromString(data), + "type" -> Json.fromString("audio"), + "data" -> Json.fromString(data), "mimeType" -> Json.fromString(mimeType) ) case ResourceContent(_, resource) => Json.obj( - "type" -> Json.fromString("resource"), + "type" -> Json.fromString("resource"), "resource" -> resource.asJson ) case ResourceLink(_, uri, name, description, mimeType) => Json .obj( - "type" -> Json.fromString("resource_link"), - "uri" -> Json.fromString(uri), - "name" -> name.map(Json.fromString).getOrElse(Json.Null), + "type" -> Json.fromString("resource_link"), + "uri" -> Json.fromString(uri), + "name" -> name.map(Json.fromString).getOrElse(Json.Null), "description" -> description.map(Json.fromString).getOrElse(Json.Null), - "mimeType" -> mimeType.map(Json.fromString).getOrElse(Json.Null) + "mimeType" -> mimeType.map(Json.fromString).getOrElse(Json.Null) ) .dropNullValues given Decoder[ToolContent] = Decoder.instance: (c: HCursor) => - c.downField("type").as[String].flatMap: - case "text" => - c.downField("text").as[String].map(Text("text", _)) - case "image" => - for - data <- c.downField("data").as[String] - mimeType <- c.downField("mimeType").as[String] - yield Image("image", data, mimeType) - case "audio" => - for - data <- c.downField("data").as[String] - mimeType <- c.downField("mimeType").as[String] - yield Audio("audio", data, mimeType) - case "resource" => - c.downField("resource").as[ResourceContents].map(ResourceContent("resource", _)) - case "resource_link" => - for - uri <- c.downField("uri").as[String] - name <- c.downField("name").as[Option[String]] - description <- c.downField("description").as[Option[String]] - mimeType <- c.downField("mimeType").as[Option[String]] - yield ResourceLink("resource_link", uri, name, description, mimeType) - case other => - Left(DecodingFailure(s"Unknown ToolContent type: $other", c.history)) + c.downField("type") + .as[String] + .flatMap: + case "text" => + c.downField("text").as[String].map(Text("text", _)) + case "image" => + for + data <- c.downField("data").as[String] + mimeType <- c.downField("mimeType").as[String] + yield Image("image", data, mimeType) + case "audio" => + for + data <- c.downField("data").as[String] + mimeType <- c.downField("mimeType").as[String] + yield Audio("audio", data, mimeType) + case "resource" => + c.downField("resource").as[ResourceContents].map(ResourceContent("resource", _)) + case "resource_link" => + for + uri <- c.downField("uri").as[String] + name <- c.downField("name").as[Option[String]] + description <- c.downField("description").as[Option[String]] + mimeType <- c.downField("mimeType").as[Option[String]] + yield ResourceLink("resource_link", uri, name, description, mimeType) + case other => + Left(DecodingFailure(s"Unknown ToolContent type: $other", c.history)) final case class CallToolParams( name: String, @@ -124,10 +126,10 @@ object CallToolResult: given Encoder[CallToolResult] = Encoder.AsObject.derived[CallToolResult] given Decoder[CallToolResult] = Decoder.instance: c => for - content <- c.downField("content").as[List[ToolContent]] + content <- c.downField("content").as[List[ToolContent]] structuredContent <- c.downField("structuredContent").as[Option[Json]] - isError <- c.downField("isError").as[Option[Boolean]] - meta <- c.downField("_meta").as[Option[Map[String, Json]]] + isError <- c.downField("isError").as[Option[Boolean]] + meta <- c.downField("_meta").as[Option[Map[String, Json]]] yield CallToolResult(content, structuredContent, isError.getOrElse(false), meta) final case class ToolListChangedNotification(method: String = "notifications/tools/list_changed") derives Codec diff --git a/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala b/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala index c781d15..3641453 100644 --- a/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala +++ b/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala @@ -20,10 +20,14 @@ class SchemaConformanceSpec extends AnyFlatSpec with Matchers: text private val defsText: String = - val rootJson = io.circe.parser.parse(rootSchemaText).getOrElse( - throw RuntimeException("Could not parse the bundled MCP schema as JSON") - ) - rootJson.hcursor.downField("$defs").focus + val rootJson = io.circe.parser + .parse(rootSchemaText) + .getOrElse( + throw RuntimeException("Could not parse the bundled MCP schema as JSON") + ) + rootJson.hcursor + .downField("$defs") + .focus .getOrElse(throw RuntimeException("Schema root is missing $defs object")) .noSpaces @@ -46,55 +50,73 @@ class SchemaConformanceSpec extends AnyFlatSpec with Matchers: // --- Lifecycle --- it should "produce InitializeRequestParams that match the spec schema" in: - validate("InitializeRequestParams", InitializeParams( - protocolVersion = ProtocolVersion.Latest, - capabilities = ClientCapabilities(), - clientInfo = Implementation(name = "chimp-test", version = "0.0.1") - )) + validate( + "InitializeRequestParams", + InitializeParams( + protocolVersion = ProtocolVersion.Latest, + capabilities = ClientCapabilities(), + clientInfo = Implementation(name = "chimp-test", version = "0.0.1") + ) + ) it should "produce InitializeResult that match the spec schema" in: - validate("InitializeResult", InitializeResult( - protocolVersion = ProtocolVersion.Latest, - capabilities = ServerCapabilities(tools = Some(ServerToolsCapability(listChanged = Some(false)))), - serverInfo = Implementation(name = "chimp-test", version = "0.0.1"), - instructions = Some("welcome") - )) + validate( + "InitializeResult", + InitializeResult( + protocolVersion = ProtocolVersion.Latest, + capabilities = ServerCapabilities(tools = Some(ServerToolsCapability(listChanged = Some(false)))), + serverInfo = Implementation(name = "chimp-test", version = "0.0.1"), + instructions = Some("welcome") + ) + ) it should "produce Implementation that match the spec schema" in: validate("Implementation", Implementation(name = "chimp", version = "1.0", title = Some("Chimp"))) it should "produce ClientCapabilities (full) that match the spec schema" in: - validate("ClientCapabilities", ClientCapabilities( - roots = Some(ClientRootsCapability(listChanged = Some(true))), - sampling = Some(io.circe.Json.obj()), - elicitation = Some(io.circe.Json.obj()) - )) + validate( + "ClientCapabilities", + ClientCapabilities( + roots = Some(ClientRootsCapability(listChanged = Some(true))), + sampling = Some(io.circe.Json.obj()), + elicitation = Some(io.circe.Json.obj()) + ) + ) it should "produce ServerCapabilities (full) that match the spec schema" in: - validate("ServerCapabilities", ServerCapabilities( - tools = Some(ServerToolsCapability(listChanged = Some(true))), - resources = Some(ServerResourcesCapability(subscribe = Some(true), listChanged = Some(false))), - prompts = Some(ServerPromptsCapability(listChanged = Some(true))), - logging = Some(io.circe.Json.obj()), - completions = Some(io.circe.Json.obj()) - )) + validate( + "ServerCapabilities", + ServerCapabilities( + tools = Some(ServerToolsCapability(listChanged = Some(true))), + resources = Some(ServerResourcesCapability(subscribe = Some(true), listChanged = Some(false))), + prompts = Some(ServerPromptsCapability(listChanged = Some(true))), + logging = Some(io.circe.Json.obj()), + completions = Some(io.circe.Json.obj()) + ) + ) // --- Tools --- it should "produce a Tool definition that matches the spec schema" in: - validate("Tool", ToolDefinition( - name = "add_numbers", - title = Some("Add numbers"), - description = Some("Adds two numbers"), - inputSchema = io.circe.Json.obj("type" -> "object".asJson), - annotations = Some(ToolAnnotations(title = Some("Add"), idempotentHint = Some(true))) - )) + validate( + "Tool", + ToolDefinition( + name = "add_numbers", + title = Some("Add numbers"), + description = Some("Adds two numbers"), + inputSchema = io.circe.Json.obj("type" -> "object".asJson), + annotations = Some(ToolAnnotations(title = Some("Add"), idempotentHint = Some(true))) + ) + ) it should "produce CallToolRequestParams that match the spec schema" in: - validate("CallToolRequestParams", CallToolParams( - name = "add_numbers", - arguments = io.circe.Json.obj("a" -> 1.asJson, "b" -> 2.asJson) - )) + validate( + "CallToolRequestParams", + CallToolParams( + name = "add_numbers", + arguments = io.circe.Json.obj("a" -> 1.asJson, "b" -> 2.asJson) + ) + ) it should "produce CallToolResult (text) that match the spec schema" in: validate("CallToolResult", CallToolResult(content = List(ToolContent.Text(text = "hello")))) @@ -123,12 +145,15 @@ class SchemaConformanceSpec extends AnyFlatSpec with Matchers: // --- Resources --- it should "produce Resource that match the spec schema" in: - validate("Resource", Resource( - uri = "file:///x", - name = "x", - title = Some("X"), - mimeType = Some("text/plain") - )) + validate( + "Resource", + Resource( + uri = "file:///x", + name = "x", + title = Some("X"), + mimeType = Some("text/plain") + ) + ) it should "produce TextResourceContents that match the spec schema" in: validate("TextResourceContents", ResourceContents.Text(uri = "file:///x", text = "body", mimeType = Some("text/plain"))) @@ -166,12 +191,15 @@ class SchemaConformanceSpec extends AnyFlatSpec with Matchers: // --- Prompts --- it should "produce Prompt that match the spec schema" in: - validate("Prompt", Prompt( - name = "greet", - title = Some("Greet"), - description = Some("Greet the user"), - arguments = Some(List(PromptArgument(name = "who", required = Some(true)))) - )) + validate( + "Prompt", + Prompt( + name = "greet", + title = Some("Greet"), + description = Some("Greet the user"), + arguments = Some(List(PromptArgument(name = "who", required = Some(true)))) + ) + ) it should "produce PromptMessage that match the spec schema" in: validate("PromptMessage", PromptMessage(role = Role.User, content = ToolContent.Text(text = "hi"))) @@ -191,39 +219,51 @@ class SchemaConformanceSpec extends AnyFlatSpec with Matchers: // --- Sampling --- it should "produce CreateMessageRequestParams that match the spec schema" in: - validate("CreateMessageRequestParams", CreateMessageParams( - messages = List(SamplingMessage(role = Role.User, content = ToolContent.Text(text = "say hi"))), - maxTokens = 100, - systemPrompt = Some("you are helpful"), - includeContext = Some(IncludeContext.None), - temperature = Some(0.5), - stopSequences = Some(List("\n\n")) - )) + validate( + "CreateMessageRequestParams", + CreateMessageParams( + messages = List(SamplingMessage(role = Role.User, content = ToolContent.Text(text = "say hi"))), + maxTokens = 100, + systemPrompt = Some("you are helpful"), + includeContext = Some(IncludeContext.None), + temperature = Some(0.5), + stopSequences = Some(List("\n\n")) + ) + ) it should "produce CreateMessageResult that match the spec schema" in: - validate("CreateMessageResult", CreateMessageResult( - role = Role.Assistant, - content = ToolContent.Text(text = "hi"), - model = "claude-test", - stopReason = Some("endTurn") - )) + validate( + "CreateMessageResult", + CreateMessageResult( + role = Role.Assistant, + content = ToolContent.Text(text = "hi"), + model = "claude-test", + stopReason = Some("endTurn") + ) + ) // --- Elicitation --- it should "produce ElicitRequestParams (form variant) that match the spec schema" in: - validate("ElicitRequestParams", ElicitParams( - message = "what is your name?", - requestedSchema = io.circe.Json.obj( - "type" -> "object".asJson, - "properties" -> io.circe.Json.obj("name" -> io.circe.Json.obj("type" -> "string".asJson)) + validate( + "ElicitRequestParams", + ElicitParams( + message = "what is your name?", + requestedSchema = io.circe.Json.obj( + "type" -> "object".asJson, + "properties" -> io.circe.Json.obj("name" -> io.circe.Json.obj("type" -> "string".asJson)) + ) ) - )) + ) it should "produce ElicitResult that match the spec schema" in: - validate("ElicitResult", ElicitResult( - action = ElicitAction.Accept, - content = Some(Map("name" -> "Alice".asJson)) - )) + validate( + "ElicitResult", + ElicitResult( + action = ElicitAction.Accept, + content = Some(Map("name" -> "Alice".asJson)) + ) + ) // --- Roots --- @@ -236,19 +276,28 @@ class SchemaConformanceSpec extends AnyFlatSpec with Matchers: // --- Completion --- it should "produce CompleteRequestParams (prompt ref) that match the spec schema" in: - validate("CompleteRequestParams", CompleteParams( - ref = CompleteRef.Prompt(PromptReference(name = "greet")), - argument = CompleteArgument(name = "who", value = "al") - )) + validate( + "CompleteRequestParams", + CompleteParams( + ref = CompleteRef.Prompt(PromptReference(name = "greet")), + argument = CompleteArgument(name = "who", value = "al") + ) + ) it should "produce CompleteRequestParams (resource template ref) that match the spec schema" in: - validate("CompleteRequestParams", CompleteParams( - ref = CompleteRef.Resource(ResourceReference(uri = "file:///{path}")), - argument = CompleteArgument(name = "path", value = "src/") - )) + validate( + "CompleteRequestParams", + CompleteParams( + ref = CompleteRef.Resource(ResourceReference(uri = "file:///{path}")), + argument = CompleteArgument(name = "path", value = "src/") + ) + ) it should "produce CompleteResult that match the spec schema" in: - validate("CompleteResult", CompleteResult(completion = Completion(values = List("Alice", "Alex"), total = Some(2), hasMore = Some(false)))) + validate( + "CompleteResult", + CompleteResult(completion = Completion(values = List("Alice", "Alex"), total = Some(2), hasMore = Some(false))) + ) // --- Logging --- @@ -256,21 +305,27 @@ class SchemaConformanceSpec extends AnyFlatSpec with Matchers: validate("SetLevelRequestParams", SetLevelParams(level = LoggingLevel.Info)) it should "produce LoggingMessageNotificationParams that match the spec schema" in: - validate("LoggingMessageNotificationParams", LoggingMessageParams( - level = LoggingLevel.Warning, - data = io.circe.Json.fromString("something happened"), - logger = Some("chimp") - )) + validate( + "LoggingMessageNotificationParams", + LoggingMessageParams( + level = LoggingLevel.Warning, + data = io.circe.Json.fromString("something happened"), + logger = Some("chimp") + ) + ) // --- Progress / Cancellation --- it should "produce ProgressNotificationParams that match the spec schema" in: - validate("ProgressNotificationParams", ProgressParams( - progressToken = ProgressToken("t1"), - progress = 0.5, - total = Some(1.0), - message = Some("halfway") - )) + validate( + "ProgressNotificationParams", + ProgressParams( + progressToken = ProgressToken("t1"), + progress = 0.5, + total = Some(1.0), + message = Some("halfway") + ) + ) it should "produce CancelledNotificationParams that match the spec schema" in: validate("CancelledNotificationParams", CancelledParams(requestId = RequestId("r1"), reason = Some("user cancelled"))) diff --git a/server/src/test/scala/chimp/server/McpHandlerSpec.scala b/server/src/test/scala/chimp/server/McpHandlerSpec.scala index ec2b8c0..330b652 100644 --- a/server/src/test/scala/chimp/server/McpHandlerSpec.scala +++ b/server/src/test/scala/chimp/server/McpHandlerSpec.scala @@ -375,4 +375,3 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: requiredFields should contain("requiredField") requiredFields should not contain "optionalField" case _ => fail("Expected Response") - From 8c12b2fda8c770b2668166ed40a0b85f1154713b Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Wed, 13 May 2026 11:40:13 +0200 Subject: [PATCH 16/27] refactor: remove comments --- .../main/scala/chimp/client/McpClient.scala | 6 ----- ...eptions.scala => McpClientException.scala} | 0 .../notifications/ServerNotification.scala | 1 - .../client/transport/HttpTransport.scala | 27 ++++++++++--------- .../client/transport/StdioTransport.scala | 4 --- .../transport/StreamingHttpTransport.scala | 5 ---- .../transport/StreamingStdioTransport.scala | 5 ---- .../chimp/client/transport/Transport.scala | 7 ----- 8 files changed, 14 insertions(+), 41 deletions(-) rename client/src/main/scala/chimp/client/{McpExceptions.scala => McpClientException.scala} (100%) diff --git a/client/src/main/scala/chimp/client/McpClient.scala b/client/src/main/scala/chimp/client/McpClient.scala index c62b0e0..db7cd76 100644 --- a/client/src/main/scala/chimp/client/McpClient.scala +++ b/client/src/main/scala/chimp/client/McpClient.scala @@ -5,12 +5,6 @@ import chimp.client.transport.Transport import chimp.protocol.* import io.circe.Json -/** An MCP client. - * - * Server-initiated requests (`roots/list`, `sampling/createMessage`, `elicitation/create`) are dispatched to the optional handler - * functions supplied at construction. Each handler that is `Some` causes the corresponding capability to be advertised on `initialize`; - * capabilities the host application doesn't opt into are answered with `MethodNotFound`. - */ trait McpClient[F[_]]: def initialize(): F[InitializeResult] def ping(): F[Unit] diff --git a/client/src/main/scala/chimp/client/McpExceptions.scala b/client/src/main/scala/chimp/client/McpClientException.scala similarity index 100% rename from client/src/main/scala/chimp/client/McpExceptions.scala rename to client/src/main/scala/chimp/client/McpClientException.scala diff --git a/client/src/main/scala/chimp/client/notifications/ServerNotification.scala b/client/src/main/scala/chimp/client/notifications/ServerNotification.scala index c6bab1e..4ff4e07 100644 --- a/client/src/main/scala/chimp/client/notifications/ServerNotification.scala +++ b/client/src/main/scala/chimp/client/notifications/ServerNotification.scala @@ -3,7 +3,6 @@ package chimp.client.notifications import chimp.protocol.* import io.circe.Json -/** A parsed, strongly-typed view of an incoming server-to-client notification. */ enum ServerNotification: case Progress(params: ProgressParams) case Cancelled(params: CancelledParams) diff --git a/client/src/main/scala/chimp/client/transport/HttpTransport.scala b/client/src/main/scala/chimp/client/transport/HttpTransport.scala index 95da87a..86fd98a 100644 --- a/client/src/main/scala/chimp/client/transport/HttpTransport.scala +++ b/client/src/main/scala/chimp/client/transport/HttpTransport.scala @@ -5,6 +5,7 @@ import chimp.protocol.{JSONRPCMessage, ProtocolVersion} import io.circe.parser import io.circe.syntax.* import sttp.client4.{basicRequest, Backend, Response} +import sttp.model.sse.ServerSentEvent import sttp.model.{MediaType, StatusCode, Uri} import sttp.monad.MonadError import sttp.monad.syntax.* @@ -12,19 +13,6 @@ import sttp.monad.syntax.* import java.util.concurrent.atomic.AtomicReference /** Non-streaming Streamable HTTP transport. Works against any sttp `Backend[F]`. */ -object HttpTransport: - private[transport] def extractSingleSseData(body: String): Option[String] = - val blocks: List[String] = body.split("\\r?\\n\\r?\\n", -1).toList - val events: List[sttp.model.sse.ServerSentEvent] = blocks.map: block => - val lines: List[String] = block.split("\\r?\\n", -1).toList - sttp.model.sse.ServerSentEvent.parse(lines) - events.flatMap(_.data).find(_.nonEmpty) - - private[transport] def isAckLike(json: String): Boolean = - parser.parse(json) match - case Right(j) => j.hcursor.downField("id").focus.isEmpty - case Left(_) => false - final class HttpTransport[F[_]]( backend: Backend[F], uri: Uri, @@ -93,3 +81,16 @@ final class HttpTransport[F[_]]( .header("MCP-Protocol-Version", protocolVersion) sessionId.set(None) req.send(backend).map(_ => ()) + +object HttpTransport: + private[transport] def extractSingleSseData(body: String): Option[String] = + val blocks: List[String] = body.split("\\r?\\n\\r?\\n", -1).toList + val events: List[sttp.model.sse.ServerSentEvent] = blocks.map: block => + val lines: List[String] = block.split("\\r?\\n", -1).toList + ServerSentEvent.parse(lines) + events.flatMap(_.data).find(_.nonEmpty) + + private[transport] def isAckLike(json: String): Boolean = + parser.parse(json) match + case Right(j) => j.hcursor.downField("id").focus.isEmpty + case Left(_) => false diff --git a/client/src/main/scala/chimp/client/transport/StdioTransport.scala b/client/src/main/scala/chimp/client/transport/StdioTransport.scala index 7581a59..8f233ac 100644 --- a/client/src/main/scala/chimp/client/transport/StdioTransport.scala +++ b/client/src/main/scala/chimp/client/transport/StdioTransport.scala @@ -14,10 +14,6 @@ import java.util.concurrent.{ConcurrentHashMap, SynchronousQueue, TimeUnit} import scala.jdk.CollectionConverters.* -/** Synchronous stdio transport spawning the MCP server as a subprocess. - * - * For fiber-based effects (ZIO, cats-effect), use a `StreamingStdioTransport` impl from a per-effect chimp client subproject. - */ final class StdioTransport( command: List[String], env: Map[String, String] = Map.empty, diff --git a/client/src/main/scala/chimp/client/transport/StreamingHttpTransport.scala b/client/src/main/scala/chimp/client/transport/StreamingHttpTransport.scala index 13056ef..bc59dce 100644 --- a/client/src/main/scala/chimp/client/transport/StreamingHttpTransport.scala +++ b/client/src/main/scala/chimp/client/transport/StreamingHttpTransport.scala @@ -4,11 +4,6 @@ import sttp.capabilities.Streams import sttp.client4.StreamBackend import sttp.model.Uri -/** Abstract Streamable HTTP transport using a Streams-capable sttp backend. - * - * Concrete implementations live in per-effect chimp client subprojects (`client-zio`, `client-fs2`) and provide SSE parsing, resumability - * via `Last-Event-ID`, and bidirectional server-initiated dispatch over a long-lived GET. - */ abstract class StreamingHttpTransport[F[_], S]( protected val backend: StreamBackend[F, S], protected val uri: Uri, diff --git a/client/src/main/scala/chimp/client/transport/StreamingStdioTransport.scala b/client/src/main/scala/chimp/client/transport/StreamingStdioTransport.scala index 5d28a3c..9cb886b 100644 --- a/client/src/main/scala/chimp/client/transport/StreamingStdioTransport.scala +++ b/client/src/main/scala/chimp/client/transport/StreamingStdioTransport.scala @@ -4,11 +4,6 @@ import sttp.capabilities.Streams import java.io.File -/** Abstract async stdio transport using a Streams-capable effect. - * - * Concrete implementations live in per-effect chimp client subprojects (`client-zio`, `client-fs2`) and replace blocking `readLine` reads - * with non-blocking stream consumption tied to the effect's runtime. - */ abstract class StreamingStdioTransport[F[_], S]( protected val command: List[String], protected val env: Map[String, String] = Map.empty, diff --git a/client/src/main/scala/chimp/client/transport/Transport.scala b/client/src/main/scala/chimp/client/transport/Transport.scala index ecd9876..0e7f151 100644 --- a/client/src/main/scala/chimp/client/transport/Transport.scala +++ b/client/src/main/scala/chimp/client/transport/Transport.scala @@ -3,13 +3,6 @@ package chimp.client.transport import chimp.protocol.JSONRPCMessage import sttp.monad.MonadError -/** A bidirectional transport carrying JSON-RPC messages for an MCP client. - * - * - `send(req)` for a `Request` returns the matching `Response` or `Error` from the peer. - * - `send(notif)` for a `Notification` returns `None` once the message has been delivered. - * - `onIncoming(handler)` registers a callback for server-initiated requests and notifications. HTTP non-streaming transports never - * invoke it; stdio and streaming transports do. - */ trait Transport[F[_]]: given monad: MonadError[F] def send(msg: JSONRPCMessage): F[Option[JSONRPCMessage]] From 3af8f47678a3d5e88ebecc14f947acb41763bd8f Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Wed, 13 May 2026 12:19:27 +0200 Subject: [PATCH 17/27] docs: document client and server conformance --- client-conformance/README.md | 45 ++++++++++++++++++ .../scala/chimp/conformance/client/Main.scala | 9 ++-- server-conformance/README.md | 46 +++++++++++++++++++ .../scala/chimp/conformance/server/Main.scala | 12 ++--- 4 files changed, 102 insertions(+), 10 deletions(-) create mode 100644 client-conformance/README.md create mode 100644 server-conformance/README.md diff --git a/client-conformance/README.md b/client-conformance/README.md new file mode 100644 index 0000000..939c136 --- /dev/null +++ b/client-conformance/README.md @@ -0,0 +1,45 @@ +# client-conformance + +Runs chimp's MCP client against the +official [MCP conformance test suite](https://github.com/modelcontextprotocol/conformance). + +## What it does + +The conformance harness is the inverse of a server: it **starts a test MCP server**, spawns the binary configured +via `--command` (this fat-jar wrapped in [`bin/chimp-conformance-client`](bin/chimp-conformance-client)), and passes the +test-server URL as the last argument. The client process reads the `MCP_CONFORMANCE_SCENARIO` env var to decide what +protocol exchange to drive, talks to the harness's server, and exits 0 on success. + +This subproject is the binary the harness invokes. `Main.scala` dispatches on the scenario name and uses `chimp-client` +to drive the protocol. + +## How to run + +Using sbt task (assembles a client fat jar and runs test suite in one step): + +```bash +sbt 'clientConformance/conformance client --suite core' +sbt 'clientConformance/conformance client --scenario initialize' +sbt 'clientConformance/conformance client --scenario tools_call' +``` + +The `@modelcontextprotocol/conformance` will be installed using npm, it must be available on the PATH. + +## Adding a scenario + +Add a case in `Main.scala` matching on the scenario name (the value of `MCP_CONFORMANCE_SCENARIO`), drive the protocol +with `McpClient`, return exit code 0 on success. Once it passes, remove the entry from the baseline file (see below). + +## The baseline file + +[`conformance-baseline.yml`](../conformance-baseline.yml) lists scenarios that are known to fail today. The harness uses +it like this: + +| Scenario result | In baseline? | Exit code | Meaning | +|-----------------|--------------|-----------|---------------------------------------| +| Fails | Yes | 0 | Expected failure — keep working on it | +| Fails | No | 1 | Regression — CI fails | +| Passes | Yes | 1 | Stale baseline — remove the entry | +| Passes | No | 0 | Normal pass | + +So the file shrinks as the SDK matures. diff --git a/client-conformance/src/main/scala/chimp/conformance/client/Main.scala b/client-conformance/src/main/scala/chimp/conformance/client/Main.scala index 0c6d626..3d62c38 100644 --- a/client-conformance/src/main/scala/chimp/conformance/client/Main.scala +++ b/client-conformance/src/main/scala/chimp/conformance/client/Main.scala @@ -5,6 +5,7 @@ import chimp.client.transport.HttpTransport import chimp.protocol.* import io.circe.Json import sttp.client4.DefaultSyncBackend +import sttp.model.Uri import sttp.shared.Identity object Main: @@ -16,12 +17,12 @@ object Main: System.err.println("Usage: chimp-conformance-client ") sys.exit(2) - val serverUrl = sttp.model.Uri.parse(args.last) match - case Right(u) => u - case Left(e) => System.err.println(s"Invalid server URL: $e"); sys.exit(2) + val serverUrl = Uri.parse(args.last) match + case Right(url) => url + case Left(e) => System.err.println(s"Invalid server URL: $e"); sys.exit(2) val scenario = sys.env.getOrElse("MCP_CONFORMANCE_SCENARIO", "") - val protocolVersion = sys.env.get("MCP_CONFORMANCE_PROTOCOL_VERSION").getOrElse(ProtocolVersion.Latest) + val protocolVersion = sys.env.getOrElse("MCP_CONFORMANCE_PROTOCOL_VERSION", ProtocolVersion.Latest) val backend = DefaultSyncBackend() val transport = HttpTransport[Identity](backend, serverUrl, protocolVersion) diff --git a/server-conformance/README.md b/server-conformance/README.md new file mode 100644 index 0000000..f7f57ed --- /dev/null +++ b/server-conformance/README.md @@ -0,0 +1,46 @@ +# server-conformance + +Runs chimp's MCP server against the +official [MCP conformance test suite](https://github.com/modelcontextprotocol/conformance). + +## What it does + +`Main.scala` starts a small chimp MCP server on a Netty sync backend, registers a handful of tools that the conformance +scenarios expect (`add_numbers`, `test_simple_text`, `test_error_handling`), and prints the bound URL to stdout. The +conformance harness then connects to it as an MCP client and runs the server-side scenarios against it. + +The harness is run separately (via the `conformance` sbt task or by hand with `npx`); it acts as the **client**, +our `Main` is the **server under test**. + +## How to run + +Using sbt task (assembles a server fat jar and runs test suite in one step): + +```bash +sbt 'serverConformance/conformance server' +sbt 'serverConformance/conformance server --scenario ping' +sbt 'serverConformance/conformance server --scenario server-initialize' +``` + +The `@modelcontextprotocol/conformance` will be installed using npm, it must be available on the PATH. + +The server binds an ephemeral port by default. To pin it: pass `--port=NNNN` or set `CHIMP_CONFORMANCE_PORT`. + +## Adding a scenario + +Add server code handling the flow that a given scenario expects. The harness's failure output tells you which name and +what result shape it wants. Remove the corresponding entry from the baseline file once it passes. + +## The baseline file + +[`conformance-baseline.yml`](../conformance-baseline.yml) lists scenarios that are known to fail today. The harness uses +it like this: + +| Scenario result | In baseline? | Exit code | Meaning | +|-----------------|--------------|-----------|---------------------------------------| +| Fails | Yes | 0 | Expected failure — keep working on it | +| Fails | No | 1 | Regression — CI fails | +| Passes | Yes | 1 | Stale baseline — remove the entry | +| Passes | No | 0 | Normal pass | + +So the file shrinks as the SDK matures. diff --git a/server-conformance/src/main/scala/chimp/conformance/server/Main.scala b/server-conformance/src/main/scala/chimp/conformance/server/Main.scala index c8465f8..64255f5 100644 --- a/server-conformance/src/main/scala/chimp/conformance/server/Main.scala +++ b/server-conformance/src/main/scala/chimp/conformance/server/Main.scala @@ -8,21 +8,21 @@ import sttp.tapir.server.netty.sync.NettySyncServer object Main: - case class AddNumbersInput(a: Double, b: Double) derives Codec, Schema - case class NoInput() derives Codec, Schema + private case class AddNumbersInput(a: Double, b: Double) derives Codec, Schema + private case class NoInput() derives Codec, Schema private val addNumbers = tool("add_numbers") - .description("Adds two numbers and returns the result as text.") + .description("Adds two numbers and returns the result as text") .input[AddNumbersInput] .handle(in => Right((in.a + in.b).toString)) private val simpleText = tool("test_simple_text") - .description("Returns a fixed text string.") + .description("Returns a fixed text string") .input[NoInput] - .handle(_ => Right("This is a simple text response for testing.")) + .handle(_ => Right("This is a simple text response for testing")) private val errorTool = tool("test_error_handling") - .description("Always returns an error result.") + .description("Always returns an error result") .input[NoInput] .handle(_ => Left("This tool intentionally returns an error for testing")) From 078b95bd0364cc3d806920d072d3153303a9f07c Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Wed, 13 May 2026 12:26:53 +0200 Subject: [PATCH 18/27] refactor: small build.sbt cleanup --- build.sbt | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/build.sbt b/build.sbt index e135a57..3734ebd 100644 --- a/build.sbt +++ b/build.sbt @@ -1,12 +1,13 @@ -import com.softwaremill.SbtSoftwareMillCommon.commonSmlBuildSettings import com.softwaremill.Publish.{ossPublishSettings, updateDocs} +import com.softwaremill.SbtSoftwareMillCommon.commonSmlBuildSettings import com.softwaremill.UpdateVersionInDocs -// Version constants val scalaTestV = "3.2.20" val circeV = "0.14.15" +val slf4jV = "2.0.17" +val logbackV = "1.5.32" val tapirV = "1.13.18" -val sttpClient4V = "4.0.23" +val sttpClientV = "4.0.23" lazy val verifyExamplesCompileUsingScalaCli = taskKey[Unit]("Verify that each example compiles using Scala CLI") @@ -31,7 +32,7 @@ lazy val root = (project in file(".")) .settings(publishArtifact := false, name := "chimp") .aggregate(core, server, client, examples, serverConformance, clientConformance) -val conformance = inputKey[Unit]("Run the MCP conformance harness via npx against this subproject. Extra args are passed through.") +val conformance = inputKey[Unit]("Run the MCP conformance harness via npx, extra args are passed through") lazy val core: Project = (project in file("core")) .settings(commonSettings: _*) @@ -42,7 +43,7 @@ lazy val core: Project = (project in file("core")) "io.circe" %% "circe-core" % circeV, "io.circe" %% "circe-generic" % circeV, "io.circe" %% "circe-parser" % circeV, - "org.slf4j" % "slf4j-api" % "2.0.17", + "org.slf4j" % "slf4j-api" % slf4jV, "com.networknt" % "json-schema-validator" % "3.0.2" % Test ) ) @@ -67,7 +68,7 @@ lazy val client: Project = (project in file("client")) name := "chimp-client", libraryDependencies ++= Seq( scalaTest, - "com.softwaremill.sttp.client4" %% "core" % sttpClient4V + "com.softwaremill.sttp.client4" %% "core" % sttpClientV ) ) .dependsOn(core) @@ -81,7 +82,7 @@ lazy val examples = (project in file("examples")) "com.softwaremill.sttp.client4" %% "core" % "4.0.23", "com.softwaremill.sttp.tapir" %% "tapir-netty-server-sync" % tapirV, "com.softwaremill.sttp.tapir" %% "tapir-zio-http-server" % tapirV, - "ch.qos.logback" % "logback-classic" % "1.5.32" + "ch.qos.logback" % "logback-classic" % logbackV ), verifyExamplesCompileUsingScalaCli := VerifyExamplesCompileUsingScalaCli(sLog.value, sourceDirectory.value) ) @@ -91,15 +92,15 @@ import sbtassembly.AssemblyPlugin.autoImport.* lazy val assemblySettings = Seq( assembly / assemblyMergeStrategy := { - case PathList("META-INF", "MANIFEST.MF") => MergeStrategy.discard - case PathList("META-INF", "INDEX.LIST") => MergeStrategy.discard - case PathList("META-INF", "DEPENDENCIES") => MergeStrategy.discard - case PathList("META-INF", "services", _ @ _*) => MergeStrategy.concat + case PathList("META-INF", "MANIFEST.MF") => MergeStrategy.discard + case PathList("META-INF", "INDEX.LIST") => MergeStrategy.discard + case PathList("META-INF", "DEPENDENCIES") => MergeStrategy.discard + case PathList("META-INF", "services", _ @_*) => MergeStrategy.concat case PathList("META-INF", xs @ _*) if xs.lastOption.exists(s => s.endsWith(".SF") || s.endsWith(".DSA") || s.endsWith(".RSA")) => MergeStrategy.discard - case PathList("META-INF", _ @ _*) => MergeStrategy.first - case PathList("module-info.class") => MergeStrategy.discard - case _ => MergeStrategy.first + case PathList("META-INF", _ @_*) => MergeStrategy.first + case PathList("module-info.class") => MergeStrategy.discard + case _ => MergeStrategy.first } ) @@ -114,10 +115,11 @@ lazy val serverConformance = (project in file("server-conformance")) assembly / assemblyJarName := "chimp-server-conformance.jar", libraryDependencies ++= Seq( "com.softwaremill.sttp.tapir" %% "tapir-netty-server-sync" % tapirV, - "ch.qos.logback" % "logback-classic" % "1.5.32" + "ch.qos.logback" % "logback-classic" % logbackV ), conformance := { import complete.DefaultParsers.* + import scala.sys.process.* val args = spaceDelimited("").parsed.toList val jar = assembly.value @@ -177,6 +179,7 @@ lazy val clientConformance = (project in file("client-conformance")) ), conformance := { import complete.DefaultParsers.* + import scala.sys.process.* val args = spaceDelimited("").parsed.toList val _ = assembly.value From 587dd4c16fc98a4eec3f21cf7cc844c296c6038d Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Wed, 13 May 2026 13:06:15 +0200 Subject: [PATCH 19/27] refactor: small updates --- .../main/scala/chimp/client/McpClient.scala | 2 +- ...aultMcpClient.scala => McpClientImpl.scala} | 18 ++++++++++-------- .../chimp/client/internal/Correlator.scala | 10 ++++++---- 3 files changed, 17 insertions(+), 13 deletions(-) rename client/src/main/scala/chimp/client/{DefaultMcpClient.scala => McpClientImpl.scala} (96%) diff --git a/client/src/main/scala/chimp/client/McpClient.scala b/client/src/main/scala/chimp/client/McpClient.scala index db7cd76..6619b80 100644 --- a/client/src/main/scala/chimp/client/McpClient.scala +++ b/client/src/main/scala/chimp/client/McpClient.scala @@ -41,7 +41,7 @@ object McpClient: elicitationHandler: Option[ElicitRequest => F[ElicitResult]] = None, protocolVersion: String = ProtocolVersion.Latest ): McpClient[F] = - DefaultMcpClient.create( + McpClientImpl.create( transport, clientInfo, protocolVersion, diff --git a/client/src/main/scala/chimp/client/DefaultMcpClient.scala b/client/src/main/scala/chimp/client/McpClientImpl.scala similarity index 96% rename from client/src/main/scala/chimp/client/DefaultMcpClient.scala rename to client/src/main/scala/chimp/client/McpClientImpl.scala index 1c388ef..ff99b77 100644 --- a/client/src/main/scala/chimp/client/DefaultMcpClient.scala +++ b/client/src/main/scala/chimp/client/McpClientImpl.scala @@ -1,6 +1,6 @@ package chimp.client -import chimp.client.internal.Correlator +import chimp.client.internal.{Correlator, UUIDCorrelator} import chimp.client.notifications.ServerNotificationListener import chimp.client.transport.Transport import chimp.protocol.* @@ -11,16 +11,17 @@ import sttp.monad.syntax.* import java.util.concurrent.atomic.AtomicReference -object DefaultMcpClient: +object McpClientImpl: def create[F[_]]( transport: Transport[F], clientInfo: Implementation, protocolVersion: String, rootsHandler: Option[() => F[ListRootsResult]], samplingHandler: Option[CreateMessageRequest => F[CreateMessageResult]], - elicitationHandler: Option[ElicitRequest => F[ElicitResult]] + elicitationHandler: Option[ElicitRequest => F[ElicitResult]], + correlator: Correlator = UUIDCorrelator() ): McpClient[F] = - val impl = new Impl[F](transport, clientInfo, protocolVersion, rootsHandler, samplingHandler, elicitationHandler) + val impl = new Impl[F](transport, clientInfo, protocolVersion, rootsHandler, samplingHandler, elicitationHandler, correlator) impl.installIncoming() impl @@ -30,13 +31,14 @@ object DefaultMcpClient: protocolVersion: String, rootsHandler: Option[() => F[ListRootsResult]], samplingHandler: Option[CreateMessageRequest => F[CreateMessageResult]], - elicitationHandler: Option[ElicitRequest => F[ElicitResult]] + elicitationHandler: Option[ElicitRequest => F[ElicitResult]], + correlator: Correlator ) extends McpClient[F]: private given MonadError[F] = transport.monad - private val correlator = Correlator() + private val listeners = AtomicReference[List[ServerNotificationListener[F]]](Nil) - private val wireCaps: ClientCapabilities = ClientCapabilities( + private val capabilities: ClientCapabilities = ClientCapabilities( roots = rootsHandler.map(_ => ClientRootsCapability(listChanged = Some(true))), sampling = samplingHandler.map(_ => Json.obj()), elicitation = elicitationHandler.map(_ => Json.obj()) @@ -99,7 +101,7 @@ object DefaultMcpClient: override def initialize(): F[InitializeResult] = val params = InitializeParams( protocolVersion = protocolVersion, - capabilities = wireCaps, + capabilities = capabilities, clientInfo = clientInfo ) sendRequest[InitializeResult]("initialize", Some(params.asJson)).flatMap: r => diff --git a/client/src/main/scala/chimp/client/internal/Correlator.scala b/client/src/main/scala/chimp/client/internal/Correlator.scala index 0504f46..7a24602 100644 --- a/client/src/main/scala/chimp/client/internal/Correlator.scala +++ b/client/src/main/scala/chimp/client/internal/Correlator.scala @@ -2,8 +2,10 @@ package chimp.client.internal import chimp.protocol.RequestId -import java.util.concurrent.atomic.AtomicLong +import java.util.UUID -final class Correlator: - private val counter = AtomicLong(0L) - def nextId(): RequestId = RequestId(counter.incrementAndGet().toInt) +trait Correlator: + def nextId(): RequestId + +final class UUIDCorrelator extends Correlator: + def nextId(): RequestId = RequestId(UUID.randomUUID().toString) From ae83b7b1a8202a95d9b54e4101dbeb704ba39b19 Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Wed, 13 May 2026 13:20:29 +0200 Subject: [PATCH 20/27] fix: post rebase update --- build.sbt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.sbt b/build.sbt index 3734ebd..072794b 100644 --- a/build.sbt +++ b/build.sbt @@ -4,7 +4,7 @@ import com.softwaremill.UpdateVersionInDocs val scalaTestV = "3.2.20" val circeV = "0.14.15" -val slf4jV = "2.0.17" +val slf4jV = "2.0.18" val logbackV = "1.5.32" val tapirV = "1.13.18" val sttpClientV = "4.0.23" From e1cd2f2f658a8be342cfd89151301a4636b0641d Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Wed, 13 May 2026 16:43:40 +0200 Subject: [PATCH 21/27] fix: fail client initialization when server protocol is unsuported --- .../scala/chimp/conformance/client/Main.scala | 5 ++++- .../main/scala/chimp/client/McpClient.scala | 2 +- .../scala/chimp/client/McpClientImpl.scala | 18 ++++++++++++++---- .../chimp/client/transport/HttpTransport.scala | 7 +++---- .../chimp/client/CapabilityDispatchSpec.scala | 2 +- .../scala/chimp/client/McpClientSpec.scala | 4 ++-- .../main/scala/chimp/protocol/Lifecycle.scala | 2 +- .../scala/chimp/protocol/ProtocolVersion.scala | 15 +++++++++++---- .../chimp/protocol/SchemaConformanceSpec.scala | 2 +- .../main/scala/chimp/server/McpHandler.scala | 2 +- 10 files changed, 39 insertions(+), 20 deletions(-) diff --git a/client-conformance/src/main/scala/chimp/conformance/client/Main.scala b/client-conformance/src/main/scala/chimp/conformance/client/Main.scala index 3d62c38..ce78a4b 100644 --- a/client-conformance/src/main/scala/chimp/conformance/client/Main.scala +++ b/client-conformance/src/main/scala/chimp/conformance/client/Main.scala @@ -22,7 +22,10 @@ object Main: case Left(e) => System.err.println(s"Invalid server URL: $e"); sys.exit(2) val scenario = sys.env.getOrElse("MCP_CONFORMANCE_SCENARIO", "") - val protocolVersion = sys.env.getOrElse("MCP_CONFORMANCE_PROTOCOL_VERSION", ProtocolVersion.Latest) + val protocolVersion: ProtocolVersion = sys.env + .get("MCP_CONFORMANCE_PROTOCOL_VERSION") + .flatMap(ProtocolVersion.from) + .getOrElse(ProtocolVersion.Latest) val backend = DefaultSyncBackend() val transport = HttpTransport[Identity](backend, serverUrl, protocolVersion) diff --git a/client/src/main/scala/chimp/client/McpClient.scala b/client/src/main/scala/chimp/client/McpClient.scala index 6619b80..a8f78c8 100644 --- a/client/src/main/scala/chimp/client/McpClient.scala +++ b/client/src/main/scala/chimp/client/McpClient.scala @@ -39,7 +39,7 @@ object McpClient: rootsHandler: Option[() => F[ListRootsResult]] = None, samplingHandler: Option[CreateMessageRequest => F[CreateMessageResult]] = None, elicitationHandler: Option[ElicitRequest => F[ElicitResult]] = None, - protocolVersion: String = ProtocolVersion.Latest + protocolVersion: ProtocolVersion = ProtocolVersion.Latest ): McpClient[F] = McpClientImpl.create( transport, diff --git a/client/src/main/scala/chimp/client/McpClientImpl.scala b/client/src/main/scala/chimp/client/McpClientImpl.scala index ff99b77..0cf9f7b 100644 --- a/client/src/main/scala/chimp/client/McpClientImpl.scala +++ b/client/src/main/scala/chimp/client/McpClientImpl.scala @@ -15,7 +15,7 @@ object McpClientImpl: def create[F[_]]( transport: Transport[F], clientInfo: Implementation, - protocolVersion: String, + protocolVersion: ProtocolVersion, rootsHandler: Option[() => F[ListRootsResult]], samplingHandler: Option[CreateMessageRequest => F[CreateMessageResult]], elicitationHandler: Option[ElicitRequest => F[ElicitResult]], @@ -28,7 +28,7 @@ object McpClientImpl: private final class Impl[F[_]]( transport: Transport[F], clientInfo: Implementation, - protocolVersion: String, + protocolVersion: ProtocolVersion, rootsHandler: Option[() => F[ListRootsResult]], samplingHandler: Option[CreateMessageRequest => F[CreateMessageResult]], elicitationHandler: Option[ElicitRequest => F[ElicitResult]], @@ -104,8 +104,18 @@ object McpClientImpl: capabilities = capabilities, clientInfo = clientInfo ) - sendRequest[InitializeResult]("initialize", Some(params.asJson)).flatMap: r => - sendNotification("notifications/initialized", None).map(_ => r) + sendRequest[InitializeResult]("initialize", Some(params.asJson)).flatMap: result => + if ProtocolVersion.from(result.protocolVersion).isDefined then sendNotification("notifications/initialized", None).map(_ => result) + else + transport + .close() + .flatMap: _ => + summon[MonadError[F]].error( + McpProtocolException( + s"Server responded with unsupported protocol version '${result.protocolVersion}'; " + + s"client supports: ${ProtocolVersion.values.toList.map(_.wire).sorted.mkString(", ")}" + ) + ) override def ping(): F[Unit] = sendRequest[Json]("ping", None).map(_ => ()) diff --git a/client/src/main/scala/chimp/client/transport/HttpTransport.scala b/client/src/main/scala/chimp/client/transport/HttpTransport.scala index 86fd98a..2c1b29f 100644 --- a/client/src/main/scala/chimp/client/transport/HttpTransport.scala +++ b/client/src/main/scala/chimp/client/transport/HttpTransport.scala @@ -12,11 +12,10 @@ import sttp.monad.syntax.* import java.util.concurrent.atomic.AtomicReference -/** Non-streaming Streamable HTTP transport. Works against any sttp `Backend[F]`. */ final class HttpTransport[F[_]]( backend: Backend[F], uri: Uri, - protocolVersion: String = ProtocolVersion.Latest + protocolVersion: ProtocolVersion = ProtocolVersion.Latest ) extends Transport[F]: given monad: MonadError[F] = backend.monad @@ -29,7 +28,7 @@ final class HttpTransport[F[_]]( .post(uri) .header("Content-Type", "application/json") .header("Accept", s"${MediaType.ApplicationJson.toString}, text/event-stream") - .header("MCP-Protocol-Version", protocolVersion) + .header("MCP-Protocol-Version", protocolVersion.wire) .body(body) sessionId.get().foreach(s => req = req.header("Mcp-Session-Id", s)) @@ -78,7 +77,7 @@ final class HttpTransport[F[_]]( val req = basicRequest .delete(uri) .header("Mcp-Session-Id", id) - .header("MCP-Protocol-Version", protocolVersion) + .header("MCP-Protocol-Version", protocolVersion.wire) sessionId.set(None) req.send(backend).map(_ => ()) diff --git a/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala b/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala index e2042e7..8a74d49 100644 --- a/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala +++ b/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala @@ -55,7 +55,7 @@ class CapabilityDispatchSpec extends AnyFlatSpec with Matchers: it should "include opted-in capabilities on initialize" in: val t = InMemoryTransport() val initResult = InitializeResult( - protocolVersion = ProtocolVersion.Latest, + protocolVersion = ProtocolVersion.Latest.wire, capabilities = ServerCapabilities(), serverInfo = Implementation(name = "s", version = "1") ) diff --git a/client/src/test/scala/chimp/client/McpClientSpec.scala b/client/src/test/scala/chimp/client/McpClientSpec.scala index f22018c..8c3660d 100644 --- a/client/src/test/scala/chimp/client/McpClientSpec.scala +++ b/client/src/test/scala/chimp/client/McpClientSpec.scala @@ -15,7 +15,7 @@ class McpClientSpec extends AnyFlatSpec with Matchers: it should "initialize and read the server's protocol version" in: val initResult = InitializeResult( - protocolVersion = ProtocolVersion.Latest, + protocolVersion = ProtocolVersion.Latest.wire, capabilities = ServerCapabilities(), serverInfo = Implementation(name = "test-server", version = "1.0") ) @@ -26,7 +26,7 @@ class McpClientSpec extends AnyFlatSpec with Matchers: val t = HttpTransport[Identity](backend, mcpUri) val client = McpClient[Identity](t, clientInfo) val result = client.initialize() - result.protocolVersion shouldBe ProtocolVersion.Latest + result.protocolVersion shouldBe ProtocolVersion.Latest.wire result.serverInfo.name shouldBe "test-server" it should "call a tool and decode the result" in: diff --git a/core/src/main/scala/chimp/protocol/Lifecycle.scala b/core/src/main/scala/chimp/protocol/Lifecycle.scala index f014907..ed859a1 100644 --- a/core/src/main/scala/chimp/protocol/Lifecycle.scala +++ b/core/src/main/scala/chimp/protocol/Lifecycle.scala @@ -27,7 +27,7 @@ final case class ServerCapabilities( ) derives Codec final case class InitializeParams( - protocolVersion: String, + protocolVersion: ProtocolVersion, capabilities: ClientCapabilities, clientInfo: Implementation, _meta: Option[Map[String, Json]] = None diff --git a/core/src/main/scala/chimp/protocol/ProtocolVersion.scala b/core/src/main/scala/chimp/protocol/ProtocolVersion.scala index 612a63b..5f75ad0 100644 --- a/core/src/main/scala/chimp/protocol/ProtocolVersion.scala +++ b/core/src/main/scala/chimp/protocol/ProtocolVersion.scala @@ -1,9 +1,16 @@ package chimp.protocol +import io.circe.{Decoder, Encoder, Json} + +enum ProtocolVersion(val wire: String): + case V2025_06_18 extends ProtocolVersion("2025-06-18") + case V2025_11_25 extends ProtocolVersion("2025-11-25") + object ProtocolVersion: - val Latest: String = "2025-11-25" + val Latest: ProtocolVersion = V2025_11_25 - val Supported: Set[String] = Set("2025-06-18", "2025-11-25") + def from(s: String): Option[ProtocolVersion] = values.find(_.wire == s) + def negotiate(requested: String): ProtocolVersion = from(requested).getOrElse(Latest) - def negotiate(requested: String): String = - if Supported.contains(requested) then requested else Latest + given Encoder[ProtocolVersion] = Encoder.instance(v => Json.fromString(v.wire)) + given Decoder[ProtocolVersion] = Decoder.decodeString.emap(s => from(s).toRight(s"Unsupported protocol version: $s")) diff --git a/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala b/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala index 3641453..c94930f 100644 --- a/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala +++ b/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala @@ -63,7 +63,7 @@ class SchemaConformanceSpec extends AnyFlatSpec with Matchers: validate( "InitializeResult", InitializeResult( - protocolVersion = ProtocolVersion.Latest, + protocolVersion = ProtocolVersion.Latest.wire, capabilities = ServerCapabilities(tools = Some(ServerToolsCapability(listChanged = Some(false)))), serverInfo = Implementation(name = "chimp-test", version = "0.0.1"), instructions = Some("welcome") diff --git a/server/src/main/scala/chimp/server/McpHandler.scala b/server/src/main/scala/chimp/server/McpHandler.scala index 9de5ff4..de6cf34 100644 --- a/server/src/main/scala/chimp/server/McpHandler.scala +++ b/server/src/main/scala/chimp/server/McpHandler.scala @@ -78,7 +78,7 @@ class McpHandler[F[_]]( val negotiated = requested.map(ProtocolVersion.negotiate).getOrElse(ProtocolVersion.Latest) val capabilities = ServerCapabilities(tools = Some(ServerToolsCapability(listChanged = Some(false)))) val result = - InitializeResult(protocolVersion = negotiated, capabilities = capabilities, serverInfo = Implementation(name, version)) + InitializeResult(protocolVersion = negotiated.wire, capabilities = capabilities, serverInfo = Implementation(name, version)) JSONRPCMessage.Response(id = id, result = result.asJson) /** Handles the 'tools/list' JSON-RPC method, returning the list of available tools. */ From 4d9ed9ec13f6c2d524d893125968c0487de0cfdf Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Wed, 13 May 2026 17:17:20 +0200 Subject: [PATCH 22/27] fix: respect server capabilities in client --- .../main/scala/chimp/client/McpClient.scala | 3 + .../scala/chimp/client/McpClientImpl.scala | 67 +++++++++++++------ .../client/transport/HttpTransport.scala | 4 +- .../chimp/client/CapabilityDispatchSpec.scala | 2 +- .../scala/chimp/client/McpClientSpec.scala | 58 +++++++++++++--- .../chimp/protocol/ProtocolVersion.scala | 6 +- .../protocol/SchemaConformanceSpec.scala | 2 +- .../main/scala/chimp/server/McpHandler.scala | 2 +- 8 files changed, 107 insertions(+), 37 deletions(-) diff --git a/client/src/main/scala/chimp/client/McpClient.scala b/client/src/main/scala/chimp/client/McpClient.scala index a8f78c8..6ae9093 100644 --- a/client/src/main/scala/chimp/client/McpClient.scala +++ b/client/src/main/scala/chimp/client/McpClient.scala @@ -10,6 +10,9 @@ trait McpClient[F[_]]: def ping(): F[Unit] def close(): F[Unit] + /** The server's negotiated capabilities. `None` before `initialize()` has completed successfully. */ + def serverCapabilities: Option[ServerCapabilities] + def listTools(cursor: Option[Cursor] = None): F[ListToolsResponse] def callTool(name: String, arguments: Json): F[CallToolResult] diff --git a/client/src/main/scala/chimp/client/McpClientImpl.scala b/client/src/main/scala/chimp/client/McpClientImpl.scala index 0cf9f7b..ebafb76 100644 --- a/client/src/main/scala/chimp/client/McpClientImpl.scala +++ b/client/src/main/scala/chimp/client/McpClientImpl.scala @@ -36,8 +36,20 @@ object McpClientImpl: ) extends McpClient[F]: private given MonadError[F] = transport.monad + private val negotiated = AtomicReference[Option[ServerCapabilities]](None) private val listeners = AtomicReference[List[ServerNotificationListener[F]]](Nil) + override def serverCapabilities: Option[ServerCapabilities] = negotiated.get() + + private def requireCapability[A](method: String, present: ServerCapabilities => Boolean)(action: => F[A]): F[A] = + negotiated.get() match + case None => + summon[MonadError[F]].error(McpProtocolException(s"Client not initialized")) + case Some(caps) if !present(caps) => + summon[MonadError[F]].error(McpProtocolException(s"Server did not negotiate the capability required for $method")) + case Some(_) => + action + private val capabilities: ClientCapabilities = ClientCapabilities( roots = rootsHandler.map(_ => ClientRootsCapability(listChanged = Some(true))), sampling = samplingHandler.map(_ => Json.obj()), @@ -105,7 +117,9 @@ object McpClientImpl: clientInfo = clientInfo ) sendRequest[InitializeResult]("initialize", Some(params.asJson)).flatMap: result => - if ProtocolVersion.from(result.protocolVersion).isDefined then sendNotification("notifications/initialized", None).map(_ => result) + if ProtocolVersion.from(result.protocolVersion).isDefined then + negotiated.set(Some(result.capabilities)) + sendNotification("notifications/initialized", None).map(_ => result) else transport .close() @@ -113,7 +127,7 @@ object McpClientImpl: summon[MonadError[F]].error( McpProtocolException( s"Server responded with unsupported protocol version '${result.protocolVersion}'; " + - s"client supports: ${ProtocolVersion.values.toList.map(_.wire).sorted.mkString(", ")}" + s"client supports: ${ProtocolVersion.values.toList.map(_.name).sorted.mkString(", ")}" ) ) @@ -122,45 +136,56 @@ object McpClientImpl: override def close(): F[Unit] = transport.close() override def listTools(cursor: Option[Cursor]): F[ListToolsResponse] = - val params = cursor.map(c => ListToolsParams(cursor = Some(c)).asJson) - sendRequest[ListToolsResponse]("tools/list", params) + requireCapability("tools/list", _.tools.isDefined): + val params = cursor.map(c => ListToolsParams(cursor = Some(c)).asJson) + sendRequest[ListToolsResponse]("tools/list", params) override def callTool(name: String, arguments: Json): F[CallToolResult] = - val params = CallToolParams(name = name, arguments = arguments).asJson - sendRequest[CallToolResult]("tools/call", Some(params)) + requireCapability("tools/call", _.tools.isDefined): + val params = CallToolParams(name = name, arguments = arguments).asJson + sendRequest[CallToolResult]("tools/call", Some(params)) override def listPrompts(cursor: Option[Cursor]): F[ListPromptsResult] = - val params = cursor.map(c => ListPromptsParams(cursor = Some(c)).asJson) - sendRequest[ListPromptsResult]("prompts/list", params) + requireCapability("prompts/list", _.prompts.isDefined): + val params = cursor.map(c => ListPromptsParams(cursor = Some(c)).asJson) + sendRequest[ListPromptsResult]("prompts/list", params) override def getPrompt(name: String, arguments: Map[String, String]): F[GetPromptResult] = - val argOpt = if arguments.isEmpty then None else Some(arguments) - val params = GetPromptParams(name = name, arguments = argOpt).asJson - sendRequest[GetPromptResult]("prompts/get", Some(params)) + requireCapability("prompts/get", _.prompts.isDefined): + val argOpt = if arguments.isEmpty then None else Some(arguments) + val params = GetPromptParams(name = name, arguments = argOpt).asJson + sendRequest[GetPromptResult]("prompts/get", Some(params)) override def listResources(cursor: Option[Cursor]): F[ListResourcesResult] = - val params = cursor.map(c => ListResourcesParams(cursor = Some(c)).asJson) - sendRequest[ListResourcesResult]("resources/list", params) + requireCapability("resources/list", _.resources.isDefined): + val params = cursor.map(c => ListResourcesParams(cursor = Some(c)).asJson) + sendRequest[ListResourcesResult]("resources/list", params) override def listResourceTemplates(cursor: Option[Cursor]): F[ListResourceTemplatesResult] = - val params = cursor.map(c => ListResourceTemplatesParams(cursor = Some(c)).asJson) - sendRequest[ListResourceTemplatesResult]("resources/templates/list", params) + requireCapability("resources/templates/list", _.resources.isDefined): + val params = cursor.map(c => ListResourceTemplatesParams(cursor = Some(c)).asJson) + sendRequest[ListResourceTemplatesResult]("resources/templates/list", params) override def readResource(uri: String): F[ReadResourceResult] = - sendRequest[ReadResourceResult]("resources/read", Some(ReadResourceParams(uri = uri).asJson)) + requireCapability("resources/read", _.resources.isDefined): + sendRequest[ReadResourceResult]("resources/read", Some(ReadResourceParams(uri = uri).asJson)) override def subscribeResource(uri: String): F[Unit] = - sendRequest[Json]("resources/subscribe", Some(SubscribeParams(uri = uri).asJson)).map(_ => ()) + requireCapability("resources/subscribe", _.resources.flatMap(_.subscribe).getOrElse(false)): + sendRequest[Json]("resources/subscribe", Some(SubscribeParams(uri = uri).asJson)).map(_ => ()) override def unsubscribeResource(uri: String): F[Unit] = - sendRequest[Json]("resources/unsubscribe", Some(UnsubscribeParams(uri = uri).asJson)).map(_ => ()) + requireCapability("resources/unsubscribe", _.resources.flatMap(_.subscribe).getOrElse(false)): + sendRequest[Json]("resources/unsubscribe", Some(UnsubscribeParams(uri = uri).asJson)).map(_ => ()) override def complete(ref: CompleteRef, argument: CompleteArgument): F[CompleteResult] = - val params = CompleteParams(ref = ref, argument = argument).asJson - sendRequest[CompleteResult]("completion/complete", Some(params)) + requireCapability("completion/complete", _.completions.isDefined): + val params = CompleteParams(ref = ref, argument = argument).asJson + sendRequest[CompleteResult]("completion/complete", Some(params)) override def setLoggingLevel(level: LoggingLevel): F[Unit] = - sendRequest[Json]("logging/setLevel", Some(SetLevelParams(level = level).asJson)).map(_ => ()) + requireCapability("logging/setLevel", _.logging.isDefined): + sendRequest[Json]("logging/setLevel", Some(SetLevelParams(level = level).asJson)).map(_ => ()) override def sendProgress(token: ProgressToken, progress: Double, total: Option[Double], message: Option[String]): F[Unit] = val params = ProgressParams(progressToken = token, progress = progress, total = total, message = message).asJson diff --git a/client/src/main/scala/chimp/client/transport/HttpTransport.scala b/client/src/main/scala/chimp/client/transport/HttpTransport.scala index 2c1b29f..44f15f8 100644 --- a/client/src/main/scala/chimp/client/transport/HttpTransport.scala +++ b/client/src/main/scala/chimp/client/transport/HttpTransport.scala @@ -28,7 +28,7 @@ final class HttpTransport[F[_]]( .post(uri) .header("Content-Type", "application/json") .header("Accept", s"${MediaType.ApplicationJson.toString}, text/event-stream") - .header("MCP-Protocol-Version", protocolVersion.wire) + .header("MCP-Protocol-Version", protocolVersion.name) .body(body) sessionId.get().foreach(s => req = req.header("Mcp-Session-Id", s)) @@ -77,7 +77,7 @@ final class HttpTransport[F[_]]( val req = basicRequest .delete(uri) .header("Mcp-Session-Id", id) - .header("MCP-Protocol-Version", protocolVersion.wire) + .header("MCP-Protocol-Version", protocolVersion.name) sessionId.set(None) req.send(backend).map(_ => ()) diff --git a/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala b/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala index 8a74d49..4d08d3c 100644 --- a/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala +++ b/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala @@ -55,7 +55,7 @@ class CapabilityDispatchSpec extends AnyFlatSpec with Matchers: it should "include opted-in capabilities on initialize" in: val t = InMemoryTransport() val initResult = InitializeResult( - protocolVersion = ProtocolVersion.Latest.wire, + protocolVersion = ProtocolVersion.Latest.name, capabilities = ServerCapabilities(), serverInfo = Implementation(name = "s", version = "1") ) diff --git a/client/src/test/scala/chimp/client/McpClientSpec.scala b/client/src/test/scala/chimp/client/McpClientSpec.scala index 8c3660d..2744c74 100644 --- a/client/src/test/scala/chimp/client/McpClientSpec.scala +++ b/client/src/test/scala/chimp/client/McpClientSpec.scala @@ -6,6 +6,8 @@ import io.circe.syntax.* import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import sttp.client4.testing.SyncBackendStub +import sttp.client4.{GenericRequest, StringBody} +import sttp.model.StatusCode import sttp.shared.Identity class McpClientSpec extends AnyFlatSpec with Matchers: @@ -13,9 +15,14 @@ class McpClientSpec extends AnyFlatSpec with Matchers: private val mcpUri = sttp.model.Uri.parse("http://localhost/mcp").toOption.get private val clientInfo = Implementation(name = "chimp-test", version = "0.0.1") + private def envelopeFor(method: String, request: GenericRequest[?, ?]): Boolean = + request.body match + case StringBody(s, _, _) => s.contains(s"\"$method\"") + case _ => false + it should "initialize and read the server's protocol version" in: val initResult = InitializeResult( - protocolVersion = ProtocolVersion.Latest.wire, + protocolVersion = ProtocolVersion.Latest.name, capabilities = ServerCapabilities(), serverInfo = Implementation(name = "test-server", version = "1.0") ) @@ -26,17 +33,52 @@ class McpClientSpec extends AnyFlatSpec with Matchers: val t = HttpTransport[Identity](backend, mcpUri) val client = McpClient[Identity](t, clientInfo) val result = client.initialize() - result.protocolVersion shouldBe ProtocolVersion.Latest.wire + result.protocolVersion shouldBe ProtocolVersion.Latest.name result.serverInfo.name shouldBe "test-server" - it should "call a tool and decode the result" in: + it should "call a tool and decode the result after initialization" in: + val initResult = InitializeResult( + protocolVersion = ProtocolVersion.Latest.name, + capabilities = ServerCapabilities(tools = Some(ServerToolsCapability(listChanged = Some(false)))), + serverInfo = Implementation(name = "test-server", version = "1.0") + ) + val initEnvelope = + (JSONRPCMessage.Response(id = RequestId(1), result = initResult.asJson): JSONRPCMessage).asJson.noSpaces val callResult = CallToolResult(content = List(ToolContent.Text(text = "hi"))) - val responseEnvelope = + val callEnvelope = (JSONRPCMessage.Response(id = RequestId(1), result = callResult.asJson): JSONRPCMessage).asJson.noSpaces - val backend = SyncBackendStub.whenAnyRequest.thenRespondAdjust(responseEnvelope) + val backend = SyncBackendStub + .whenRequestMatches(envelopeFor("initialize", _)) + .thenRespondAdjust(initEnvelope) + .whenRequestMatches(envelopeFor("tools/call", _)) + .thenRespondAdjust(callEnvelope) + .whenAnyRequest + .thenRespondAdjust("", StatusCode.Accepted) + + val client = McpClient[Identity](HttpTransport[Identity](backend, mcpUri), clientInfo) + val _ = client.initialize() + val result = client.callTool("echo", io.circe.Json.obj("message" -> io.circe.Json.fromString("hi"))) + result.isError shouldBe false + result.content.head shouldBe ToolContent.Text("text", "hi") + + it should "fail fast when a server capability is not negotiated" in: + val initResult = InitializeResult( + protocolVersion = ProtocolVersion.Latest.name, + capabilities = ServerCapabilities(), + serverInfo = Implementation(name = "test-server", version = "1.0") + ) + val initEnvelope = + (JSONRPCMessage.Response(id = RequestId(1), result = initResult.asJson): JSONRPCMessage).asJson.noSpaces + val backend = SyncBackendStub.whenAnyRequest.thenRespondAdjust(initEnvelope) + val client = McpClient[Identity](HttpTransport[Identity](backend, mcpUri), clientInfo) + val _ = client.initialize() + val ex = intercept[McpProtocolException](client.callTool("anything", io.circe.Json.obj())) + ex.getMessage should include("Server did not negotiate the capability required for tools/call") + + it should "fail fast when called before initialization" in: + val backend = SyncBackendStub.whenAnyRequest.thenRespondAdjust("") val t = HttpTransport[Identity](backend, mcpUri) val client = McpClient[Identity](t, clientInfo) - val r = client.callTool("echo", io.circe.Json.obj("message" -> io.circe.Json.fromString("hi"))) - r.isError shouldBe false - r.content.head shouldBe ToolContent.Text("text", "hi") + val ex = intercept[McpProtocolException](client.listTools()) + ex.getMessage should include("Client not initialized") diff --git a/core/src/main/scala/chimp/protocol/ProtocolVersion.scala b/core/src/main/scala/chimp/protocol/ProtocolVersion.scala index 5f75ad0..829c4e7 100644 --- a/core/src/main/scala/chimp/protocol/ProtocolVersion.scala +++ b/core/src/main/scala/chimp/protocol/ProtocolVersion.scala @@ -2,15 +2,15 @@ package chimp.protocol import io.circe.{Decoder, Encoder, Json} -enum ProtocolVersion(val wire: String): +enum ProtocolVersion(val name: String): case V2025_06_18 extends ProtocolVersion("2025-06-18") case V2025_11_25 extends ProtocolVersion("2025-11-25") object ProtocolVersion: val Latest: ProtocolVersion = V2025_11_25 - def from(s: String): Option[ProtocolVersion] = values.find(_.wire == s) + def from(s: String): Option[ProtocolVersion] = values.find(_.name == s) def negotiate(requested: String): ProtocolVersion = from(requested).getOrElse(Latest) - given Encoder[ProtocolVersion] = Encoder.instance(v => Json.fromString(v.wire)) + given Encoder[ProtocolVersion] = Encoder.instance(v => Json.fromString(v.name)) given Decoder[ProtocolVersion] = Decoder.decodeString.emap(s => from(s).toRight(s"Unsupported protocol version: $s")) diff --git a/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala b/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala index c94930f..51d1a5b 100644 --- a/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala +++ b/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala @@ -63,7 +63,7 @@ class SchemaConformanceSpec extends AnyFlatSpec with Matchers: validate( "InitializeResult", InitializeResult( - protocolVersion = ProtocolVersion.Latest.wire, + protocolVersion = ProtocolVersion.Latest.name, capabilities = ServerCapabilities(tools = Some(ServerToolsCapability(listChanged = Some(false)))), serverInfo = Implementation(name = "chimp-test", version = "0.0.1"), instructions = Some("welcome") diff --git a/server/src/main/scala/chimp/server/McpHandler.scala b/server/src/main/scala/chimp/server/McpHandler.scala index de6cf34..c83ffe3 100644 --- a/server/src/main/scala/chimp/server/McpHandler.scala +++ b/server/src/main/scala/chimp/server/McpHandler.scala @@ -78,7 +78,7 @@ class McpHandler[F[_]]( val negotiated = requested.map(ProtocolVersion.negotiate).getOrElse(ProtocolVersion.Latest) val capabilities = ServerCapabilities(tools = Some(ServerToolsCapability(listChanged = Some(false)))) val result = - InitializeResult(protocolVersion = negotiated.wire, capabilities = capabilities, serverInfo = Implementation(name, version)) + InitializeResult(protocolVersion = negotiated.name, capabilities = capabilities, serverInfo = Implementation(name, version)) JSONRPCMessage.Response(id = id, result = result.asJson) /** Handles the 'tools/list' JSON-RPC method, returning the list of available tools. */ From 96ec74dad148ac5148050fa5096430972c59eb27 Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Wed, 13 May 2026 17:37:10 +0200 Subject: [PATCH 23/27] refactor: small refactor in client impl --- .../scala/chimp/client/McpClientImpl.scala | 103 +++++++++--------- .../scala/chimp/client/McpClientSpec.scala | 3 +- 2 files changed, 52 insertions(+), 54 deletions(-) diff --git a/client/src/main/scala/chimp/client/McpClientImpl.scala b/client/src/main/scala/chimp/client/McpClientImpl.scala index ebafb76..a257900 100644 --- a/client/src/main/scala/chimp/client/McpClientImpl.scala +++ b/client/src/main/scala/chimp/client/McpClientImpl.scala @@ -36,27 +36,17 @@ object McpClientImpl: ) extends McpClient[F]: private given MonadError[F] = transport.monad - private val negotiated = AtomicReference[Option[ServerCapabilities]](None) - private val listeners = AtomicReference[List[ServerNotificationListener[F]]](Nil) - - override def serverCapabilities: Option[ServerCapabilities] = negotiated.get() - - private def requireCapability[A](method: String, present: ServerCapabilities => Boolean)(action: => F[A]): F[A] = - negotiated.get() match - case None => - summon[MonadError[F]].error(McpProtocolException(s"Client not initialized")) - case Some(caps) if !present(caps) => - summon[MonadError[F]].error(McpProtocolException(s"Server did not negotiate the capability required for $method")) - case Some(_) => - action - - private val capabilities: ClientCapabilities = ClientCapabilities( + private val clientCapabilities: ClientCapabilities = ClientCapabilities( roots = rootsHandler.map(_ => ClientRootsCapability(listChanged = Some(true))), sampling = samplingHandler.map(_ => Json.obj()), elicitation = elicitationHandler.map(_ => Json.obj()) ) + private val negotiatedServerCapabilities = AtomicReference[Option[ServerCapabilities]](None) + private val notificationListeners = AtomicReference[List[ServerNotificationListener[F]]](Nil) - private val dispatch: Map[String, Json => F[Json]] = + override def serverCapabilities: Option[ServerCapabilities] = negotiatedServerCapabilities.get() + + private val handlers: Map[String, Json => F[Json]] = val entries = List( rootsHandler.map(fn => "roots/list" -> ((_: Json) => fn().map(_.asJson))), samplingHandler.map(fn => @@ -82,43 +72,44 @@ object McpClientImpl: private def handleIncoming(msg: JSONRPCMessage): F[Unit] = msg match case JSONRPCMessage.Request(_, method, params, id) => - dispatch.get(method) match - case Some(h) => + handlers.get(method) match + case Some(handler) => val rawParams = params.getOrElse(Json.obj()) - h(rawParams).flatMap(result => transport.send(JSONRPCMessage.Response(id = id, result = result)).map(_ => ())).handleError { - case t => - val err = JSONRPCMessage.Error( + handler(rawParams) + .flatMap(result => transport.send(JSONRPCMessage.Response(id = id, result = result)).map(_ => ())) + .handleError { case t => + val error = JSONRPCMessage.Error( id = id, error = JSONRPCErrorObject( code = JSONRPCErrorCodes.InternalError.code, - message = Option(t.getMessage).getOrElse("internal error") + message = Option(t.getMessage).getOrElse("Internal error") ) ) - transport.send(err).map(_ => ()) - } + transport.send(error).map(_ => ()) + } case None => - val err = JSONRPCMessage.Error( + val error = JSONRPCMessage.Error( id = id, - error = JSONRPCErrorObject(code = JSONRPCErrorCodes.MethodNotFound.code, message = s"No handler for method: $method") + error = JSONRPCErrorObject(code = JSONRPCErrorCodes.MethodNotFound.code, message = s"Client doesn't support method: $method") ) - transport.send(err).map(_ => ()) - case n: JSONRPCMessage.Notification => - listeners + transport.send(error).map(_ => ()) + case notification: JSONRPCMessage.Notification => + notificationListeners .get() - .foldLeft(summon[MonadError[F]].unit(())): (acc, l) => - acc.flatMap(_ => l.onNotification(n).handleError(_ => summon[MonadError[F]].unit(()))) + .foldLeft(summon[MonadError[F]].unit(())): (acc, listener) => + acc.flatMap(_ => listener.onNotification(notification).handleError(_ => summon[MonadError[F]].unit(()))) case _ => summon[MonadError[F]].unit(()) override def initialize(): F[InitializeResult] = val params = InitializeParams( protocolVersion = protocolVersion, - capabilities = capabilities, + capabilities = clientCapabilities, clientInfo = clientInfo ) sendRequest[InitializeResult]("initialize", Some(params.asJson)).flatMap: result => if ProtocolVersion.from(result.protocolVersion).isDefined then - negotiated.set(Some(result.capabilities)) + negotiatedServerCapabilities.set(Some(result.capabilities)) sendNotification("notifications/initialized", None).map(_ => result) else transport @@ -126,7 +117,7 @@ object McpClientImpl: .flatMap: _ => summon[MonadError[F]].error( McpProtocolException( - s"Server responded with unsupported protocol version '${result.protocolVersion}'; " + + s"Server responded with unsupported protocol version '${result.protocolVersion}', " + s"client supports: ${ProtocolVersion.values.toList.map(_.name).sorted.mkString(", ")}" ) ) @@ -136,55 +127,54 @@ object McpClientImpl: override def close(): F[Unit] = transport.close() override def listTools(cursor: Option[Cursor]): F[ListToolsResponse] = - requireCapability("tools/list", _.tools.isDefined): + requireServerCapability("tools/list", _.tools.isDefined): val params = cursor.map(c => ListToolsParams(cursor = Some(c)).asJson) sendRequest[ListToolsResponse]("tools/list", params) override def callTool(name: String, arguments: Json): F[CallToolResult] = - requireCapability("tools/call", _.tools.isDefined): + requireServerCapability("tools/call", _.tools.isDefined): val params = CallToolParams(name = name, arguments = arguments).asJson sendRequest[CallToolResult]("tools/call", Some(params)) override def listPrompts(cursor: Option[Cursor]): F[ListPromptsResult] = - requireCapability("prompts/list", _.prompts.isDefined): + requireServerCapability("prompts/list", _.prompts.isDefined): val params = cursor.map(c => ListPromptsParams(cursor = Some(c)).asJson) sendRequest[ListPromptsResult]("prompts/list", params) override def getPrompt(name: String, arguments: Map[String, String]): F[GetPromptResult] = - requireCapability("prompts/get", _.prompts.isDefined): - val argOpt = if arguments.isEmpty then None else Some(arguments) - val params = GetPromptParams(name = name, arguments = argOpt).asJson + requireServerCapability("prompts/get", _.prompts.isDefined): + val params = GetPromptParams(name = name, arguments = if arguments.isEmpty then None else Some(arguments)).asJson sendRequest[GetPromptResult]("prompts/get", Some(params)) override def listResources(cursor: Option[Cursor]): F[ListResourcesResult] = - requireCapability("resources/list", _.resources.isDefined): + requireServerCapability("resources/list", _.resources.isDefined): val params = cursor.map(c => ListResourcesParams(cursor = Some(c)).asJson) sendRequest[ListResourcesResult]("resources/list", params) override def listResourceTemplates(cursor: Option[Cursor]): F[ListResourceTemplatesResult] = - requireCapability("resources/templates/list", _.resources.isDefined): + requireServerCapability("resources/templates/list", _.resources.isDefined): val params = cursor.map(c => ListResourceTemplatesParams(cursor = Some(c)).asJson) sendRequest[ListResourceTemplatesResult]("resources/templates/list", params) override def readResource(uri: String): F[ReadResourceResult] = - requireCapability("resources/read", _.resources.isDefined): + requireServerCapability("resources/read", _.resources.isDefined): sendRequest[ReadResourceResult]("resources/read", Some(ReadResourceParams(uri = uri).asJson)) override def subscribeResource(uri: String): F[Unit] = - requireCapability("resources/subscribe", _.resources.flatMap(_.subscribe).getOrElse(false)): + requireServerCapability("resources/subscribe", _.resources.flatMap(_.subscribe).getOrElse(false)): sendRequest[Json]("resources/subscribe", Some(SubscribeParams(uri = uri).asJson)).map(_ => ()) override def unsubscribeResource(uri: String): F[Unit] = - requireCapability("resources/unsubscribe", _.resources.flatMap(_.subscribe).getOrElse(false)): + requireServerCapability("resources/unsubscribe", _.resources.flatMap(_.subscribe).getOrElse(false)): sendRequest[Json]("resources/unsubscribe", Some(UnsubscribeParams(uri = uri).asJson)).map(_ => ()) override def complete(ref: CompleteRef, argument: CompleteArgument): F[CompleteResult] = - requireCapability("completion/complete", _.completions.isDefined): + requireServerCapability("completion/complete", _.completions.isDefined): val params = CompleteParams(ref = ref, argument = argument).asJson sendRequest[CompleteResult]("completion/complete", Some(params)) override def setLoggingLevel(level: LoggingLevel): F[Unit] = - requireCapability("logging/setLevel", _.logging.isDefined): + requireServerCapability("logging/setLevel", _.logging.isDefined): sendRequest[Json]("logging/setLevel", Some(SetLevelParams(level = level).asJson)).map(_ => ()) override def sendProgress(token: ProgressToken, progress: Double, total: Option[Double], message: Option[String]): F[Unit] = @@ -199,13 +189,22 @@ object McpClientImpl: sendNotification("notifications/roots/list_changed", None) override def onServerNotification(listener: ServerNotificationListener[F]): F[Unit] = - val _ = listeners.updateAndGet(ls => ls :+ listener) + val _ = notificationListeners.updateAndGet(listeners => listeners :+ listener) summon[MonadError[F]].unit(()) + private def requireServerCapability[A](method: String, present: ServerCapabilities => Boolean)(action: => F[A]): F[A] = + negotiatedServerCapabilities.get() match + case None => + summon[MonadError[F]].error(McpProtocolException(s"Client not initialized")) + case Some(caps) if !present(caps) => + summon[MonadError[F]].error(McpProtocolException(s"Server did not negotiate the capability required for $method")) + case Some(_) => + action + private def sendRequest[R: Decoder](method: String, params: Option[Json]): F[R] = - val req = JSONRPCMessage.Request(method = method, params = params, id = correlator.nextId()) + val request = JSONRPCMessage.Request(method = method, params = params, id = correlator.nextId()) transport - .send(req) + .send(request) .flatMap: case Some(JSONRPCMessage.Response(_, _, result)) => result.as[R] match @@ -219,5 +218,5 @@ object McpClientImpl: summon[MonadError[F]].error(McpProtocolException(s"No response received for request $method")) private def sendNotification(method: String, params: Option[Json]): F[Unit] = - val n = JSONRPCMessage.Notification(method = method, params = params) - transport.send(n).map(_ => ()) + val notification = JSONRPCMessage.Notification(method = method, params = params) + transport.send(notification).map(_ => ()) diff --git a/client/src/test/scala/chimp/client/McpClientSpec.scala b/client/src/test/scala/chimp/client/McpClientSpec.scala index 2744c74..d86f568 100644 --- a/client/src/test/scala/chimp/client/McpClientSpec.scala +++ b/client/src/test/scala/chimp/client/McpClientSpec.scala @@ -30,8 +30,7 @@ class McpClientSpec extends AnyFlatSpec with Matchers: (JSONRPCMessage.Response(id = RequestId(1), result = initResult.asJson): JSONRPCMessage).asJson.noSpaces val backend = SyncBackendStub.whenAnyRequest.thenRespondAdjust(responseEnvelope) - val t = HttpTransport[Identity](backend, mcpUri) - val client = McpClient[Identity](t, clientInfo) + val client = McpClient[Identity](HttpTransport[Identity](backend, mcpUri), clientInfo) val result = client.initialize() result.protocolVersion shouldBe ProtocolVersion.Latest.name result.serverInfo.name shouldBe "test-server" From 0e5cde688c1462aa87728058b06471273dded87a Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Wed, 13 May 2026 17:40:15 +0200 Subject: [PATCH 24/27] refactor: small refactor in client impl --- .../main/scala/chimp/client/McpClientImpl.scala | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/client/src/main/scala/chimp/client/McpClientImpl.scala b/client/src/main/scala/chimp/client/McpClientImpl.scala index a257900..15a4415 100644 --- a/client/src/main/scala/chimp/client/McpClientImpl.scala +++ b/client/src/main/scala/chimp/client/McpClientImpl.scala @@ -52,16 +52,17 @@ object McpClientImpl: samplingHandler.map(fn => "sampling/createMessage" -> ((params: Json) => params.as[CreateMessageRequest] match - case Right(req) => fn(req).map(_.asJson) - case Left(e) => - summon[MonadError[F]].error(IllegalArgumentException(s"Failed to decode CreateMessageRequest: ${e.getMessage}")) + case Right(request) => fn(request).map(_.asJson) + case Left(error) => + summon[MonadError[F]].error(IllegalArgumentException(s"Failed to decode CreateMessageRequest: ${error.getMessage}")) ) ), elicitationHandler.map(fn => "elicitation/create" -> ((params: Json) => params.as[ElicitRequest] match - case Right(req) => fn(req).map(_.asJson) - case Left(e) => summon[MonadError[F]].error(IllegalArgumentException(s"Failed to decode ElicitRequest: ${e.getMessage}")) + case Right(request) => fn(request).map(_.asJson) + case Left(error) => + summon[MonadError[F]].error(IllegalArgumentException(s"Failed to decode ElicitRequest: ${error.getMessage}")) ) ) ).flatten @@ -196,7 +197,7 @@ object McpClientImpl: negotiatedServerCapabilities.get() match case None => summon[MonadError[F]].error(McpProtocolException(s"Client not initialized")) - case Some(caps) if !present(caps) => + case Some(capabilities) if !present(capabilities) => summon[MonadError[F]].error(McpProtocolException(s"Server did not negotiate the capability required for $method")) case Some(_) => action @@ -208,8 +209,8 @@ object McpClientImpl: .flatMap: case Some(JSONRPCMessage.Response(_, _, result)) => result.as[R] match - case Right(r) => summon[MonadError[F]].unit(r) - case Left(e) => summon[MonadError[F]].error(McpProtocolException(s"Failed to decode $method result: ${e.getMessage}")) + case Right(response) => summon[MonadError[F]].unit(response) + case Left(error) => summon[MonadError[F]].error(McpProtocolException(s"Failed to decode $method result: ${error.getMessage}")) case Some(JSONRPCMessage.Error(_, _, error)) => summon[MonadError[F]].error(McpProtocolException(s"$method failed: ${error.code} ${error.message}")) case Some(other) => From 9961666e6fef870b7acd337aa999031e2db67448 Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Wed, 13 May 2026 18:03:48 +0200 Subject: [PATCH 25/27] refactor: typed server notification listener, refactor --- .../scala/chimp/client/McpClientImpl.scala | 34 ++++++----- .../ServerNotificationListener.scala | 4 +- ...Spec.scala => CapabilityHandlerSpec.scala} | 58 ++++++++++--------- 3 files changed, 50 insertions(+), 46 deletions(-) rename client/src/test/scala/chimp/client/{CapabilityDispatchSpec.scala => CapabilityHandlerSpec.scala} (54%) diff --git a/client/src/main/scala/chimp/client/McpClientImpl.scala b/client/src/main/scala/chimp/client/McpClientImpl.scala index 15a4415..ed62bde 100644 --- a/client/src/main/scala/chimp/client/McpClientImpl.scala +++ b/client/src/main/scala/chimp/client/McpClientImpl.scala @@ -1,7 +1,7 @@ package chimp.client import chimp.client.internal.{Correlator, UUIDCorrelator} -import chimp.client.notifications.ServerNotificationListener +import chimp.client.notifications.{ServerNotification, ServerNotificationListener} import chimp.client.transport.Transport import chimp.protocol.* import io.circe.syntax.* @@ -35,6 +35,7 @@ object McpClientImpl: correlator: Correlator ) extends McpClient[F]: private given MonadError[F] = transport.monad + private val monad: MonadError[F] = transport.monad private val clientCapabilities: ClientCapabilities = ClientCapabilities( roots = rootsHandler.map(_ => ClientRootsCapability(listChanged = Some(true))), @@ -54,7 +55,7 @@ object McpClientImpl: params.as[CreateMessageRequest] match case Right(request) => fn(request).map(_.asJson) case Left(error) => - summon[MonadError[F]].error(IllegalArgumentException(s"Failed to decode CreateMessageRequest: ${error.getMessage}")) + monad.error(IllegalArgumentException(s"Failed to decode CreateMessageRequest: ${error.getMessage}")) ) ), elicitationHandler.map(fn => @@ -62,7 +63,7 @@ object McpClientImpl: params.as[ElicitRequest] match case Right(request) => fn(request).map(_.asJson) case Left(error) => - summon[MonadError[F]].error(IllegalArgumentException(s"Failed to decode ElicitRequest: ${error.getMessage}")) + monad.error(IllegalArgumentException(s"Failed to decode ElicitRequest: ${error.getMessage}")) ) ) ).flatten @@ -94,13 +95,14 @@ object McpClientImpl: error = JSONRPCErrorObject(code = JSONRPCErrorCodes.MethodNotFound.code, message = s"Client doesn't support method: $method") ) transport.send(error).map(_ => ()) - case notification: JSONRPCMessage.Notification => + case message: JSONRPCMessage.Notification => + val notification = ServerNotification.parse(message) notificationListeners .get() - .foldLeft(summon[MonadError[F]].unit(())): (acc, listener) => - acc.flatMap(_ => listener.onNotification(notification).handleError(_ => summon[MonadError[F]].unit(()))) + .foldLeft(monad.unit(())): (acc, listener) => + acc.flatMap(_ => listener.onNotification(notification).handleError(_ => monad.unit(()))) case _ => - summon[MonadError[F]].unit(()) + monad.unit(()) override def initialize(): F[InitializeResult] = val params = InitializeParams( @@ -116,7 +118,7 @@ object McpClientImpl: transport .close() .flatMap: _ => - summon[MonadError[F]].error( + monad.error( McpProtocolException( s"Server responded with unsupported protocol version '${result.protocolVersion}', " + s"client supports: ${ProtocolVersion.values.toList.map(_.name).sorted.mkString(", ")}" @@ -191,14 +193,14 @@ object McpClientImpl: override def onServerNotification(listener: ServerNotificationListener[F]): F[Unit] = val _ = notificationListeners.updateAndGet(listeners => listeners :+ listener) - summon[MonadError[F]].unit(()) + monad.unit(()) private def requireServerCapability[A](method: String, present: ServerCapabilities => Boolean)(action: => F[A]): F[A] = negotiatedServerCapabilities.get() match case None => - summon[MonadError[F]].error(McpProtocolException(s"Client not initialized")) + monad.error(McpProtocolException(s"Client not initialized")) case Some(capabilities) if !present(capabilities) => - summon[MonadError[F]].error(McpProtocolException(s"Server did not negotiate the capability required for $method")) + monad.error(McpProtocolException(s"Server did not negotiate the capability required for $method")) case Some(_) => action @@ -209,14 +211,14 @@ object McpClientImpl: .flatMap: case Some(JSONRPCMessage.Response(_, _, result)) => result.as[R] match - case Right(response) => summon[MonadError[F]].unit(response) - case Left(error) => summon[MonadError[F]].error(McpProtocolException(s"Failed to decode $method result: ${error.getMessage}")) + case Right(response) => monad.unit(response) + case Left(error) => monad.error(McpProtocolException(s"Failed to decode $method result: ${error.getMessage}")) case Some(JSONRPCMessage.Error(_, _, error)) => - summon[MonadError[F]].error(McpProtocolException(s"$method failed: ${error.code} ${error.message}")) + monad.error(McpProtocolException(s"$method failed: ${error.code} ${error.message}")) case Some(other) => - summon[MonadError[F]].error(McpProtocolException(s"Unexpected response to $method: $other")) + monad.error(McpProtocolException(s"Unexpected response to $method: $other")) case None => - summon[MonadError[F]].error(McpProtocolException(s"No response received for request $method")) + monad.error(McpProtocolException(s"No response received for request $method")) private def sendNotification(method: String, params: Option[Json]): F[Unit] = val notification = JSONRPCMessage.Notification(method = method, params = params) diff --git a/client/src/main/scala/chimp/client/notifications/ServerNotificationListener.scala b/client/src/main/scala/chimp/client/notifications/ServerNotificationListener.scala index 8b9591e..f884622 100644 --- a/client/src/main/scala/chimp/client/notifications/ServerNotificationListener.scala +++ b/client/src/main/scala/chimp/client/notifications/ServerNotificationListener.scala @@ -1,6 +1,4 @@ package chimp.client.notifications -import chimp.protocol.JSONRPCMessage - trait ServerNotificationListener[F[_]]: - def onNotification(n: JSONRPCMessage.Notification): F[Unit] + def onNotification(n: ServerNotification): F[Unit] diff --git a/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala b/client/src/test/scala/chimp/client/CapabilityHandlerSpec.scala similarity index 54% rename from client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala rename to client/src/test/scala/chimp/client/CapabilityHandlerSpec.scala index 4d08d3c..b106c98 100644 --- a/client/src/test/scala/chimp/client/CapabilityDispatchSpec.scala +++ b/client/src/test/scala/chimp/client/CapabilityHandlerSpec.scala @@ -7,71 +7,75 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import sttp.shared.Identity -class CapabilityDispatchSpec extends AnyFlatSpec with Matchers: +class CapabilityHandlerSpec extends AnyFlatSpec with Matchers: private val clientInfo = Implementation(name = "chimp-test", version = "0.0.1") it should "respond to a server-initiated roots/list with the registered handler's result" in: - val t = InMemoryTransport() + val transport = InMemoryTransport() val _ = McpClient[Identity]( - t, + transport, clientInfo, rootsHandler = Some(() => ListRootsResult(roots = List(Root(uri = "file:///x", name = Some("x"))))) ) - val req: JSONRPCMessage = JSONRPCMessage.Request(method = "roots/list", id = RequestId("server-1")) - t.simulateIncoming(req) + val request: JSONRPCMessage = JSONRPCMessage.Request(method = "roots/list", id = RequestId("server-1")) + transport.simulateIncoming(request) - t.sent.last match + transport.sent.last match case JSONRPCMessage.Response(_, _, result) => - val r = result.as[ListRootsResult].toOption.get - r.roots.head.name shouldBe Some("x") + result.as[ListRootsResult].toOption match + case Some(result) => + result.roots.head.name shouldBe Some("x") + case _ => fail("Expected result") case other => fail(s"Expected Response, got $other") it should "respond with MethodNotFound for capabilities the client didn't opt into" in: - val t = InMemoryTransport() - val _ = McpClient[Identity](t, clientInfo) + val transport = InMemoryTransport() + val _ = McpClient[Identity](transport, clientInfo) - val req: JSONRPCMessage = JSONRPCMessage.Request(method = "sampling/createMessage", id = RequestId("server-2")) - t.simulateIncoming(req) + val request: JSONRPCMessage = JSONRPCMessage.Request(method = "sampling/createMessage", id = RequestId("server-2")) + transport.simulateIncoming(request) - t.sent.last match + transport.sent.last match case JSONRPCMessage.Error(_, _, err) => err.code shouldBe JSONRPCErrorCodes.MethodNotFound.code case other => fail(s"Expected Error, got $other") it should "deliver incoming notifications to registered listeners" in: - val t = InMemoryTransport() - val client = McpClient[Identity](t, clientInfo) + val transport = InMemoryTransport() + val client = McpClient[Identity](transport, clientInfo) var received: Option[ServerNotification] = None - val listener: ServerNotificationListener[Identity] = n => { received = Some(ServerNotification.parse(n)); () } + val listener: ServerNotificationListener[Identity] = n => { received = Some(n); () } val _ = client.onServerNotification(listener) val params = ProgressParams(progressToken = ProgressToken("p1"), progress = 0.42) - val notif: JSONRPCMessage = JSONRPCMessage.Notification(method = "notifications/progress", params = Some(params.asJson)) - t.simulateIncoming(notif) + val notification: JSONRPCMessage = JSONRPCMessage.Notification(method = "notifications/progress", params = Some(params.asJson)) + transport.simulateIncoming(notification) received shouldBe Some(ServerNotification.Progress(params)) it should "include opted-in capabilities on initialize" in: - val t = InMemoryTransport() + val transport = InMemoryTransport() val initResult = InitializeResult( protocolVersion = ProtocolVersion.Latest.name, capabilities = ServerCapabilities(), serverInfo = Implementation(name = "s", version = "1") ) - t.planResponse(JSONRPCMessage.Response(id = RequestId(1), result = initResult.asJson)) + transport.planResponse(JSONRPCMessage.Response(id = RequestId(1), result = initResult.asJson)) val client = McpClient[Identity]( - t, + transport, clientInfo, rootsHandler = Some(() => ListRootsResult(roots = Nil)), elicitationHandler = Some((_: ElicitRequest) => ElicitResult(action = ElicitAction.Cancel)) ) val _ = client.initialize() - t.sent.head match - case r: JSONRPCMessage.Request => - val params = r.params.get.as[InitializeParams].toOption.get - params.capabilities.roots.isDefined shouldBe true - params.capabilities.elicitation.isDefined shouldBe true - params.capabilities.sampling shouldBe None + transport.sent.head match + case request: JSONRPCMessage.Request => + request.params.get.as[InitializeParams].toOption match + case Some(params) => + params.capabilities.roots.isDefined shouldBe true + params.capabilities.elicitation.isDefined shouldBe true + params.capabilities.sampling shouldBe None + case _ => fail("Expected params") case other => fail(s"Expected Request, got $other") From 5bf2fe4d677f8e224952ac3ae86a77ec89bc1a58 Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Wed, 13 May 2026 18:13:13 +0200 Subject: [PATCH 26/27] refactor: refactor http transport spec --- .../chimp/client/HttpTransportSpec.scala | 31 +++++++++---------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/client/src/test/scala/chimp/client/HttpTransportSpec.scala b/client/src/test/scala/chimp/client/HttpTransportSpec.scala index 65e1a3c..54e3328 100644 --- a/client/src/test/scala/chimp/client/HttpTransportSpec.scala +++ b/client/src/test/scala/chimp/client/HttpTransportSpec.scala @@ -4,6 +4,7 @@ import chimp.client.transport.HttpTransport import chimp.protocol.* import io.circe.Json import io.circe.syntax.* +import org.scalatest.Assertions import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import sttp.client4.testing.SyncBackendStub @@ -14,30 +15,28 @@ class HttpTransportSpec extends AnyFlatSpec with Matchers: private val mcpUri = sttp.model.Uri.parse("http://localhost/mcp").toOption.get - private def envelope(body: JSONRPCMessage): String = (body: JSONRPCMessage).asJson.noSpaces - it should "POST a request and decode the response body" in: - val expectedResult = Json.obj("ok" -> Json.fromBoolean(true)) + val result = Json.obj("ok" -> Json.fromBoolean(true)) val backend = SyncBackendStub.whenAnyRequest.thenRespondAdjust( - envelope(JSONRPCMessage.Response(id = RequestId(1), result = expectedResult)), + (JSONRPCMessage.Response(id = RequestId(1), result = result): JSONRPCMessage).asJson.noSpaces, StatusCode.Ok ) - val t = HttpTransport[Identity](backend, mcpUri) - val req: JSONRPCMessage = JSONRPCMessage.Request(method = "x", params = None, id = RequestId(1)) - t.send(req) match - case Some(JSONRPCMessage.Response(_, _, r)) => r shouldBe expectedResult - case other => fail(s"Expected Response, got: $other") + val transport = HttpTransport[Identity](backend, mcpUri) + val request: JSONRPCMessage = JSONRPCMessage.Request(method = "x", params = None, id = RequestId(1)) + transport.send(request) match + case Some(JSONRPCMessage.Response(_, _, result)) => Assertions.succeed + case other => fail(s"Expected Response, got: $other") - it should "return None for 202 Accepted (notification ack)" in: + it should "return none for 202 Accepted (notification ack)" in: val backend = SyncBackendStub.whenAnyRequest.thenRespondAdjust("", StatusCode.Accepted) - val t = HttpTransport[Identity](backend, mcpUri) - val n: JSONRPCMessage = JSONRPCMessage.Notification(method = "notifications/initialized") - t.send(n) shouldBe None + val transport = HttpTransport[Identity](backend, mcpUri) + val notification: JSONRPCMessage = JSONRPCMessage.Notification(method = "notifications/initialized") + transport.send(notification) shouldBe None it should "fail with McpAuthorizationException on 401" in: val backend = SyncBackendStub.whenAnyRequest.thenRespondAdjust("", StatusCode.Unauthorized) - val t = HttpTransport[Identity](backend, mcpUri) - val req: JSONRPCMessage = JSONRPCMessage.Request(method = "x", params = None, id = RequestId(1)) - val ex = intercept[McpAuthorizationException](t.send(req)) + val transport = HttpTransport[Identity](backend, mcpUri) + val request: JSONRPCMessage = JSONRPCMessage.Request(method = "x", params = None, id = RequestId(1)) + val ex = intercept[McpAuthorizationException](transport.send(request)) ex.statusCode shouldBe 401 From 731de8e3d73107356a24ed88d7449a4aeefc4884 Mon Sep 17 00:00:00 2001 From: kubinio123 Date: Wed, 13 May 2026 18:16:08 +0200 Subject: [PATCH 27/27] refactor: use defined media type --- .../src/main/scala/chimp/client/transport/HttpTransport.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/main/scala/chimp/client/transport/HttpTransport.scala b/client/src/main/scala/chimp/client/transport/HttpTransport.scala index 44f15f8..1d6c876 100644 --- a/client/src/main/scala/chimp/client/transport/HttpTransport.scala +++ b/client/src/main/scala/chimp/client/transport/HttpTransport.scala @@ -27,7 +27,7 @@ final class HttpTransport[F[_]]( var req = basicRequest .post(uri) .header("Content-Type", "application/json") - .header("Accept", s"${MediaType.ApplicationJson.toString}, text/event-stream") + .header("Accept", s"${MediaType.ApplicationJson.toString}, ${MediaType.TextEventStream.toString()}}") .header("MCP-Protocol-Version", protocolVersion.name) .body(body) sessionId.get().foreach(s => req = req.header("Mcp-Session-Id", s))