diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 85bc830..a7dd4c0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,9 +26,13 @@ jobs: uses: actions/setup-java@v5 with: distribution: 'temurin' - java-version: 11 + java-version: 21 cache: 'sbt' - uses: sbt/setup-sbt@3e125ece5c3e5248e18da9ed8d2cce3d335ec8dd # v1, specifically v1.1.14 + - name: Set up Node + uses: actions/setup-node@v4 + with: + node-version: '24' - name: Install scala-cli uses: VirtusLab/scala-cli-setup@68bd9c30954d20e6cb6ddaf01b3b38336f25df4b # main, specifically v1.10.1 with: @@ -37,10 +41,15 @@ jobs: run: sbt -v scalafmtCheckAll - name: Compile run: sbt -v compile - - name: Verify that examples compile using Scala CLI - run: sbt -v "project examples" verifyExamplesCompileUsingScalaCli + # TODO bring this step back after first release with new project structure (client + server) +# - name: Verify that examples compile using Scala CLI +# run: sbt -v "project examples" verifyExamplesCompileUsingScalaCli - name: Test run: sbt -v test + - name: Client conformance + run: sbt -v "clientConformance/conformance client --suite core" + - name: Server conformance + run: sbt -v "serverConformance/conformance server" - uses: actions/upload-artifact@v5 # upload test results if: success() || failure() # run this step even if previous step failed with: diff --git a/build.sbt b/build.sbt index d8613c0..54d139e 100644 --- a/build.sbt +++ b/build.sbt @@ -1,11 +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.18" +val logbackV = "1.5.32" val tapirV = "1.13.19" +val sttpClientV = "4.0.23" lazy val verifyExamplesCompileUsingScalaCli = taskKey[Unit]("Verify that each example compiles using Scala CLI") @@ -19,32 +21,57 @@ 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 -lazy val rootProject = (project in file(".")) +lazy val root = (project in file(".")) .settings(commonSettings: _*) .settings(publishArtifact := false, name := "chimp") - .aggregate(core, examples) + .aggregate(core, server, client, examples, serverConformance, clientConformance) + +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: _*) .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" % slf4jV, + "com.networknt" % "json-schema-validator" % "3.0.2" % Test + ) + ) + +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 client: Project = (project in file("client")) + .settings(commonSettings: _*) + .settings( + name := "chimp-client", + libraryDependencies ++= Seq( + scalaTest, + "com.softwaremill.sttp.client4" %% "core" % sttpClientV ) ) + .dependsOn(core) lazy val examples = (project in file("examples")) .settings(commonSettings: _*) @@ -55,8 +82,127 @@ 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) ) - .dependsOn(core) + .dependsOn(server, client) + +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" % logbackV + ), + 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(() => { + 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() + + val errReaderThread = new Thread(() => { + val reader = new java.io.BufferedReader(new java.io.InputStreamReader(proc.getErrorStream, "UTF-8")) + try { + var line: String = reader.readLine() + while (line != null) { + log.warn(s"[server-stderr] $line") + line = reader.readLine() + } + } catch { + case _: Throwable => () + } + }) + errReaderThread.setDaemon(true) + errReaderThread.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/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/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..ce78a4b --- /dev/null +++ b/client-conformance/src/main/scala/chimp/conformance/client/Main.scala @@ -0,0 +1,66 @@ +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.model.Uri +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 = 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: ProtocolVersion = sys.env + .get("MCP_CONFORMANCE_PROTOCOL_VERSION") + .flatMap(ProtocolVersion.from) + .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](transport, clientInfo, protocolVersion = protocolVersion) + val _ = client.initialize() + client.close() + 0 + + case "tools_call" => + val client = McpClient[Identity](transport, clientInfo, protocolVersion = protocolVersion) + val _ = client.initialize() + val _ = 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/McpClient.scala b/client/src/main/scala/chimp/client/McpClient.scala new file mode 100644 index 0000000..6ae9093 --- /dev/null +++ b/client/src/main/scala/chimp/client/McpClient.scala @@ -0,0 +1,54 @@ +package chimp.client + +import chimp.client.notifications.ServerNotificationListener +import chimp.client.transport.Transport +import chimp.protocol.* +import io.circe.Json + +trait McpClient[F[_]]: + def initialize(): F[InitializeResult] + 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] + + 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: + 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: ProtocolVersion = ProtocolVersion.Latest + ): McpClient[F] = + McpClientImpl.create( + transport, + clientInfo, + protocolVersion, + rootsHandler, + samplingHandler, + elicitationHandler + ) diff --git a/client/src/main/scala/chimp/client/McpClientException.scala b/client/src/main/scala/chimp/client/McpClientException.scala new file mode 100644 index 0000000..969528a --- /dev/null +++ b/client/src/main/scala/chimp/client/McpClientException.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/McpClientImpl.scala b/client/src/main/scala/chimp/client/McpClientImpl.scala new file mode 100644 index 0000000..ed62bde --- /dev/null +++ b/client/src/main/scala/chimp/client/McpClientImpl.scala @@ -0,0 +1,225 @@ +package chimp.client + +import chimp.client.internal.{Correlator, UUIDCorrelator} +import chimp.client.notifications.{ServerNotification, ServerNotificationListener} +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.* + +import java.util.concurrent.atomic.AtomicReference + +object McpClientImpl: + def create[F[_]]( + transport: Transport[F], + clientInfo: Implementation, + protocolVersion: ProtocolVersion, + rootsHandler: Option[() => F[ListRootsResult]], + samplingHandler: Option[CreateMessageRequest => F[CreateMessageResult]], + elicitationHandler: Option[ElicitRequest => F[ElicitResult]], + correlator: Correlator = UUIDCorrelator() + ): McpClient[F] = + val impl = new Impl[F](transport, clientInfo, protocolVersion, rootsHandler, samplingHandler, elicitationHandler, correlator) + impl.installIncoming() + impl + + private final class Impl[F[_]]( + transport: Transport[F], + clientInfo: Implementation, + protocolVersion: ProtocolVersion, + rootsHandler: Option[() => F[ListRootsResult]], + samplingHandler: Option[CreateMessageRequest => F[CreateMessageResult]], + elicitationHandler: Option[ElicitRequest => F[ElicitResult]], + 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))), + 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) + + 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 => + "sampling/createMessage" -> ((params: Json) => + params.as[CreateMessageRequest] match + case Right(request) => fn(request).map(_.asJson) + case Left(error) => + monad.error(IllegalArgumentException(s"Failed to decode CreateMessageRequest: ${error.getMessage}")) + ) + ), + elicitationHandler.map(fn => + "elicitation/create" -> ((params: Json) => + params.as[ElicitRequest] match + case Right(request) => fn(request).map(_.asJson) + case Left(error) => + monad.error(IllegalArgumentException(s"Failed to decode ElicitRequest: ${error.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.get(method) match + case Some(handler) => + val rawParams = params.getOrElse(Json.obj()) + 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") + ) + ) + transport.send(error).map(_ => ()) + } + case None => + val error = JSONRPCMessage.Error( + id = id, + error = JSONRPCErrorObject(code = JSONRPCErrorCodes.MethodNotFound.code, message = s"Client doesn't support method: $method") + ) + transport.send(error).map(_ => ()) + case message: JSONRPCMessage.Notification => + val notification = ServerNotification.parse(message) + notificationListeners + .get() + .foldLeft(monad.unit(())): (acc, listener) => + acc.flatMap(_ => listener.onNotification(notification).handleError(_ => monad.unit(()))) + case _ => + monad.unit(()) + + override def initialize(): F[InitializeResult] = + val params = InitializeParams( + protocolVersion = protocolVersion, + capabilities = clientCapabilities, + clientInfo = clientInfo + ) + sendRequest[InitializeResult]("initialize", Some(params.asJson)).flatMap: result => + if ProtocolVersion.from(result.protocolVersion).isDefined then + negotiatedServerCapabilities.set(Some(result.capabilities)) + sendNotification("notifications/initialized", None).map(_ => result) + else + transport + .close() + .flatMap: _ => + monad.error( + McpProtocolException( + s"Server responded with unsupported protocol version '${result.protocolVersion}', " + + s"client supports: ${ProtocolVersion.values.toList.map(_.name).sorted.mkString(", ")}" + ) + ) + + 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] = + 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] = + 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] = + 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] = + 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] = + 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] = + 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] = + requireServerCapability("resources/read", _.resources.isDefined): + sendRequest[ReadResourceResult]("resources/read", Some(ReadResourceParams(uri = uri).asJson)) + + override def subscribeResource(uri: String): F[Unit] = + 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] = + 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] = + 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] = + 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] = + 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] = + val _ = notificationListeners.updateAndGet(listeners => listeners :+ listener) + monad.unit(()) + + private def requireServerCapability[A](method: String, present: ServerCapabilities => Boolean)(action: => F[A]): F[A] = + negotiatedServerCapabilities.get() match + case None => + monad.error(McpProtocolException(s"Client not initialized")) + case Some(capabilities) if !present(capabilities) => + monad.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 request = JSONRPCMessage.Request(method = method, params = params, id = correlator.nextId()) + transport + .send(request) + .flatMap: + case Some(JSONRPCMessage.Response(_, _, result)) => + result.as[R] match + 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)) => + monad.error(McpProtocolException(s"$method failed: ${error.code} ${error.message}")) + case Some(other) => + monad.error(McpProtocolException(s"Unexpected response to $method: $other")) + case None => + 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) + transport.send(notification).map(_ => ()) 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..7a24602 --- /dev/null +++ b/client/src/main/scala/chimp/client/internal/Correlator.scala @@ -0,0 +1,11 @@ +package chimp.client.internal + +import chimp.protocol.RequestId + +import java.util.UUID + +trait Correlator: + def nextId(): RequestId + +final class UUIDCorrelator extends Correlator: + def nextId(): RequestId = RequestId(UUID.randomUUID().toString) 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..4ff4e07 --- /dev/null +++ b/client/src/main/scala/chimp/client/notifications/ServerNotification.scala @@ -0,0 +1,31 @@ +package chimp.client.notifications + +import chimp.protocol.* +import io.circe.Json + +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..f884622 --- /dev/null +++ b/client/src/main/scala/chimp/client/notifications/ServerNotificationListener.scala @@ -0,0 +1,4 @@ +package chimp.client.notifications + +trait ServerNotificationListener[F[_]]: + def onNotification(n: ServerNotification): F[Unit] 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..bccfcea --- /dev/null +++ b/client/src/main/scala/chimp/client/transport/HttpTransport.scala @@ -0,0 +1,89 @@ +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.{basicRequest, Backend, Response} +import sttp.model.sse.ServerSentEvent +import sttp.model.{MediaType, StatusCode, Uri} +import sttp.monad.MonadError +import sttp.monad.syntax.* + +import java.util.concurrent.atomic.AtomicReference + +final class HttpTransport[F[_]]( + backend: Backend[F], + uri: Uri, + protocolVersion: ProtocolVersion = 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 request = basicRequest + .post(uri) + .header("Content-Type", "application/json") + .header("Accept", s"${MediaType.ApplicationJson.toString}, ${MediaType.TextEventStream.toString()}}") + .header("MCP-Protocol-Version", protocolVersion.name) + .body(body) + sessionId.get().foreach(s => request = request.header("Mcp-Session-Id", s)) + + request.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(body) => + val contentType = response.header("Content-Type").getOrElse("") + val payload = + if contentType.contains(MediaType.TextEventStream.toString()) then HttpTransport.extractSingleSseData(body) + else if body.isEmpty then None + else Some(body) + payload match + case None => monad.unit(None) + case Some(json) => + parser.decode[JSONRPCMessage](json) match + case Right(message) => monad.unit(Some(message)) + case Left(error) => + monad.error(McpProtocolException(s"Failed to decode response body: ${error.getMessage}, payload $json")) + 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.name) + 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) 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..8f233ac --- /dev/null +++ b/client/src/main/scala/chimp/client/transport/StdioTransport.scala @@ -0,0 +1,124 @@ +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.* + +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 { val _ = q.offer(r, 1, TimeUnit.SECONDS) } + case e: JSONRPCMessage.Error => + val q = pending.remove(e.id) + if q != null then { val _ = 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") + ) + val _ = 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 { 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 new file mode 100644 index 0000000..bc59dce --- /dev/null +++ b/client/src/main/scala/chimp/client/transport/StreamingHttpTransport.scala @@ -0,0 +1,11 @@ +package chimp.client.transport + +import sttp.capabilities.Streams +import sttp.client4.StreamBackend +import sttp.model.Uri + +abstract class StreamingHttpTransport[F[_], 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 new file mode 100644 index 0000000..9cb886b --- /dev/null +++ b/client/src/main/scala/chimp/client/transport/StreamingStdioTransport.scala @@ -0,0 +1,12 @@ +package chimp.client.transport + +import sttp.capabilities.Streams + +import java.io.File + +abstract class StreamingStdioTransport[F[_], 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/main/scala/chimp/client/transport/Transport.scala b/client/src/main/scala/chimp/client/transport/Transport.scala new file mode 100644 index 0000000..0e7f151 --- /dev/null +++ b/client/src/main/scala/chimp/client/transport/Transport.scala @@ -0,0 +1,10 @@ +package chimp.client.transport + +import chimp.protocol.JSONRPCMessage +import sttp.monad.MonadError + +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/CapabilityHandlerSpec.scala b/client/src/test/scala/chimp/client/CapabilityHandlerSpec.scala new file mode 100644 index 0000000..b106c98 --- /dev/null +++ b/client/src/test/scala/chimp/client/CapabilityHandlerSpec.scala @@ -0,0 +1,81 @@ +package chimp.client + +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 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 transport = InMemoryTransport() + val _ = McpClient[Identity]( + transport, + clientInfo, + rootsHandler = Some(() => ListRootsResult(roots = List(Root(uri = "file:///x", name = Some("x"))))) + ) + + val request: JSONRPCMessage = JSONRPCMessage.Request(method = "roots/list", id = RequestId("server-1")) + transport.simulateIncoming(request) + + transport.sent.last match + case JSONRPCMessage.Response(_, _, result) => + 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 transport = InMemoryTransport() + val _ = McpClient[Identity](transport, clientInfo) + + val request: JSONRPCMessage = JSONRPCMessage.Request(method = "sampling/createMessage", id = RequestId("server-2")) + transport.simulateIncoming(request) + + 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 transport = InMemoryTransport() + val client = McpClient[Identity](transport, clientInfo) + var received: Option[ServerNotification] = None + val listener: ServerNotificationListener[Identity] = n => { received = Some(n); () } + val _ = client.onServerNotification(listener) + + val params = ProgressParams(progressToken = ProgressToken("p1"), progress = 0.42) + 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 transport = InMemoryTransport() + val initResult = InitializeResult( + protocolVersion = ProtocolVersion.Latest.name, + capabilities = ServerCapabilities(), + serverInfo = Implementation(name = "s", version = "1") + ) + transport.planResponse(JSONRPCMessage.Response(id = RequestId(1), result = initResult.asJson)) + val client = McpClient[Identity]( + transport, + clientInfo, + rootsHandler = Some(() => ListRootsResult(roots = Nil)), + elicitationHandler = Some((_: ElicitRequest) => ElicitResult(action = ElicitAction.Cancel)) + ) + val _ = client.initialize() + + 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") 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..54e3328 --- /dev/null +++ b/client/src/test/scala/chimp/client/HttpTransportSpec.scala @@ -0,0 +1,42 @@ +package chimp.client + +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 +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 + + it should "POST a request and decode the response body" in: + val result = Json.obj("ok" -> Json.fromBoolean(true)) + val backend = SyncBackendStub.whenAnyRequest.thenRespondAdjust( + (JSONRPCMessage.Response(id = RequestId(1), result = result): JSONRPCMessage).asJson.noSpaces, + StatusCode.Ok + ) + + 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: + val backend = SyncBackendStub.whenAnyRequest.thenRespondAdjust("", StatusCode.Accepted) + 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 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 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/McpClientSpec.scala b/client/src/test/scala/chimp/client/McpClientSpec.scala new file mode 100644 index 0000000..d86f568 --- /dev/null +++ b/client/src/test/scala/chimp/client/McpClientSpec.scala @@ -0,0 +1,83 @@ +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.client4.{GenericRequest, StringBody} +import sttp.model.StatusCode +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") + + 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.name, + 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 client = McpClient[Identity](HttpTransport[Identity](backend, mcpUri), clientInfo) + val result = client.initialize() + result.protocolVersion shouldBe ProtocolVersion.Latest.name + result.serverInfo.name shouldBe "test-server" + + 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 callEnvelope = + (JSONRPCMessage.Response(id = RequestId(1), result = callResult.asJson): JSONRPCMessage).asJson.noSpaces + + 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 ex = intercept[McpProtocolException](client.listTools()) + ex.getMessage should include("Client not initialized") 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())) 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/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..e107b7e --- /dev/null +++ b/core/src/main/scala/chimp/protocol/Completion.scala @@ -0,0 +1,37 @@ +package chimp.protocol + +import io.circe.syntax.* +import io.circe.{Codec, Decoder, DecodingFailure, Encoder, Json} + +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 + +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..56d4af6 --- /dev/null +++ b/core/src/main/scala/chimp/protocol/Elicitation.scala @@ -0,0 +1,31 @@ +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 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..598e26e --- /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..ed859a1 --- /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: ProtocolVersion, + 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..8db10a3 --- /dev/null +++ b/core/src/main/scala/chimp/protocol/Prompts.scala @@ -0,0 +1,56 @@ +package chimp.protocol + +import io.circe.{Codec, Decoder, 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..829c4e7 --- /dev/null +++ b/core/src/main/scala/chimp/protocol/ProtocolVersion.scala @@ -0,0 +1,16 @@ +package chimp.protocol + +import io.circe.{Decoder, Encoder, Json} + +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(_.name == s) + def negotiate(requested: String): ProtocolVersion = from(requested).getOrElse(Latest) + + 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/main/scala/chimp/protocol/Resources.scala b/core/src/main/scala/chimp/protocol/Resources.scala new file mode 100644 index 0000000..59901de --- /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..4934942 --- /dev/null +++ b/core/src/main/scala/chimp/protocol/Tools.scala @@ -0,0 +1,135 @@ +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 +) + +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/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 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" + } + } +} + 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 16f8938..0000000 --- a/core/src/test/scala/chimp/protocol/ModelSpec.scala +++ /dev/null @@ -1,248 +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 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)) - 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 new file mode 100644 index 0000000..51d1a5b --- /dev/null +++ b/core/src/test/scala/chimp/protocol/SchemaConformanceSpec.scala @@ -0,0 +1,353 @@ +package chimp.protocol + +import com.networknt.schema.{InputFormat, SchemaRegistry, SpecificationVersion} +import io.circe.{Decoder, 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: 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(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 --- + + 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.name, + 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 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"))) + + // --- 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 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: + 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 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"))))) + + // --- 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 (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))) + ) + + // --- 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) 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 93% rename from examples/src/main/scala/chimp/AdderMcpZio.scala rename to examples/src/main/scala/chimp/server/AdderMcpZio.scala index c371329..52a0086 100644 --- a/examples/src/main/scala/chimp/AdderMcpZio.scala +++ b/examples/src/main/scala/chimp/server/AdderMcpZio.scala @@ -1,8 +1,8 @@ -//> 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 io.circe.Codec import sttp.tapir.* diff --git a/examples/src/main/scala/chimp/adderMcp.scala b/examples/src/main/scala/chimp/server/adderMcp.scala similarity index 90% rename from examples/src/main/scala/chimp/adderMcp.scala rename to examples/src/main/scala/chimp/server/adderMcp.scala index 7849a86..117642d 100644 --- a/examples/src/main/scala/chimp/adderMcp.scala +++ b/examples/src/main/scala/chimp/server/adderMcp.scala @@ -1,8 +1,8 @@ -//> 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 io.circe.Codec import sttp.tapir.* 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 ea93697..f548566 100644 --- a/examples/src/main/scala/chimp/adderWithAuthMcp.scala +++ b/examples/src/main/scala/chimp/server/adderWithAuthMcp.scala @@ -1,8 +1,8 @@ -//> 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 io.circe.Codec import sttp.model.Header diff --git a/examples/src/main/scala/chimp/twoToolsMcp.scala b/examples/src/main/scala/chimp/server/twoToolsMcp.scala similarity index 96% rename from examples/src/main/scala/chimp/twoToolsMcp.scala rename to examples/src/main/scala/chimp/server/twoToolsMcp.scala index f1aa04e..03a2fca 100644 --- a/examples/src/main/scala/chimp/twoToolsMcp.scala +++ b/examples/src/main/scala/chimp/server/twoToolsMcp.scala @@ -1,8 +1,8 @@ -//> 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 io.circe.Codec import sttp.tapir.* diff --git a/examples/src/main/scala/chimp/weatherMcp.scala b/examples/src/main/scala/chimp/server/weatherMcp.scala similarity index 98% rename from examples/src/main/scala/chimp/weatherMcp.scala rename to examples/src/main/scala/chimp/server/weatherMcp.scala index 08a8b8e..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.* import io.circe.Codec import io.circe.parser.decode import ox.either 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/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/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..64255f5 --- /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: + + 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") + .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/core/src/main/scala/chimp/McpHandler.scala b/server/src/main/scala/chimp/server/McpHandler.scala similarity index 73% rename from core/src/main/scala/chimp/McpHandler.scala rename to server/src/main/scala/chimp/server/McpHandler.scala index 1406ebb..c83ffe3 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.* @@ -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.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. */ @@ -92,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) => @@ -108,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. */ @@ -121,13 +119,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 +147,16 @@ 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 "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 - 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/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 85% rename from core/src/main/scala/chimp/tool.scala rename to server/src/main/scala/chimp/server/tool.scala index 3ad1f47..691a319 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 @@ -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/core/src/test/scala/chimp/McpHandlerSpec.scala b/server/src/test/scala/chimp/server/McpHandlerSpec.scala similarity index 74% rename from core/src/test/scala/chimp/McpHandlerSpec.scala rename to server/src/test/scala/chimp/server/McpHandlerSpec.scala index 2e9fa98..330b652 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 @@ -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") @@ -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: @@ -248,7 +247,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 +267,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 +282,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 +303,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 +326,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") @@ -460,43 +375,3 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: requiredFields should contain("requiredField") 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")