From db72eb4c328baf6967eb26bc690172b8bee472b0 Mon Sep 17 00:00:00 2001 From: Ondra Pelech Date: Thu, 19 Nov 2026 15:38:23 +0100 Subject: [PATCH 1/8] feat(T8): expose request facts to handlers and gate logs by _meta logLevel Add RequestInfo (protocol version, client capabilities, client info, log level, progress token) and expose it as ServerContext.request. The handler builds it once per request and passes it to the transport's context factory, which replaces the bare progress-token argument. A modern (2026-07-28) request takes all facts from _meta. A legacy request gives only the protocol version (header or _meta) and the progress token, because the server keeps no state from initialize. StreamingServerContext.log now follows the per-request log level of a modern request: it sends notifications/message only at or above _meta logLevel, and none when the request sets no level, as the 2026-07-28 spec requires. Legacy requests keep receiving all messages. --- .../scala/chimp/protocol/Versioning.scala | 1 + .../server/ox/OxServerStdioTransport.scala | 8 +-- .../pekko/PekkoServerStdioTransport.scala | 10 +-- .../server/zio/ZioServerStdioTransport.scala | 8 +-- .../main/scala/chimp/server/McpHandler.scala | 43 ++++++++---- .../scala/chimp/server/ServerContext.scala | 46 ++++++++++--- .../SecuredServerHttpTransport.scala | 2 +- .../SecuredServerStreamingHttpTransport.scala | 5 +- .../transport/ServerStdioTransport.scala | 6 +- .../ServerStreamingHttpTransport.scala | 5 +- .../scala/chimp/server/McpHandlerSpec.scala | 66 +++++++++++++++++++ 11 files changed, 155 insertions(+), 45 deletions(-) diff --git a/core/src/main/scala/chimp/protocol/Versioning.scala b/core/src/main/scala/chimp/protocol/Versioning.scala index 9a5cacb4..280260e0 100644 --- a/core/src/main/scala/chimp/protocol/Versioning.scala +++ b/core/src/main/scala/chimp/protocol/Versioning.scala @@ -18,6 +18,7 @@ object ProtocolMeta: val ProtocolVersionKey: String = "io.modelcontextprotocol/protocolVersion" val ClientInfo: String = "io.modelcontextprotocol/clientInfo" val ClientCapabilities: String = "io.modelcontextprotocol/clientCapabilities" + val LogLevel: String = "io.modelcontextprotocol/logLevel" val ServerInfo: String = "io.modelcontextprotocol/serverInfo" val SubscriptionId: String = "io.modelcontextprotocol/subscriptionId" diff --git a/server-streaming/server-ox/src/main/scala/chimp/server/ox/OxServerStdioTransport.scala b/server-streaming/server-ox/src/main/scala/chimp/server/ox/OxServerStdioTransport.scala index b52e692c..1492d751 100644 --- a/server-streaming/server-ox/src/main/scala/chimp/server/ox/OxServerStdioTransport.scala +++ b/server-streaming/server-ox/src/main/scala/chimp/server/ox/OxServerStdioTransport.scala @@ -1,8 +1,8 @@ package chimp.server.ox -import chimp.protocol.{JSONRPCMessage, ProgressToken} +import chimp.protocol.JSONRPCMessage import chimp.server.transport.ServerStreamingStdioTransport -import chimp.server.{McpHandler, OutboundSink, SinkStreamingServerContext, StreamingMcpServer, StreamingServerContext} +import chimp.server.{McpHandler, OutboundSink, RequestInfo, SinkStreamingServerContext, StreamingMcpServer, StreamingServerContext} import chimp.transport.{StdioFraming, StdioLineReader} import io.circe.syntax.* import io.circe.{parser, Json} @@ -39,8 +39,8 @@ final class OxServerStdioTransport( val sink = new OutboundSink[Identity]: def send(message: JSONRPCMessage): Unit = outbound.send(message.asJson.deepDropNullValues) - val makeContext: Option[ProgressToken] => StreamingServerContext[Identity] = - token => SinkStreamingServerContext(sink, token) + val makeContext: RequestInfo => StreamingServerContext[Identity] = + info => SinkStreamingServerContext(sink, info) reader.lines .filter(_.nonEmpty) diff --git a/server-streaming/server-pekko/src/main/scala/chimp/server/pekko/PekkoServerStdioTransport.scala b/server-streaming/server-pekko/src/main/scala/chimp/server/pekko/PekkoServerStdioTransport.scala index ccc840f1..d181bf86 100644 --- a/server-streaming/server-pekko/src/main/scala/chimp/server/pekko/PekkoServerStdioTransport.scala +++ b/server-streaming/server-pekko/src/main/scala/chimp/server/pekko/PekkoServerStdioTransport.scala @@ -1,8 +1,8 @@ package chimp.server.pekko -import chimp.protocol.{JSONRPCMessage, ProgressToken} +import chimp.protocol.JSONRPCMessage import chimp.server.transport.ServerStreamingStdioTransport -import chimp.server.{McpHandler, OutboundSink, SinkStreamingServerContext, StreamingMcpServer, StreamingServerContext} +import chimp.server.{McpHandler, OutboundSink, RequestInfo, SinkStreamingServerContext, StreamingMcpServer, StreamingServerContext} import chimp.transport.{McpLineTooLongException, StdioFraming} import io.circe.syntax.* import io.circe.{parser, Json} @@ -39,8 +39,8 @@ final class PekkoServerStdioTransport( val sink = new OutboundSink[Future]: def send(message: JSONRPCMessage): Future[Unit] = PekkoOutbound.offer(outbound, message.asJson.deepDropNullValues) - val makeContext: Option[ProgressToken] => StreamingServerContext[Future] = - token => SinkStreamingServerContext(sink, token) + val makeContext: RequestInfo => StreamingServerContext[Future] = + info => SinkStreamingServerContext(sink, info) val reading = StreamConverters .fromInputStream(() => in) @@ -57,7 +57,7 @@ final class PekkoServerStdioTransport( private def handleLine( handler: McpHandler[Future, StreamingServerContext[Future]], - makeContext: Option[ProgressToken] => StreamingServerContext[Future], + makeContext: RequestInfo => StreamingServerContext[Future], outbound: SourceQueueWithComplete[Json], line: String ): Future[Unit] = diff --git a/server-streaming/server-zio/src/main/scala/chimp/server/zio/ZioServerStdioTransport.scala b/server-streaming/server-zio/src/main/scala/chimp/server/zio/ZioServerStdioTransport.scala index dc3710ba..0c7cbefe 100644 --- a/server-streaming/server-zio/src/main/scala/chimp/server/zio/ZioServerStdioTransport.scala +++ b/server-streaming/server-zio/src/main/scala/chimp/server/zio/ZioServerStdioTransport.scala @@ -1,7 +1,7 @@ package chimp.server.zio -import chimp.protocol.{JSONRPCMessage, ProgressToken} -import chimp.server.{McpHandler, OutboundSink, SinkStreamingServerContext, StreamingMcpServer, StreamingServerContext} +import chimp.protocol.JSONRPCMessage +import chimp.server.{McpHandler, OutboundSink, RequestInfo, SinkStreamingServerContext, StreamingMcpServer, StreamingServerContext} import chimp.server.transport.ServerStreamingStdioTransport import chimp.transport.{StdioFraming, StdioLineReader} import io.circe.syntax.* @@ -36,8 +36,8 @@ final class ZioServerStdioTransport( val sink = new OutboundSink[Task]: def send(message: JSONRPCMessage): Task[Unit] = writeLine(message.asJson.deepDropNullValues) - val makeContext: Option[ProgressToken] => StreamingServerContext[Task] = - token => SinkStreamingServerContext(sink, token) + val makeContext: RequestInfo => StreamingServerContext[Task] = + info => SinkStreamingServerContext(sink, info) def loop: Task[Unit] = ZIO diff --git a/server/src/main/scala/chimp/server/McpHandler.scala b/server/src/main/scala/chimp/server/McpHandler.scala index 38b066dc..ebcdf93a 100644 --- a/server/src/main/scala/chimp/server/McpHandler.scala +++ b/server/src/main/scala/chimp/server/McpHandler.scala @@ -63,15 +63,15 @@ private[server] class McpHandler[F[_], C <: ServerContext[F]](server: McpServerD ) ) - def handleJsonRpc(request: Json, headers: Seq[Header], makeContext: Option[ProgressToken] => C)(using MonadError[F]): F[McpResponse] = + def handleJsonRpc(request: Json, headers: Seq[Header], makeContext: RequestInfo => C)(using MonadError[F]): F[McpResponse] = doHandleJsonRpc(request, headers, makeContext).map: response => logger.debug(s"Request: $request, response: ${response.statusCode}, body: ${response.body.getOrElse(Json.Null)}") response.withNullsDroppedDeep def handleJsonRpc(request: Json, headers: Seq[Header])(using m: MonadError[F], ev: ServerContext[F] <:< C): F[McpResponse] = - handleJsonRpc(request, headers, _ => ev(ServerContext.noop[F])) + handleJsonRpc(request, headers, info => ev(ServerContext[F](info))) - private def doHandleJsonRpc(request: Json, headers: Seq[Header], makeContext: Option[ProgressToken] => C)(using + private def doHandleJsonRpc(request: Json, headers: Seq[Header], makeContext: RequestInfo => C)(using MonadError[F] ): F[McpResponse] = request.as[JSONRPCMessage] match @@ -80,7 +80,10 @@ private[server] class McpHandler[F[_], C <: ServerContext[F]](server: McpServerD case Right(JSONRPCMessage.Request(_, method, params: Option[Json], id)) => requestRejection(method, params, headers, id) match case Some(rejection) => rejection.unit - case None => dispatch(method, params, id, headers, makeContext, isModernRequest(method, params, headers)) + case None => + val isModern = isModernRequest(method, params, headers) + val info = requestInfo(params, headers, isModern) + dispatch(method, params, id, headers, () => makeContext(info), isModern) case Right(notification: JSONRPCMessage.Notification) => logger.debug(s"Received notification: ${notification.method}") McpResponse.EmptyAcceptResponse.unit @@ -93,7 +96,7 @@ private[server] class McpHandler[F[_], C <: ServerContext[F]](server: McpServerD params: Option[Json], id: RequestId, headers: Seq[Header], - makeContext: Option[ProgressToken] => C, + makeContext: () => C, isModern: Boolean )(using MonadError[F]): F[McpResponse] = def wrap(cacheHints: Option[CacheHints])(message: JSONRPCMessage): JSONRPCMessage = message match @@ -180,6 +183,23 @@ private[server] class McpHandler[F[_], C <: ServerContext[F]](server: McpServerD val metaIsModern = metaVersion.exists(version => ProtocolVersion.from(version).forall(_.isModern)) method != "server/discover" && (metaIsModern || headerVersion.flatMap(ProtocolVersion.from).exists(_.isModern)) + /** The facts a handler can read about the request; see [[RequestInfo]]. */ + private def requestInfo(params: Option[Json], headers: Seq[Header], isModern: Boolean): RequestInfo = + val meta = params.flatMap(_.hcursor.downField("_meta").focus).map(_.hcursor) + def fromMeta[A: Decoder](key: String): Option[A] = meta.flatMap(_.get[A](key).toOption) + val headerVersion = headers.collectFirst { case h if h.name.equalsIgnoreCase(ProtocolMeta.ProtocolVersionHeader) => h.value.trim } + val progressToken = fromMeta[ProgressToken]("progressToken") + val protocolVersion = fromMeta[String](ProtocolMeta.ProtocolVersionKey).orElse(headerVersion).flatMap(ProtocolVersion.from) + if isModern then + RequestInfo( + protocolVersion = protocolVersion, + clientCapabilities = fromMeta[ClientCapabilities](ProtocolMeta.ClientCapabilities), + clientInfo = fromMeta[Implementation](ProtocolMeta.ClientInfo), + logLevel = fromMeta[LoggingLevel](ProtocolMeta.LogLevel), + progressToken = progressToken + ) + else RequestInfo(protocolVersion = protocolVersion, progressToken = progressToken) + /** The rejection to send for an invalid request, or `None` if it may be dispatched. Runs no tool logic, so a transport can call it before * deciding how to respond (a modern validation error is a plain-JSON HTTP error, not an SSE stream). */ @@ -289,19 +309,18 @@ private[server] class McpHandler[F[_], C <: ServerContext[F]](server: McpServerD private def handleDiscover(id: RequestId): JSONRPCMessage.Response = JSONRPCMessage.Response(id = id, result = discoverResult.asJson) - private def handleToolsCall(params: Option[Json], id: RequestId, headers: Seq[Header], makeContext: Option[ProgressToken] => C)(using + private def handleToolsCall(params: Option[Json], id: RequestId, headers: Seq[Header], makeContext: () => C)(using MonadError[F] ): F[JSONRPCMessage] = val name = params.flatMap(_.hcursor.downField("name").as[String].toOption) val arguments = params.flatMap(_.hcursor.downField("arguments").focus).getOrElse(Json.obj()) - val progressToken = params.flatMap(_.hcursor.downField("_meta").downField("progressToken").as[ProgressToken].toOption) name match case Some(name) => toolsByName.get(name) match case Some(tool) => tool.inputDecoder.decodeJson(arguments) match case Right(input) => - val context = makeContext(progressToken) + val context = makeContext() tool .logic(input, context, headers) .map: result => @@ -335,10 +354,10 @@ private[server] class McpHandler[F[_], C <: ServerContext[F]](server: McpServerD params: Option[Json], id: RequestId, headers: Seq[Header], - makeContext: Option[ProgressToken] => C + makeContext: () => C )(using MonadError[F]): F[JSONRPCMessage] = decodeParams[ReadResourceParams](params, id): params => - val context = makeContext(None) + val context = makeContext() resourcesByUri.get(params.uri) match case Some(resource) => resource.read(context, headers).map(resourceReadResponse(id, params.uri)) case None => @@ -383,13 +402,13 @@ private[server] class McpHandler[F[_], C <: ServerContext[F]](server: McpServerD params: Option[Json], id: RequestId, headers: Seq[Header], - makeContext: Option[ProgressToken] => C + makeContext: () => C )(using MonadError[F]): F[JSONRPCMessage] = decodeParams[GetPromptParams](params, id): params => promptsByName.get(params.name) match case Some(prompt) => prompt - .logic(params.arguments.getOrElse(Map.empty), makeContext(None), headers) + .logic(params.arguments.getOrElse(Map.empty), makeContext(), headers) .map(promptResult => JSONRPCMessage.Response(id = id, result = promptResult.asJson)) case None => protocolError(id, JSONRPCErrorCodes.InvalidParams.code, s"Unknown prompt: ${params.name}").unit diff --git a/server/src/main/scala/chimp/server/ServerContext.scala b/server/src/main/scala/chimp/server/ServerContext.scala index ebcfa603..3a73c975 100644 --- a/server/src/main/scala/chimp/server/ServerContext.scala +++ b/server/src/main/scala/chimp/server/ServerContext.scala @@ -5,28 +5,52 @@ import io.circe.Json import io.circe.syntax.* import sttp.monad.MonadError -trait ServerContext[F[_]] +/** What a request tells about itself. A modern (2026-07-28+) request carries all of it in `_meta`. A legacy request gives only the protocol + * version (from the `MCP-Protocol-Version` header or `_meta`) and the progress token; the server keeps no state from `initialize`. + */ +final case class RequestInfo( + protocolVersion: Option[ProtocolVersion] = None, + clientCapabilities: Option[ClientCapabilities] = None, + clientInfo: Option[Implementation] = None, + logLevel: Option[LoggingLevel] = None, + progressToken: Option[ProgressToken] = None +): + /** A modern request gets `notifications/message` only at or above its `logLevel`, and none without one. A legacy request gets all. */ + private[server] def allowsLog(level: LoggingLevel): Boolean = + if protocolVersion.exists(_.isModern) then logLevel.exists(minimum => level.ordinal >= minimum.ordinal) else true + +object RequestInfo: + val empty: RequestInfo = RequestInfo() + +trait ServerContext[F[_]]: + def request: RequestInfo object ServerContext: - def noop[F[_]]: ServerContext[F] = new ServerContext[F] {} + def noop[F[_]]: ServerContext[F] = apply(RequestInfo.empty) + + private[server] def apply[F[_]](info: RequestInfo): ServerContext[F] = new ServerContext[F]: + def request: RequestInfo = info /** A context which also gives the principal that the security logic of a [[SecuredMcpServer]] made from the request. */ trait SecuredServerContext[F[_], +P] extends ServerContext[F]: def principal: P object SecuredServerContext: - def apply[F[_], P](value: P): SecuredServerContext[F, P] = new SecuredServerContext[F, P]: + def apply[F[_], P](value: P, info: RequestInfo = RequestInfo.empty): SecuredServerContext[F, P] = new SecuredServerContext[F, P]: def principal: P = value + def request: RequestInfo = info trait StreamingServerContext[F[_]] extends ServerContext[F]: def reportProgress(progress: Double, total: Option[Double] = None, message: Option[String] = None): F[Unit] + + /** Sends `notifications/message`. For a modern request it sends only at or above the request's `logLevel`, and nothing without one. */ def log(level: LoggingLevel, data: Json, logger: Option[String] = None): F[Unit] -private[server] final class SinkStreamingServerContext[F[_]](sink: OutboundSink[F], progressToken: Option[ProgressToken])(using +private[server] final class SinkStreamingServerContext[F[_]](sink: OutboundSink[F], val request: RequestInfo)(using m: MonadError[F] ) extends StreamingServerContext[F]: def reportProgress(progress: Double, total: Option[Double] = None, message: Option[String] = None): F[Unit] = - progressToken match + request.progressToken match case Some(token) => sink.send( JSONRPCMessage.Notification( @@ -37,9 +61,11 @@ private[server] final class SinkStreamingServerContext[F[_]](sink: OutboundSink[ case None => m.unit(()) def log(level: LoggingLevel, data: Json, logger: Option[String] = None): F[Unit] = - sink.send( - JSONRPCMessage.Notification(method = "notifications/message", params = Some(LoggingMessageParams(level, data, logger).asJson)) - ) + if request.allowsLog(level) then + sink.send( + JSONRPCMessage.Notification(method = "notifications/message", params = Some(LoggingMessageParams(level, data, logger).asJson)) + ) + else m.unit(()) /** A context which gives both the principal that the security logic of a [[SecuredMcpServer]] made from the request, and the streaming * capabilities of a [[StreamingServerContext]]. @@ -48,11 +74,11 @@ trait SecuredStreamingServerContext[F[_], +P] extends SecuredServerContext[F, P] private[server] final class SinkSecuredStreamingServerContext[F[_], P]( sink: OutboundSink[F], - progressToken: Option[ProgressToken], + val request: RequestInfo, val principal: P )(using MonadError[F]) extends SecuredStreamingServerContext[F, P]: - private val delegate = SinkStreamingServerContext[F](sink, progressToken) + private val delegate = SinkStreamingServerContext[F](sink, request) def reportProgress(progress: Double, total: Option[Double] = None, message: Option[String] = None): F[Unit] = delegate.reportProgress(progress, total, message) def log(level: LoggingLevel, data: Json, logger: Option[String] = None): F[Unit] = delegate.log(level, data, logger) diff --git a/server/src/main/scala/chimp/server/transport/SecuredServerHttpTransport.scala b/server/src/main/scala/chimp/server/transport/SecuredServerHttpTransport.scala index ebc452f9..a317b178 100644 --- a/server/src/main/scala/chimp/server/transport/SecuredServerHttpTransport.scala +++ b/server/src/main/scala/chimp/server/transport/SecuredServerHttpTransport.scala @@ -35,7 +35,7 @@ final case class SecuredServerHttpTransport[F[_], S, E, P](path: List[String]): val (headers, json) = input given MonadError[F] = me respondToJsonRpc(server.originCheck, headers) { - handler.handleJsonRpc(json, headers, _ => SecuredServerContext[F, P](principal)) + handler.handleJsonRpc(json, headers, info => SecuredServerContext[F, P](principal, info)) }.map(Right(_)) } ) diff --git a/server/src/main/scala/chimp/server/transport/SecuredServerStreamingHttpTransport.scala b/server/src/main/scala/chimp/server/transport/SecuredServerStreamingHttpTransport.scala index 5ba0d740..16d0df5c 100644 --- a/server/src/main/scala/chimp/server/transport/SecuredServerStreamingHttpTransport.scala +++ b/server/src/main/scala/chimp/server/transport/SecuredServerStreamingHttpTransport.scala @@ -1,6 +1,5 @@ package chimp.server.transport -import chimp.protocol.ProgressToken import chimp.server.* import io.circe.Json import sttp.model.Header @@ -46,8 +45,8 @@ final case class SecuredServerStreamingHttpTransport[F[_], Caps, S, E, P]( val (headers, json) = input given MonadError[F] = me respondWithEventStream(server.originCheck, headers, backend, handler.validateRequest(json, headers)) { sink => - val makeContext: Option[ProgressToken] => SecuredStreamingServerContext[F, P] = - token => SinkSecuredStreamingServerContext(sink, token, principal) + val makeContext: RequestInfo => SecuredStreamingServerContext[F, P] = + info => SinkSecuredStreamingServerContext(sink, info, principal) handler.handleJsonRpc(json, headers, makeContext).map(_.body) }.map(_.left.map(Right(_))) } diff --git a/server/src/main/scala/chimp/server/transport/ServerStdioTransport.scala b/server/src/main/scala/chimp/server/transport/ServerStdioTransport.scala index 619b91d2..cd4da85c 100644 --- a/server/src/main/scala/chimp/server/transport/ServerStdioTransport.scala +++ b/server/src/main/scala/chimp/server/transport/ServerStdioTransport.scala @@ -1,6 +1,6 @@ package chimp.server.transport -import chimp.protocol.{JSONRPCMessage, ProgressToken} +import chimp.protocol.JSONRPCMessage import chimp.server.* import chimp.transport.{StdioFraming, StdioLineReader} import io.circe.parser @@ -49,8 +49,8 @@ final class ServerStdioTransport( val sink = new OutboundSink[Identity]: def send(message: JSONRPCMessage): Identity[Unit] = writeLine(message.asJson.deepDropNullValues) - val makeContext: Option[ProgressToken] => StreamingServerContext[Identity] = - token => SinkStreamingServerContext(sink, token) + val makeContext: RequestInfo => StreamingServerContext[Identity] = + info => SinkStreamingServerContext(sink, info) reader.lines .filter(_.nonEmpty) diff --git a/server/src/main/scala/chimp/server/transport/ServerStreamingHttpTransport.scala b/server/src/main/scala/chimp/server/transport/ServerStreamingHttpTransport.scala index d6529d44..cadf6428 100644 --- a/server/src/main/scala/chimp/server/transport/ServerStreamingHttpTransport.scala +++ b/server/src/main/scala/chimp/server/transport/ServerStreamingHttpTransport.scala @@ -1,6 +1,5 @@ package chimp.server.transport -import chimp.protocol.ProgressToken import chimp.server.* import io.circe.Json import sttp.capabilities.Streams @@ -45,8 +44,8 @@ abstract class ServerStreamingHttpTransport[F[_], Caps](path: List[String]) exte val (headers, json) = input given MonadError[F] = me respondWithEventStream(server.originCheck, headers, this, handler.validateRequest(json, headers)) { sink => - val makeContext: Option[ProgressToken] => StreamingServerContext[F] = - token => SinkStreamingServerContext(sink, token) + val makeContext: RequestInfo => StreamingServerContext[F] = + info => SinkStreamingServerContext(sink, info) handler.handleJsonRpc(json, headers, makeContext).map(_.body) } } diff --git a/server/src/test/scala/chimp/server/McpHandlerSpec.scala b/server/src/test/scala/chimp/server/McpHandlerSpec.scala index 5770649d..459a8137 100644 --- a/server/src/test/scala/chimp/server/McpHandlerSpec.scala +++ b/server/src/test/scala/chimp/server/McpHandlerSpec.scala @@ -697,3 +697,69 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: featureResult("resources/subscribe", Some(params), "n1") match case Error(_, _, error) => error.code shouldBe MethodNotFound.code case _ => fail("Expected Error") + + private val seenRequest = new java.util.concurrent.atomic.AtomicReference(Option.empty[RequestInfo]) + + private val loggingTool = tool("logs") + .input[EchoInput] + .streamingServerLogic[Identity]: (_, ctx, _) => + seenRequest.set(Some(ctx.request)) + LoggingLevel.values.foreach(level => ctx.log(level, Json.fromString(level.toString))) + ToolResult.text("logged") + + private val streamingHandler = + McpHandler[Identity, StreamingServerContext[Identity]](McpServer[Identity]().streaming.addStreamingTool(loggingTool)) + + private def callLoggingTool(meta: Json, headers: Seq[Header] = Seq.empty): (McpResponse, List[LoggingLevel]) = + val sent = scala.collection.mutable.ListBuffer.empty[JSONRPCMessage] + val sink = new OutboundSink[Identity]: + def send(message: JSONRPCMessage): Unit = sent += message + val params = Json.obj("name" -> Json.fromString("logs"), "arguments" -> Json.obj("message" -> Json.fromString("hi")), "_meta" -> meta) + val req: JSONRPCMessage = Request(method = "tools/call", params = Some(params), id = RequestId("log")) + val response = streamingHandler.handleJsonRpc(req.asJson, headers, info => SinkStreamingServerContext(sink, info)) + val levels = sent.toList.collect { case Notification(_, "notifications/message", Some(p)) => + p.as[LoggingMessageParams].toOption.get.level + } + (response, levels) + + private def modernToolMeta(extra: (String, Json)*): Json = + Json.obj( + (ProtocolMeta.ProtocolVersionKey -> Json.fromString("2026-07-28")) +: + (ProtocolMeta.ClientCapabilities -> Json.obj("sampling" -> Json.obj())) +: + extra* + ) + + it should "give a handler the facts of a modern request" in: + val clientInfo = Json.obj("name" -> Json.fromString("cli"), "version" -> Json.fromString("1.2")) + val meta = modernToolMeta( + ProtocolMeta.ClientInfo -> clientInfo, + ProtocolMeta.LogLevel -> Json.fromString("warning"), + "progressToken" -> Json.fromString("p1") + ) + callLoggingTool(meta)._1.statusCode shouldBe sttp.model.StatusCode.Ok + seenRequest.get() shouldBe Some( + RequestInfo( + protocolVersion = Some(ProtocolVersion.V2026_07_28), + clientCapabilities = Some(ClientCapabilities(sampling = Some(Json.obj()))), + clientInfo = Some(Implementation("cli", "1.2")), + logLevel = Some(LoggingLevel.Warning), + progressToken = Some(ProgressToken("p1")) + ) + ) + + it should "give a handler only the protocol version and progress token of a legacy request" in: + val meta = Json.obj("progressToken" -> Json.fromString("p2"), ProtocolMeta.LogLevel -> Json.fromString("debug")) + callLoggingTool(meta, Seq(Header(ProtocolMeta.ProtocolVersionHeader, "2025-11-25")))._1.statusCode shouldBe sttp.model.StatusCode.Ok + seenRequest.get() shouldBe Some( + RequestInfo(protocolVersion = Some(ProtocolVersion.V2025_11_25), progressToken = Some(ProgressToken("p2"))) + ) + + it should "send no log messages for a modern request without a logLevel" in: + callLoggingTool(modernToolMeta())._2 shouldBe Nil + + it should "send only log messages at or above the logLevel of a modern request" in: + callLoggingTool(modernToolMeta(ProtocolMeta.LogLevel -> Json.fromString("error")))._2 shouldBe + List(LoggingLevel.Error, LoggingLevel.Critical, LoggingLevel.Alert, LoggingLevel.Emergency) + + it should "send all log messages for a legacy request" in: + callLoggingTool(Json.obj())._2 shouldBe LoggingLevel.values.toList From 075616384e1ec9bacda75d1bbc7aff759c0b2520 Mon Sep 17 00:00:00 2001 From: Ondra Pelech Date: Thu, 19 Nov 2026 15:39:24 +0100 Subject: [PATCH 2/8] feat(T8): let plain tool, prompt and resource logic read the server context Add serverLogicWithContext to tools, prompts, resources and resource templates. The logic receives the ServerContext, so it can read the request facts (protocol version, client capabilities, client info, log level) without a streaming server. Until now only streaming tools got a context. --- .../src/main/scala/chimp/server/Prompt.scala | 6 ++++ .../main/scala/chimp/server/Resource.scala | 12 +++++++ server/src/main/scala/chimp/server/Tool.scala | 4 +++ .../scala/chimp/server/McpHandlerSpec.scala | 34 +++++++++++++++++++ 4 files changed, 56 insertions(+) diff --git a/server/src/main/scala/chimp/server/Prompt.scala b/server/src/main/scala/chimp/server/Prompt.scala index fa3264ca..5ad4eec0 100644 --- a/server/src/main/scala/chimp/server/Prompt.scala +++ b/server/src/main/scala/chimp/server/Prompt.scala @@ -38,6 +38,12 @@ case class PartialPrompt( ): ServerPrompt[F, ServerContext[F]] = ServerPrompt(definition, (args, _, headers) => logic(args, headers)) + /** Attaches effectful logic, with access to the [[ServerContext]], which gives the facts of the request. */ + def serverLogicWithContext[F[_]]( + logic: (Map[String, String], ServerContext[F], Seq[Header]) => F[GetPromptResult] + ): ServerPrompt[F, ServerContext[F]] = + ServerPrompt(definition, logic) + /** Attaches effectful logic, with access to the principal; usable only on a [[SecuredMcpServer]]. */ def securedServerLogic[F[_], P]( logic: (Map[String, String], P, Seq[Header]) => F[GetPromptResult] diff --git a/server/src/main/scala/chimp/server/Resource.scala b/server/src/main/scala/chimp/server/Resource.scala index ad645a61..57d001b9 100644 --- a/server/src/main/scala/chimp/server/Resource.scala +++ b/server/src/main/scala/chimp/server/Resource.scala @@ -54,6 +54,12 @@ case class PartialResource( ): ServerResource[F, ServerContext[F]] = ServerResource(definition, (_, headers) => logic(headers)) + /** Attaches effectful logic, with access to the [[ServerContext]], which gives the facts of the request. */ + def serverLogicWithContext[F[_]]( + logic: (ServerContext[F], Seq[Header]) => F[Either[ResourceError, List[ResourceContents]]] + ): ServerResource[F, ServerContext[F]] = + ServerResource(definition, logic) + /** Attaches effectful logic, with access to the principal; usable only on a [[SecuredMcpServer]]. */ def securedServerLogic[F[_], P]( logic: (P, Seq[Header]) => F[Either[ResourceError, List[ResourceContents]]] @@ -120,6 +126,12 @@ case class PartialResourceTemplate( ): ServerResourceTemplate[F, ServerContext[F]] = ServerResourceTemplate(definition, UriTemplate.compile(uriTemplate), (vars, uri, _, headers) => logic(vars, uri, headers)) + /** Attaches effectful logic reading a matched URI, with access to the [[ServerContext]], which gives the facts of the request. */ + def serverLogicWithContext[F[_]]( + logic: (Map[String, String], String, ServerContext[F], Seq[Header]) => F[Either[ResourceError, List[ResourceContents]]] + ): ServerResourceTemplate[F, ServerContext[F]] = + ServerResourceTemplate(definition, UriTemplate.compile(uriTemplate), logic) + /** Attaches effectful logic, with access to the principal; usable only on a [[SecuredMcpServer]]. */ def securedServerLogic[F[_], P]( logic: (Map[String, String], String, P, Seq[Header]) => F[Either[ResourceError, List[ResourceContents]]] diff --git a/server/src/main/scala/chimp/server/Tool.scala b/server/src/main/scala/chimp/server/Tool.scala index e6aecd3b..8f3937e9 100644 --- a/server/src/main/scala/chimp/server/Tool.scala +++ b/server/src/main/scala/chimp/server/Tool.scala @@ -103,6 +103,10 @@ case class Tool[I, O]( def serverLogic[F[_]](logic: (I, Seq[Header]) => F[ToolResult[O]]): ServerTool[I, O, F, ServerContext[F]] = ServerTool(name, description, inputSchema, inputDecoder, outputSchema, annotations, (input, _, headers) => logic(input, headers)) + /** Attaches effectful logic, with access to the [[ServerContext]], which gives the facts of the request. */ + def serverLogicWithContext[F[_]](logic: (I, ServerContext[F], Seq[Header]) => F[ToolResult[O]]): ServerTool[I, O, F, ServerContext[F]] = + ServerTool(name, description, inputSchema, inputDecoder, outputSchema, annotations, logic) + /** Attaches effectful logic, with access to the principal; usable only on a [[SecuredMcpServer]]. */ def securedServerLogic[F[_], P](logic: (I, P, Seq[Header]) => F[ToolResult[O]]): ServerTool[I, O, F, SecuredServerContext[F, P]] = ServerTool( diff --git a/server/src/test/scala/chimp/server/McpHandlerSpec.scala b/server/src/test/scala/chimp/server/McpHandlerSpec.scala index 459a8137..34a26e1b 100644 --- a/server/src/test/scala/chimp/server/McpHandlerSpec.scala +++ b/server/src/test/scala/chimp/server/McpHandlerSpec.scala @@ -763,3 +763,37 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: it should "send all log messages for a legacy request" in: callLoggingTool(Json.obj())._2 shouldBe LoggingLevel.values.toList + + private def describe(ctx: ServerContext[Identity]): String = + s"${ctx.request.protocolVersion.map(_.name).getOrElse("-")} ${ctx.request.clientInfo.map(_.name).getOrElse("-")}" + + private val contextServer = McpServer[Identity]() + .addTool(tool("ctx").input[EchoInput].serverLogicWithContext[Identity]((_, ctx, _) => ToolResult.text(describe(ctx)))) + .addPrompt( + prompt("ctx").serverLogicWithContext[Identity]((_, ctx, _) => + GetPromptResult(messages = List(PromptMessage(Role.User, ToolContent.Text(text = describe(ctx))))) + ) + ) + .addResource( + resource("test://ctx").serverLogicWithContext[Identity]((ctx, _) => Right(List(ResourceContents.Text("test://ctx", describe(ctx))))) + ) + .addResourceTemplate( + resourceTemplate("test://ctx/{id}") + .serverLogicWithContext[Identity]((_, uri, ctx, _) => Right(List(ResourceContents.Text(uri, describe(ctx))))) + ) + + it should "give the request facts to tool, prompt, resource and resource template logic" in: + val meta = Json.obj( + "_meta" -> modernToolMeta(ProtocolMeta.ClientInfo -> Json.obj("name" -> Json.fromString("cli"), "version" -> Json.fromString("1"))) + ) + val calls = List( + "tools/call" -> Json.obj("name" -> Json.fromString("ctx"), "arguments" -> Json.obj("message" -> Json.fromString("hi"))), + "prompts/get" -> Json.obj("name" -> Json.fromString("ctx")), + "resources/read" -> Json.obj("uri" -> Json.fromString("test://ctx")), + "resources/read" -> Json.obj("uri" -> Json.fromString("test://ctx/1")) + ) + for (method, params) <- calls do + val req: JSONRPCMessage = Request(method = method, params = Some(params.deepMerge(meta)), id = RequestId("ctx")) + val body = extractJsonFromResponse(McpHandler(contextServer).handleJsonRpc(req.asJson, Seq.empty)) + withClue(s"$method $params"): + body.noSpaces should include("2026-07-28 cli") From 26b89cab923b87858277f0485c371ed4873525b7 Mon Sep 17 00:00:00 2001 From: Ondra Pelech Date: Thu, 19 Nov 2026 15:42:17 +0100 Subject: [PATCH 3/8] feat(T8): reject modern tool calls missing a required client capability A tool can now declare the client capabilities it needs with withRequiredClientCapabilities. When a modern (2026-07-28) tools/call targets such a tool and _meta clientCapabilities does not declare them, the request fails before any logic runs with -32021 MissingRequiredClientCapability, HTTP 400, and data.requiredCapabilities set to the tool's requirement, as the schema requires. The check runs in requestRejection, so a streaming transport answers with plain JSON and not an SSE stream. Capabilities are compared key by key, recursively for nested objects. Legacy requests carry no capabilities, so they are not checked. --- .../scala/chimp/protocol/Versioning.scala | 8 +++ .../main/scala/chimp/server/McpHandler.scala | 27 ++++++- server/src/main/scala/chimp/server/Tool.scala | 72 +++++++++++-------- .../scala/chimp/server/McpHandlerSpec.scala | 49 +++++++++++++ 4 files changed, 123 insertions(+), 33 deletions(-) diff --git a/core/src/main/scala/chimp/protocol/Versioning.scala b/core/src/main/scala/chimp/protocol/Versioning.scala index 280260e0..7600a3c6 100644 --- a/core/src/main/scala/chimp/protocol/Versioning.scala +++ b/core/src/main/scala/chimp/protocol/Versioning.scala @@ -30,6 +30,14 @@ object ProtocolMeta: data = Some(Json.obj("requested" -> requested.asJson, "supported" -> supported.asJson)) ) + /** A `MissingRequiredClientCapability` error (`-32021`) naming the capabilities the client must declare to make the request. */ + def missingClientCapabilityError(required: ClientCapabilities): JSONRPCErrorObject = + JSONRPCErrorObject( + code = JSONRPCErrorCodes.MissingRequiredClientCapability.code, + message = "Missing required client capability", + data = Some(Json.obj("requiredCapabilities" -> required.asJson.deepDropNullValues)) + ) + /** The type of a modern (2026-07-28+) result: `complete` for a finished result, `incomplete` for one that needs another round trip (MRTR * input-required). */ diff --git a/server/src/main/scala/chimp/server/McpHandler.scala b/server/src/main/scala/chimp/server/McpHandler.scala index ebcdf93a..86508012 100644 --- a/server/src/main/scala/chimp/server/McpHandler.scala +++ b/server/src/main/scala/chimp/server/McpHandler.scala @@ -251,10 +251,31 @@ private[server] class McpHandler[F[_], C <: ServerContext[F]](server: McpServerD ) else if !modernMethods.contains(method) then Some(jsonError(id, StatusCode.NotFound, JSONRPCErrorCodes.MethodNotFound.code, s"Method not found: $method")) - else if headers.exists(_.name.equalsIgnoreCase("Host")) then + else // SEP-2243 standard request headers only apply over HTTP (identified by the Host header); stdio carries no such headers - headerValidationError(method, params, headers, id) - else None + val headerError = Option.when(headers.exists(_.name.equalsIgnoreCase("Host")))(headerValidationError(method, params, headers, id)) + headerError.flatten.orElse(missingCapabilityError(method, params, meta, id)) + + /** A `-32021` with HTTP 400 when `tools/call` names a tool whose required client capabilities the request's `_meta` does not declare. */ + private def missingCapabilityError(method: String, params: Option[Json], meta: Option[Json], id: RequestId): Option[McpResponse] = + val declared = meta.flatMap(_.hcursor.downField(ProtocolMeta.ClientCapabilities).focus).getOrElse(Json.obj()) + val required = Option + .when(method == "tools/call")(params.flatMap(_.hcursor.get[String]("name").toOption)) + .flatten + .flatMap(toolsByName.get) + .flatMap(_.requiredClientCapabilities) + required + .filterNot(capabilities => declares(declared, capabilities.asJson.deepDropNullValues)) + .map: capabilities => + val envelope: JSONRPCMessage = JSONRPCMessage.Error(id = id, error = ProtocolMeta.missingClientCapabilityError(capabilities)) + logger.debug(s"Modern request rejected (id=$id): missing client capabilities ${capabilities.asJson.noSpaces}") + McpResponse.JsonError(StatusCode.BadRequest, envelope.asJson) + + /** Whether `declared` has every key of `required`, recursively for nested objects. */ + private def declares(declared: Json, required: Json): Boolean = + required.asObject.forall(_.toList.forall { (key, value) => + declared.asObject.flatMap(_(key)).exists(declaredValue => value.asObject.forall(_ => declares(declaredValue, value))) + }) // SEP-2243: the body field that the `Mcp-Name` header must mirror, per method private val nameFields: Map[String, String] = Map("tools/call" -> "name", "prompts/get" -> "name", "resources/read" -> "uri") diff --git a/server/src/main/scala/chimp/server/Tool.scala b/server/src/main/scala/chimp/server/Tool.scala index 8f3937e9..ca68baef 100644 --- a/server/src/main/scala/chimp/server/Tool.scala +++ b/server/src/main/scala/chimp/server/Tool.scala @@ -1,6 +1,6 @@ package chimp.server -import chimp.protocol.{ResourceContents, ToolContent} +import chimp.protocol.{ClientCapabilities, ResourceContents, ToolContent} import io.circe.syntax.* import io.circe.{Decoder, Encoder, Json} import sttp.model.Header @@ -66,7 +66,8 @@ def tool(name: String): PartialTool = case class PartialTool( name: String, description: Option[String] = None, - annotations: Option[ToolAnnotations] = None + annotations: Option[ToolAnnotations] = None, + requiredClientCapabilities: Option[ClientCapabilities] = None ): def description(desc: String): PartialTool = copy(description = Some(desc)) @@ -74,13 +75,35 @@ case class PartialTool( def withAnnotations(ann: ToolAnnotations): PartialTool = copy(annotations = Some(ann)) + /** Declares the client capabilities a call needs. A modern (2026-07-28+) request whose `_meta` does not declare them fails with `-32021` + * (MissingRequiredClientCapability) before the logic runs. + */ + def withRequiredClientCapabilities(capabilities: ClientCapabilities): PartialTool = + copy(requiredClientCapabilities = Some(capabilities)) + /** Fixes the input type, deriving its JSON Schema and decoder from the given instances. */ def input[I: Schema: Decoder]: Tool[I, NoStructuredOutput] = - Tool[I, NoStructuredOutput](name, description, ToolSchema.Derived(summon[Schema[I]]), summon[Decoder[I]], None, annotations) + Tool[I, NoStructuredOutput]( + name, + description, + ToolSchema.Derived(summon[Schema[I]]), + summon[Decoder[I]], + None, + annotations, + requiredClientCapabilities + ) /** Fixes the input as raw JSON, validated against the given JSON Schema. */ def inputJson(schema: Json): Tool[Json, NoStructuredOutput] = - Tool[Json, NoStructuredOutput](name, description, ToolSchema.Raw(schema), summon[Decoder[Json]], None, annotations) + Tool[Json, NoStructuredOutput]( + name, + description, + ToolSchema.Raw(schema), + summon[Decoder[Json]], + None, + annotations, + requiredClientCapabilities + ) /** A tool with a known input type `I` and structured output type `O`, ready to be given its handling logic. */ case class Tool[I, O]( @@ -89,60 +112,45 @@ case class Tool[I, O]( inputSchema: ToolSchema, inputDecoder: Decoder[I], outputSchema: Option[ToolSchema], - annotations: Option[ToolAnnotations] + annotations: Option[ToolAnnotations], + requiredClientCapabilities: Option[ClientCapabilities] = None ): /** Fixes the structured output type, deriving its JSON Schema from the given instance. */ def output[O2: Schema]: Tool[I, O2] = - Tool[I, O2](name, description, inputSchema, inputDecoder, Some(ToolSchema.Derived(summon[Schema[O2]])), annotations) + copy(outputSchema = Some(ToolSchema.Derived(summon[Schema[O2]]))) /** Fixes the structured output as raw JSON, described by the given JSON Schema. */ def outputJson(schema: Json): Tool[I, Json] = - Tool[I, Json](name, description, inputSchema, inputDecoder, Some(ToolSchema.Raw(schema)), annotations) + copy(outputSchema = Some(ToolSchema.Raw(schema))) /** Attaches effectful logic, with access to the request headers. */ def serverLogic[F[_]](logic: (I, Seq[Header]) => F[ToolResult[O]]): ServerTool[I, O, F, ServerContext[F]] = - ServerTool(name, description, inputSchema, inputDecoder, outputSchema, annotations, (input, _, headers) => logic(input, headers)) + serverTool((input, _, headers) => logic(input, headers)) /** Attaches effectful logic, with access to the [[ServerContext]], which gives the facts of the request. */ def serverLogicWithContext[F[_]](logic: (I, ServerContext[F], Seq[Header]) => F[ToolResult[O]]): ServerTool[I, O, F, ServerContext[F]] = - ServerTool(name, description, inputSchema, inputDecoder, outputSchema, annotations, logic) + serverTool(logic) /** Attaches effectful logic, with access to the principal; usable only on a [[SecuredMcpServer]]. */ def securedServerLogic[F[_], P](logic: (I, P, Seq[Header]) => F[ToolResult[O]]): ServerTool[I, O, F, SecuredServerContext[F, P]] = - ServerTool( - name, - description, - inputSchema, - inputDecoder, - outputSchema, - annotations, - (input, context, headers) => logic(input, context.principal, headers) - ) + serverTool((input, context, headers) => logic(input, context.principal, headers)) /** Attaches effectful logic with access to the [[StreamingServerContext]]; usable only on a streaming server. */ def streamingServerLogic[F[_]]( logic: (I, StreamingServerContext[F], Seq[Header]) => F[ToolResult[O]] ): ServerTool[I, O, F, StreamingServerContext[F]] = - ServerTool(name, description, inputSchema, inputDecoder, outputSchema, annotations, logic) + serverTool(logic) /** Attaches effectful logic with access to the principal and the [[StreamingServerContext]]; usable only on a secured streaming server. */ def securedStreamingServerLogic[F[_], P]( logic: (I, P, StreamingServerContext[F], Seq[Header]) => F[ToolResult[O]] ): ServerTool[I, O, F, SecuredStreamingServerContext[F, P]] = - ServerTool( - name, - description, - inputSchema, - inputDecoder, - outputSchema, - annotations, - (input, context, headers) => logic(input, context.principal, context, headers) - ) + serverTool((input, context, headers) => logic(input, context.principal, context, headers)) /** Attaches synchronous logic that also receives the request headers. */ def handleWithHeaders(logic: (I, Seq[Header]) => ToolResult[O]): ServerTool[I, O, Identity, ServerContext[Identity]] = - ServerTool(name, description, inputSchema, inputDecoder, outputSchema, annotations, (i, _, headers) => logic(i, headers)) + serverTool((i, _, headers) => logic(i, headers)) /** Attaches synchronous logic over just the decoded input. */ def handle(logic: I => ToolResult[O]): ServerTool[I, O, Identity, ServerContext[Identity]] = @@ -152,6 +160,9 @@ case class Tool[I, O]( def handleSecured[P](logic: (I, P) => ToolResult[O]): ServerTool[I, O, Identity, SecuredServerContext[Identity, P]] = securedServerLogic[Identity, P]((i, principal, _) => logic(i, principal)) + private def serverTool[F[_], C <: ServerContext[F]](logic: (I, C, Seq[Header]) => F[ToolResult[O]]): ServerTool[I, O, F, C] = + ServerTool(name, description, inputSchema, inputDecoder, outputSchema, annotations, logic, requiredClientCapabilities) + /** A fully-defined tool: its metadata plus the logic handling a call, in effect `F` with context `C`. */ case class ServerTool[I, O, F[_], -C <: ServerContext[F]]( name: String, @@ -160,5 +171,6 @@ case class ServerTool[I, O, F[_], -C <: ServerContext[F]]( inputDecoder: Decoder[I], outputSchema: Option[ToolSchema], annotations: Option[ToolAnnotations], - logic: (I, C, Seq[Header]) => F[ToolResult[O]] + logic: (I, C, Seq[Header]) => F[ToolResult[O]], + requiredClientCapabilities: Option[ClientCapabilities] = None ) diff --git a/server/src/test/scala/chimp/server/McpHandlerSpec.scala b/server/src/test/scala/chimp/server/McpHandlerSpec.scala index 34a26e1b..736fc8f3 100644 --- a/server/src/test/scala/chimp/server/McpHandlerSpec.scala +++ b/server/src/test/scala/chimp/server/McpHandlerSpec.scala @@ -797,3 +797,52 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: val body = extractJsonFromResponse(McpHandler(contextServer).handleJsonRpc(req.asJson, Seq.empty)) withClue(s"$method $params"): body.noSpaces should include("2026-07-28 cli") + + private val samplingTool = tool("needs_sampling") + .withRequiredClientCapabilities(ClientCapabilities(sampling = Some(Json.obj()))) + .input[EchoInput] + .handle(in => ToolResult.text(in.message)) + + private val capabilityHandler = McpHandler(McpServer[Identity]().addTool(samplingTool)) + + private def samplingToolCall(meta: Json): Json = + val params = Json.obj("name" -> Json.fromString("needs_sampling"), "arguments" -> Json.obj("message" -> Json.fromString("hi"))) + val req: JSONRPCMessage = + Request(method = "tools/call", params = Some(params.deepMerge(Json.obj("_meta" -> meta))), id = RequestId("cap")) + req.asJson + + private def callSamplingTool(meta: Json): McpResponse = capabilityHandler.handleJsonRpc(samplingToolCall(meta), Seq.empty) + + it should "reject a modern call of a tool that needs an undeclared client capability with -32021 and HTTP 400" in: + val meta = Json.obj(ProtocolMeta.ProtocolVersionKey -> Json.fromString("2026-07-28"), ProtocolMeta.ClientCapabilities -> Json.obj()) + val response = callSamplingTool(meta) + response.statusCode shouldBe sttp.model.StatusCode.BadRequest + capabilityHandler.validateRequest(samplingToolCall(meta), Seq.empty).map(_.statusCode) shouldBe Some(sttp.model.StatusCode.BadRequest) + extractJsonFromResponse(response).as[JSONRPCMessage].getOrElse(fail("decode")) match + case Error(_, id, err) => + id shouldBe RequestId("cap") + err.code shouldBe MissingRequiredClientCapability.code + err.data.flatMap(_.hcursor.downField("requiredCapabilities").focus) shouldBe Some(Json.obj("sampling" -> Json.obj())) + case other => fail(s"Expected Error, got $other") + + it should "serve a modern call of a tool whose required client capabilities are declared" in: + callSamplingTool(modernToolMeta()).statusCode shouldBe sttp.model.StatusCode.Ok + + it should "serve a legacy call of a tool that needs a client capability" in: + callSamplingTool(Json.obj()).statusCode shouldBe sttp.model.StatusCode.Ok + + it should "check nested required client capabilities key by key" in: + val formTool = tool("needs_form") + .withRequiredClientCapabilities(ClientCapabilities(elicitation = Some(Json.obj("form" -> Json.obj())))) + .input[EchoInput] + .handle(in => ToolResult.text(in.message)) + val formHandler = McpHandler(McpServer[Identity]().addTool(formTool)) + def call(declared: Json): sttp.model.StatusCode = + val meta = Json.obj(ProtocolMeta.ProtocolVersionKey -> Json.fromString("2026-07-28"), ProtocolMeta.ClientCapabilities -> declared) + val params = + Json.obj("name" -> Json.fromString("needs_form"), "arguments" -> Json.obj("message" -> Json.fromString("hi")), "_meta" -> meta) + val req: JSONRPCMessage = Request(method = "tools/call", params = Some(params), id = RequestId("form")) + formHandler.handleJsonRpc(req.asJson, Seq.empty).statusCode + call(Json.obj("elicitation" -> Json.obj())) shouldBe sttp.model.StatusCode.BadRequest + call(Json.obj("elicitation" -> Json.obj("url" -> Json.obj()))) shouldBe sttp.model.StatusCode.BadRequest + call(Json.obj("elicitation" -> Json.obj("form" -> Json.obj(), "url" -> Json.obj()))) shouldBe sttp.model.StatusCode.Ok From 68199c5dd8532b034fa9328dfaec24028801f54d Mon Sep 17 00:00:00 2001 From: Ondra Pelech Date: Thu, 19 Nov 2026 15:47:23 +0100 Subject: [PATCH 4/8] fix(T8): accept JSON-RPC request ids beyond the Int range RequestId decoded numeric ids only as Int. A request with a larger id (for example a millisecond timestamp, which the conformance harness sends) failed to decode as a request and was taken for a notification, so the server answered with an empty response. RequestId now also holds a Long; small numbers still decode as Int, so existing ids compare equal. --- core/src/main/scala/chimp/protocol/Ids.scala | 9 +++++---- server/src/test/scala/chimp/server/McpHandlerSpec.scala | 6 ++++++ 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/core/src/main/scala/chimp/protocol/Ids.scala b/core/src/main/scala/chimp/protocol/Ids.scala index 13803dc9..77b476b1 100644 --- a/core/src/main/scala/chimp/protocol/Ids.scala +++ b/core/src/main/scala/chimp/protocol/Ids.scala @@ -2,15 +2,16 @@ package chimp.protocol import io.circe.{Codec, Decoder, Encoder, Json} -opaque type RequestId = String | Int +opaque type RequestId = String | Int | Long object RequestId: - def apply(value: String | Int): RequestId = value - def unapply(id: RequestId): Option[String | Int] = Some(id) + def apply(value: String | Int | Long): RequestId = value + def unapply(id: RequestId): Option[String | Int | Long] = Some(id) given encoder: Encoder[RequestId] = Encoder.instance: case s: String => Json.fromString(s) case i: Int => Json.fromInt(i) + case l: Long => Json.fromLong(l) given decoder: Decoder[RequestId] = Decoder.instance: c => - c.as[String].map(RequestId(_)).orElse(c.as[Int].map(RequestId(_))) + c.as[String].map(RequestId(_)).orElse(c.as[Int].map(RequestId(_))).orElse(c.as[Long].map(RequestId(_))) given codec: Codec[RequestId] = Codec.from(decoder, encoder) opaque type ProgressToken = String | Int diff --git a/server/src/test/scala/chimp/server/McpHandlerSpec.scala b/server/src/test/scala/chimp/server/McpHandlerSpec.scala index 736fc8f3..5aec5a43 100644 --- a/server/src/test/scala/chimp/server/McpHandlerSpec.scala +++ b/server/src/test/scala/chimp/server/McpHandlerSpec.scala @@ -846,3 +846,9 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: call(Json.obj("elicitation" -> Json.obj())) shouldBe sttp.model.StatusCode.BadRequest call(Json.obj("elicitation" -> Json.obj("url" -> Json.obj()))) shouldBe sttp.model.StatusCode.BadRequest call(Json.obj("elicitation" -> Json.obj("form" -> Json.obj(), "url" -> Json.obj()))) shouldBe sttp.model.StatusCode.Ok + + it should "serve a request whose numeric id is beyond the Int range and echo the id" in: + val json = parseJson("""{"jsonrpc":"2.0","id":1763561090000,"method":"tools/list"}""") + extractJsonFromResponse(handler.handleJsonRpc(json, Seq.empty)).hcursor.downField("id").focus shouldBe Some( + Json.fromLong(1763561090000L) + ) From 33eb72a9446f6312b3fbf170c488369a703354a5 Mon Sep 17 00:00:00 2001 From: Ondra Pelech Date: Thu, 19 Nov 2026 15:47:57 +0100 Subject: [PATCH 5/8] feat(T8): add test_missing_capability and test_logging_tool conformance fixtures The server-stateless scenario (2026-07-28) calls test_missing_capability without declaring sampling and expects -32021 with HTTP 400, and calls test_logging_tool without a logLevel and expects no notifications/message. test_missing_capability declares sampling as a required client capability; test_logging_tool logs once at every level and relies on the per-request log gate. Both checks now pass. The scenario stays in the baseline, because it also covers subscriptions/listen and other later work. --- .../scala/chimp/conformance/server/Main.scala | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/server-conformance/src/main/scala/chimp/conformance/server/Main.scala b/server-conformance/src/main/scala/chimp/conformance/server/Main.scala index 848ed73b..f287803f 100644 --- a/server-conformance/src/main/scala/chimp/conformance/server/Main.scala +++ b/server-conformance/src/main/scala/chimp/conformance/server/Main.scala @@ -132,6 +132,19 @@ object Main: ctx.log(LoggingLevel.Info, Json.fromString("Tool execution completed")) ToolResult.text("logging complete") + private val missingCapabilityTool = tool("test_missing_capability") + .description("Needs the sampling client capability") + .withRequiredClientCapabilities(ClientCapabilities(sampling = Some(Json.obj()))) + .input[NoInput] + .handle(_ => ToolResult.text("sampling capability declared")) + + private val perRequestLoggingTool = tool("test_logging_tool") + .description("Emits a log notification at each level; a modern request gets only those at or above its _meta logLevel") + .input[NoInput] + .streamingServerLogic[Identity]: (_, ctx, _) => + LoggingLevel.values.foreach(level => ctx.log(level, Json.fromString(s"$level message"))) + ToolResult.text("logging complete") + private val staticText = resource("test://static-text") .name("static-text") .mimeType("text/plain") @@ -184,7 +197,17 @@ object Main: .handle(_ => GetPromptResult(messages = List(PromptMessage(Role.User, ToolContent.Image(data = pngData, mimeType = "image/png"))))) private val server = McpServer[Identity](name = "chimp-conformance-server", version = "0.1.0") - .addTools(addNumbers, simpleText, errorTool, imageTool, audioTool, mixedTool, embeddedResourceTool, jsonSchemaTool) + .addTools( + addNumbers, + simpleText, + errorTool, + imageTool, + audioTool, + mixedTool, + embeddedResourceTool, + jsonSchemaTool, + missingCapabilityTool + ) .addResources(staticText, staticBinary) .addResourceTemplate(dataTemplate) .addPrompts(simplePrompt, argsPrompt, embeddedResourcePrompt, imagePrompt) @@ -192,7 +215,7 @@ object Main: .withLoggingLevel(_ => ()) .withSubscriptions(ResourceSubscriptions[Identity](_ => (), _ => ())) - private val streamingServer = server.streaming.addStreamingTools(progressTool, loggingTool) + private val streamingServer = server.streaming.addStreamingTools(progressTool, loggingTool, perRequestLoggingTool) def main(args: Array[String]): Unit = val requestedPort = args From ebcdb7f68c450193f70b7c740bd774c25f0626ce Mon Sep 17 00:00:00 2001 From: Ondra Pelech Date: Thu, 19 Nov 2026 15:49:30 +0100 Subject: [PATCH 6/8] docs(T8): document request facts, per-request log level and -32021 Describe ctx.request (RequestInfo) and which facts a modern and a legacy request give, serverLogicWithContext, the logLevel gate on ctx.log for modern requests, and withRequiredClientCapabilities with its -32021 rejection. Add -32021 to the table of modern request errors. --- docs/server/capabilities.md | 39 +++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/docs/server/capabilities.md b/docs/server/capabilities.md index 092db3d1..733a2ef9 100644 --- a/docs/server/capabilities.md +++ b/docs/server/capabilities.md @@ -1,9 +1,9 @@ # Server capabilities -Most tools just answer a request, so `serverLogic`/`handle` expose no context. A tool that needs to **push to the client while it runs** uses `streamingServerLogic`, which receives a `StreamingServerContext[F]`: +Most tools just answer a request, so `serverLogic`/`handle` expose no context. Use `serverLogicWithContext` to read the facts of the request (see [request facts](#request-facts)). A tool that needs to **push to the client while it runs** uses `streamingServerLogic`, which receives a `StreamingServerContext[F]`: - `reportProgress` — [progress](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/progress) notifications, auto-wired to the request's progress token. -- `log` — [logging](https://modelcontextprotocol.io/specification/2025-11-25/server/utilities/logging) notifications. +- `log` — [logging](https://modelcontextprotocol.io/specification/2025-11-25/server/utilities/logging) notifications. For a modern (`2026-07-28`) request, chimp sends a message only when its level is at or above the [per-request log level](https://modelcontextprotocol.io/specification/2026-07-28/server/utilities/logging#per-request-log-level) in `_meta` (`io.modelcontextprotocol/logLevel`). If the request sets no level, chimp sends no messages. For a legacy request, chimp sends all messages; use `.withLoggingLevel` to receive `logging/setLevel`. ```{note} Pushing to the client requires an open stream, so a `streamingServerLogic` tool is registered with `addStreamingTool` on a `StreamingMcpServer`, and will not compile on the plain request/response endpoint. @@ -45,5 +45,40 @@ A request is **modern** when its `_meta` or its `MCP-Protocol-Version` header de | the `MCP-Protocol-Version` header and `_meta` declare different versions | `-32020` HeaderMismatch | `400` | | `Mcp-Method` / `Mcp-Name` header missing or different from the body (HTTP only) | `-32020` HeaderMismatch | `400` | | removed method (`initialize`, `ping`, `logging/setLevel`, `resources/subscribe`, `resources/unsubscribe`) or unknown method | `-32601` MethodNotFound | `404` | +| `tools/call` of a tool whose required client capabilities `_meta` does not declare | `-32021` MissingRequiredClientCapability | `400` | Over HTTP, a modern request must carry the SEP-2243 standard headers: `Mcp-Method` with the body's `method`, and `Mcp-Name` with `params.name` on `tools/call` and `prompts/get`, or `params.uri` on `resources/read`. Header names are case-insensitive, values are case-sensitive, and surrounding whitespace is ignored. chimp's own client sends these headers and the `_meta` when you give it a modern protocol version — see [client transport](../client/transport.md). + +## Request facts + +Each handler can read the facts of its request from `ctx.request`, a `RequestInfo`: + +- `protocolVersion` — the protocol version of the request. +- `clientCapabilities` and `clientInfo` — what the client declares in `_meta`. +- `logLevel` — the per-request log level from `_meta`. +- `progressToken` — the progress token from `_meta`. + +A modern request carries all of these in `_meta`. The server keeps no state between requests, so a legacy request gives only the protocol version (from the `MCP-Protocol-Version` header or `_meta`) and the progress token. The other facts are `None`. + +`serverLogicWithContext` gives the context to tools, prompts, resources and resource templates on every server. `streamingServerLogic` and `securedStreamingServerLogic` give it too, because `StreamingServerContext` is a `ServerContext`. + +A tool that needs a client capability declares it with `withRequiredClientCapabilities`. If a modern request does not declare all of these capabilities in `_meta`, chimp rejects it before the logic runs, with `-32021` (MissingRequiredClientCapability), HTTP `400`, and the capabilities in `data.requiredCapabilities`. chimp compares the capabilities key by key, also in nested objects. A legacy request has no per-request capabilities, so chimp does not check it. + +```scala mdoc:compile-only +import chimp.server.* +import chimp.protocol.ClientCapabilities +import io.circe.{Codec, Json} +import sttp.shared.Identity +import sttp.tapir.* + +case class AskInput(question: String) derives Codec, Schema + +val ask = tool("ask") + .withRequiredClientCapabilities(ClientCapabilities(sampling = Some(Json.obj()))) + .input[AskInput] + .serverLogicWithContext[Identity]: (in, ctx, _) => + val client = ctx.request.clientInfo.fold("unknown client")(_.name) + ToolResult.text(s"$client asked: ${in.question}") + +val server = McpServer[Identity]().addTool(ask) +``` From 178aef7eef8f3c833035b65fd5af1a81dd0e6dcf Mon Sep 17 00:00:00 2001 From: Ondra Pelech Date: Thu, 19 Nov 2026 16:05:04 +0100 Subject: [PATCH 7/8] test(T8): expect no log notifications for modern requests without a log level The shared streaming tests run with a legacy client (Pekko) and with a modern 2026-07-28 client (ZIO, Ox). The modern client sends no _meta logLevel yet, so under the per-request log level rule it must receive no notifications/message. Each spec now states its client protocol version, and the log tests expect the messages for a legacy client and none for a modern one. This covers the log gate end to end over HTTP on all three backends. --- .../chimp/server/ox/OxMcpServerHttpSpec.scala | 9 +++++---- .../server/pekko/PekkoMcpServerHttpSpec.scala | 3 ++- .../chimp/server/zio/ZioMcpServerHttpSpec.scala | 9 +++++---- .../chimp/server/McpServerStreamingTests.scala | 15 +++++++++++---- .../server/SecuredMcpServerStreamingTests.scala | 16 +++++++++++----- 5 files changed, 34 insertions(+), 18 deletions(-) diff --git a/server-streaming/server-ox/src/test/scala/chimp/server/ox/OxMcpServerHttpSpec.scala b/server-streaming/server-ox/src/test/scala/chimp/server/ox/OxMcpServerHttpSpec.scala index d958c82d..317c9423 100644 --- a/server-streaming/server-ox/src/test/scala/chimp/server/ox/OxMcpServerHttpSpec.scala +++ b/server-streaming/server-ox/src/test/scala/chimp/server/ox/OxMcpServerHttpSpec.scala @@ -40,6 +40,7 @@ class OxMcpServerHttpSpec with SecuredMcpServerStreamingTests[Identity] with SyncToFuture: private val clientInfo = Implementation("chimp-server-test", "0.0.1") + override protected val clientProtocolVersion: ProtocolVersion = ProtocolVersion.Latest override protected def withServer(server: McpServer[Identity])(test: McpClient[Identity] => Identity[Assertion]): Future[Assertion] = withStreamingServer(server.streaming)(test) @@ -50,8 +51,8 @@ class OxMcpServerHttpSpec withHttpServer(OxServerHttpTransport(List("mcp")).serve(server)): (port, backend, ox) => given Ox = ox val transport = - OxClientHttpTransport(backend, uri"http://localhost:$port/mcp", ProtocolVersion.Latest, ClientTransport.defaultTimeout) - try test(McpClient.bidirectional(transport, clientInfo, protocolVersion = ProtocolVersion.Latest)) + OxClientHttpTransport(backend, uri"http://localhost:$port/mcp", clientProtocolVersion, ClientTransport.defaultTimeout) + try test(McpClient.bidirectional(transport, clientInfo, protocolVersion = clientProtocolVersion)) finally transport.close() override protected def withSecuredServer( @@ -77,11 +78,11 @@ class OxMcpServerHttpSpec val transport = OxClientHttpTransport( backend, uri"http://localhost:$port/mcp", - ProtocolVersion.Latest, + clientProtocolVersion, ClientTransport.defaultTimeout, headers = List(Header.authorization("Bearer", token)) ) - try test(McpClient.bidirectional(transport, clientInfo, protocolVersion = ProtocolVersion.Latest)) + try test(McpClient.bidirectional(transport, clientInfo, protocolVersion = clientProtocolVersion)) finally transport.close() // 2026-07-28 requests over raw HTTP: chimp's client does not write the modern `_meta` or the SEP-2243 headers yet diff --git a/server-streaming/server-pekko/src/test/scala/chimp/server/pekko/PekkoMcpServerHttpSpec.scala b/server-streaming/server-pekko/src/test/scala/chimp/server/pekko/PekkoMcpServerHttpSpec.scala index f3c09448..e80782bf 100644 --- a/server-streaming/server-pekko/src/test/scala/chimp/server/pekko/PekkoMcpServerHttpSpec.scala +++ b/server-streaming/server-pekko/src/test/scala/chimp/server/pekko/PekkoMcpServerHttpSpec.scala @@ -2,7 +2,7 @@ package chimp.server.pekko import chimp.client.transport.pekko.PekkoClientHttpTransport import chimp.client.{BidirectionalMcpClient, McpClient} -import chimp.protocol.Implementation +import chimp.protocol.{Implementation, ProtocolVersion} import chimp.server.transport.SecuredServerStreamingHttpTransport import chimp.server.{ McpServer, @@ -34,6 +34,7 @@ class PekkoMcpServerHttpSpec with SecuredMcpServerStreamingTests[Future] with PekkoToFuture: private val clientInfo = Implementation("chimp-server-test", "0.0.1") + override protected val clientProtocolVersion: ProtocolVersion = ProtocolVersion.LatestLegacy override protected def withServer(server: McpServer[Future])(test: McpClient[Future] => Future[Assertion]): Future[Assertion] = withStreamingServer(server.streaming)(test) diff --git a/server-streaming/server-zio/src/test/scala/chimp/server/zio/ZioMcpServerHttpSpec.scala b/server-streaming/server-zio/src/test/scala/chimp/server/zio/ZioMcpServerHttpSpec.scala index a500fa28..251b88c3 100644 --- a/server-streaming/server-zio/src/test/scala/chimp/server/zio/ZioMcpServerHttpSpec.scala +++ b/server-streaming/server-zio/src/test/scala/chimp/server/zio/ZioMcpServerHttpSpec.scala @@ -35,6 +35,7 @@ class ZioMcpServerHttpSpec with SecuredMcpServerStreamingTests[Task] with ZioToFuture: private val clientInfo = Implementation("chimp-server-test", "0.0.1") + override protected val clientProtocolVersion: ProtocolVersion = ProtocolVersion.Latest override protected def withServer(server: McpServer[Task])(test: McpClient[Task] => Task[Assertion]): Future[Assertion] = withStreamingServer(server.streaming)(test) @@ -43,14 +44,14 @@ class ZioMcpServerHttpSpec server: StreamingMcpServer[Task] )(test: BidirectionalMcpClient[Task] => Task[Assertion]): Future[Assertion] = withHttpServer(ZioServerHttpTransport(List("mcp")).serve(server), Nil): transport => - McpClient.bidirectional(transport, clientInfo, protocolVersion = ProtocolVersion.Latest).flatMap(test) + McpClient.bidirectional(transport, clientInfo, protocolVersion = clientProtocolVersion).flatMap(test) override protected def withSecuredServer( server: SecuredMcpServer[Task, String, String, User], token: String )(test: McpClient[Task] => Task[Assertion]): Future[Assertion] = withHttpServer(server.endpoint(List("mcp")), List(Header.authorization("Bearer", token))): transport => - McpClient(transport, clientInfo, ProtocolVersion.Latest).flatMap(test) + McpClient(transport, clientInfo, clientProtocolVersion).flatMap(test) override protected def withSecuredStreamingServer( server: SecuredStreamingMcpServer[Task, String, String, User], @@ -58,7 +59,7 @@ class ZioMcpServerHttpSpec )(test: BidirectionalMcpClient[Task] => Task[Assertion]): Future[Assertion] = val endpoint = SecuredServerStreamingHttpTransport(List("mcp"), ZioServerHttpTransport(List("mcp"))).serve(server) withHttpServer(endpoint, List(Header.authorization("Bearer", token))): transport => - McpClient.bidirectional(transport, clientInfo, protocolVersion = ProtocolVersion.Latest).flatMap(test) + McpClient.bidirectional(transport, clientInfo, protocolVersion = clientProtocolVersion).flatMap(test) private def withHttpServer( endpoint: ServerEndpoint[ZioStreams & WebSockets, Task], @@ -74,7 +75,7 @@ class ZioMcpServerHttpSpec .scoped( backend, uri"http://localhost:$port/mcp", - ProtocolVersion.Latest, + clientProtocolVersion, ClientTransport.defaultTimeout, headers = headers ) diff --git a/server/src/test/scala/chimp/server/McpServerStreamingTests.scala b/server/src/test/scala/chimp/server/McpServerStreamingTests.scala index da568d64..5c60540a 100644 --- a/server/src/test/scala/chimp/server/McpServerStreamingTests.scala +++ b/server/src/test/scala/chimp/server/McpServerStreamingTests.scala @@ -19,6 +19,9 @@ trait McpServerStreamingTests[F[_]] extends AsyncFlatSpec with Matchers: protected def withStreamingServer(server: StreamingMcpServer[F])(test: BidirectionalMcpClient[F] => F[Assertion]): Future[Assertion] + /** The protocol version of the spec's client. A modern client sets no `_meta` logLevel, so it must get no log notifications. */ + protected def clientProtocolVersion: ProtocolVersion + private case class NoInput() derives Codec, Schema protected def streamingServer: StreamingMcpServer[F] = @@ -36,7 +39,7 @@ trait McpServerStreamingTests[F[_]] extends AsyncFlatSpec with Matchers: yield ToolResult.text("done") ) - "a streaming MCP server" should "deliver log notifications emitted during a tool call" in + "a streaming MCP server" should "deliver log notifications emitted during a tool call, but none to a modern request without a log level" in withStreamingServer(streamingServer): client => val messages = ConcurrentLinkedQueue[Json]() val listener: ServerNotification => F[Unit] = { @@ -47,6 +50,10 @@ trait McpServerStreamingTests[F[_]] extends AsyncFlatSpec with Matchers: .onServerNotification(notification => listener(notification)) .flatMap(_ => client.callTool("noisy", Json.obj())) .flatMap: result => - waitUntil(messages.size >= 3).map: _ => - result.content shouldBe List(ToolContent.Text("text", "done")) - messages.asScala.toList shouldBe List(Json.fromString("one"), Json.fromString("two"), Json.fromString("three")) + val expected = + if clientProtocolVersion.isModern then Nil else List(Json.fromString("one"), Json.fromString("two"), Json.fromString("three")) + waitUntil(messages.size >= expected.size) + .flatMap(_ => sleep(50)) + .map: _ => + result.content shouldBe List(ToolContent.Text("text", "done")) + messages.asScala.toList shouldBe expected diff --git a/server/src/test/scala/chimp/server/SecuredMcpServerStreamingTests.scala b/server/src/test/scala/chimp/server/SecuredMcpServerStreamingTests.scala index 750f7202..17080f71 100644 --- a/server/src/test/scala/chimp/server/SecuredMcpServerStreamingTests.scala +++ b/server/src/test/scala/chimp/server/SecuredMcpServerStreamingTests.scala @@ -23,6 +23,9 @@ trait SecuredMcpServerTestFixtures[F[_]]: trait SecuredMcpServerStreamingTests[F[_]] extends AsyncFlatSpec with Matchers with RecoverMethods with SecuredMcpServerTestFixtures[F]: this: ToFuture[F] => + /** The protocol version of the spec's client. A modern client sets no `_meta` logLevel, so it must get no log notifications. */ + protected def clientProtocolVersion: ProtocolVersion + /** @param token * The bearer token the client authenticates with; defaults to [[validToken]] so most tests need not pass it. */ @@ -83,11 +86,14 @@ trait SecuredMcpServerStreamingTests[F[_]] extends AsyncFlatSpec with Matchers w .onServerNotification(notification => listener(notification)) .flatMap(_ => client.callTool("whoAmI", Json.obj())) .flatMap: result => - waitUntil(messages.size >= 1).map: _ => - result.content shouldBe List(ToolContent.Text("text", "employee@example.com")) - messages.asScala.toList shouldBe List(Json.fromString("employee@example.com")) - - "a secured streaming MCP server" should "give the principal to a streaming tool, and deliver its log notifications" in + val expected = if clientProtocolVersion.isModern then Nil else List(Json.fromString("employee@example.com")) + waitUntil(messages.size >= expected.size) + .flatMap(_ => sleep(50)) + .map: _ => + result.content shouldBe List(ToolContent.Text("text", "employee@example.com")) + messages.asScala.toList shouldBe expected + + "a secured streaming MCP server" should "give the principal to a streaming tool, and deliver its log notifications (none to a modern request without a log level)" in withSecuredStreamingServer(securedStreamingServer)(assertWhoAmIDeliversPrincipal) it should "give the principal to a streaming tool when the security logic is effectful" in From 345050ac09fecb7c00c49b6c082a388ab2c7dbf7 Mon Sep 17 00:00:00 2001 From: Ondra Pelech Date: Thu, 19 Nov 2026 17:06:27 +0100 Subject: [PATCH 8/8] feat(T8): validate server/discover like other modern requests server/discover was the era-agnostic bootstrap and skipped all checks. A discover that declares a version (in _meta or in the MCP-Protocol-Version header) is now a modern request and gets the same checks: -32602 for missing _meta keys, -32022 with the supported and requested versions for an unsupported version, -32020 for a header that differs from _meta, and the SEP-2243 Mcp-Method check, all with HTTP 400. A discover with no version, or a legacy one, is still answered, so a probing client can discover the server. Two ordering fixes follow the conformance harness: a header/_meta version mismatch is now reported (-32020) before an unsupported _meta version (-32022), and a modern HTTP request without the MCP-Protocol-Version header fails with -32020. --- docs/server/capabilities.md | 4 +- .../main/scala/chimp/server/McpHandler.scala | 24 ++++---- .../scala/chimp/server/McpHandlerSpec.scala | 60 ++++++++++++++++++- 3 files changed, 75 insertions(+), 13 deletions(-) diff --git a/docs/server/capabilities.md b/docs/server/capabilities.md index 733a2ef9..be4b790b 100644 --- a/docs/server/capabilities.md +++ b/docs/server/capabilities.md @@ -36,13 +36,13 @@ chimp is **dual-era**: it speaks the legacy handshake revisions (`2025-11-25` an The server answers `server/discover` automatically with its supported versions, capabilities and identity (`serverInfo` in `_meta`), so a client can learn them in one request without connecting. A request that declares a protocol version the server does not support is rejected with an `UnsupportedProtocolVersion` error (`-32022`) listing the supported versions, per the [versioning compatibility matrix](https://modelcontextprotocol.io/specification/2026-07-28/basic/versioning#compatibility-matrix). No configuration is required for any of this. -A request is **modern** when its `_meta` or its `MCP-Protocol-Version` header declares `2026-07-28`. A legacy client that writes a legacy version into `_meta` stays on the legacy rules. chimp checks every modern request before any tool logic runs, and answers a failed check with a plain JSON error and its own HTTP status: +A request is **modern** when its `_meta` or its `MCP-Protocol-Version` header declares `2026-07-28`. A legacy client that writes a legacy version into `_meta` stays on the legacy rules. chimp checks every modern request, `server/discover` included, before any tool logic runs, and answers a failed check with a plain JSON error and its own HTTP status. A `server/discover` that declares no version (or a legacy version) gets no checks, so any client can discover the server: | Problem | JSON-RPC error | HTTP status | |---|---|---| | unsupported protocol version | `-32022` UnsupportedProtocolVersion | `400` | | `_meta` has no `protocolVersion` or no `clientCapabilities` | `-32602` InvalidParams | `400` | -| the `MCP-Protocol-Version` header and `_meta` declare different versions | `-32020` HeaderMismatch | `400` | +| the `MCP-Protocol-Version` header is missing (HTTP only), or it and `_meta` declare different versions | `-32020` HeaderMismatch | `400` | | `Mcp-Method` / `Mcp-Name` header missing or different from the body (HTTP only) | `-32020` HeaderMismatch | `400` | | removed method (`initialize`, `ping`, `logging/setLevel`, `resources/subscribe`, `resources/unsubscribe`) or unknown method | `-32601` MethodNotFound | `404` | | `tools/call` of a tool whose required client capabilities `_meta` does not declare | `-32021` MissingRequiredClientCapability | `400` | diff --git a/server/src/main/scala/chimp/server/McpHandler.scala b/server/src/main/scala/chimp/server/McpHandler.scala index 86508012..fd598d48 100644 --- a/server/src/main/scala/chimp/server/McpHandler.scala +++ b/server/src/main/scala/chimp/server/McpHandler.scala @@ -81,7 +81,7 @@ private[server] class McpHandler[F[_], C <: ServerContext[F]](server: McpServerD requestRejection(method, params, headers, id) match case Some(rejection) => rejection.unit case None => - val isModern = isModernRequest(method, params, headers) + val isModern = isModernRequest(params, headers) val info = requestInfo(params, headers, isModern) dispatch(method, params, id, headers, () => makeContext(info), isModern) case Right(notification: JSONRPCMessage.Notification) => @@ -155,9 +155,10 @@ private[server] class McpHandler[F[_], C <: ServerContext[F]](server: McpServerD private def jsonResponse(message: JSONRPCMessage): McpResponse = McpResponse.JsonResponse(message.asJson) - // request methods a 2026-07-28 client may call (server/discover is handled separately as the era-agnostic bootstrap) + // request methods a 2026-07-28 client may call private val modernMethods: Set[String] = Set( + "server/discover", "tools/list", "tools/call", "resources/list", @@ -175,13 +176,13 @@ private[server] class McpHandler[F[_], C <: ServerContext[F]](server: McpServerD /** Whether the request follows the modern (2026-07-28) rules: it declares a modern version in `_meta` or via the `MCP-Protocol-Version` * header. A known legacy version in `_meta` keeps the legacy rules; an unknown one is treated as modern, so it gets the modern `-32022` - * with HTTP 400. `server/discover` is the era-agnostic bootstrap and is never treated as modern here. + * with HTTP 400. A `server/discover` that declares no version stays legacy, so a probing client can still discover the server. */ - private def isModernRequest(method: String, params: Option[Json], headers: Seq[Header]): Boolean = + private def isModernRequest(params: Option[Json], headers: Seq[Header]): Boolean = val metaVersion = params.flatMap(_.hcursor.downField("_meta").downField(ProtocolMeta.ProtocolVersionKey).as[String].toOption) val headerVersion = headers.collectFirst { case h if h.name.equalsIgnoreCase(ProtocolMeta.ProtocolVersionHeader) => h.value.trim } val metaIsModern = metaVersion.exists(version => ProtocolVersion.from(version).forall(_.isModern)) - method != "server/discover" && (metaIsModern || headerVersion.flatMap(ProtocolVersion.from).exists(_.isModern)) + metaIsModern || headerVersion.flatMap(ProtocolVersion.from).exists(_.isModern) /** The facts a handler can read about the request; see [[RequestInfo]]. */ private def requestInfo(params: Option[Json], headers: Seq[Header], isModern: Boolean): RequestInfo = @@ -207,7 +208,7 @@ private[server] class McpHandler[F[_], C <: ServerContext[F]](server: McpServerD val meta = params.flatMap(_.hcursor.downField("_meta").focus) val metaVersion = meta.flatMap(_.hcursor.get[String](ProtocolMeta.ProtocolVersionKey).toOption) val headerVersion = headers.collectFirst { case h if h.name.equalsIgnoreCase(ProtocolMeta.ProtocolVersionHeader) => h.value.trim } - if isModernRequest(method, params, headers) then modernRejection(method, params, meta, metaVersion, headerVersion, headers, id) + if isModernRequest(params, headers) then modernRejection(method, params, meta, metaVersion, headerVersion, headers, id) else metaVersion match case Some(version) if ProtocolVersion.from(version).isEmpty => @@ -235,12 +236,15 @@ private[server] class McpHandler[F[_], C <: ServerContext[F]](server: McpServerD id: RequestId ): Option[McpResponse] = val declared = metaVersion.orElse(headerVersion) - if declared.exists(version => ProtocolVersion.from(version).isEmpty) then + val overHttp = headers.exists(_.name.equalsIgnoreCase("Host")) + if overHttp && headerVersion.isEmpty then + Some(jsonError(id, StatusCode.BadRequest, JSONRPCErrorCodes.HeaderMismatch.code, "Missing MCP-Protocol-Version header")) + else if headerVersion.isDefined && metaVersion.isDefined && headerVersion != metaVersion then + Some(jsonError(id, StatusCode.BadRequest, JSONRPCErrorCodes.HeaderMismatch.code, "MCP-Protocol-Version header does not match _meta")) + else if declared.exists(version => ProtocolVersion.from(version).isEmpty) then val envelope: JSONRPCMessage = JSONRPCMessage.Error(id = id, error = ProtocolMeta.unsupportedVersionError(declared.get, ProtocolVersion.supported.map(_.name))) Some(McpResponse.JsonError(StatusCode.BadRequest, envelope.asJson)) - else if headerVersion.isDefined && metaVersion.isDefined && headerVersion != metaVersion then - Some(jsonError(id, StatusCode.BadRequest, JSONRPCErrorCodes.HeaderMismatch.code, "MCP-Protocol-Version header does not match _meta")) else if metaVersion.isEmpty then Some( jsonError(id, StatusCode.BadRequest, JSONRPCErrorCodes.InvalidParams.code, s"Missing ${ProtocolMeta.ProtocolVersionKey} in _meta") @@ -253,7 +257,7 @@ private[server] class McpHandler[F[_], C <: ServerContext[F]](server: McpServerD Some(jsonError(id, StatusCode.NotFound, JSONRPCErrorCodes.MethodNotFound.code, s"Method not found: $method")) else // SEP-2243 standard request headers only apply over HTTP (identified by the Host header); stdio carries no such headers - val headerError = Option.when(headers.exists(_.name.equalsIgnoreCase("Host")))(headerValidationError(method, params, headers, id)) + val headerError = Option.when(overHttp)(headerValidationError(method, params, headers, id)) headerError.flatten.orElse(missingCapabilityError(method, params, meta, id)) /** A `-32021` with HTTP 400 when `tools/call` names a tool whose required client capabilities the request's `_meta` does not declare. */ diff --git a/server/src/test/scala/chimp/server/McpHandlerSpec.scala b/server/src/test/scala/chimp/server/McpHandlerSpec.scala index 5aec5a43..e2b51d03 100644 --- a/server/src/test/scala/chimp/server/McpHandlerSpec.scala +++ b/server/src/test/scala/chimp/server/McpHandlerSpec.scala @@ -178,7 +178,7 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: private def modernHttpCall(method: String, params: Json, extraHeaders: (String, String)*): McpResponse = val req: JSONRPCMessage = Request(method = method, params = Some(params.deepMerge(Json.obj(modernMeta))), id = RequestId("h")) - val headers = Header("Host", "localhost") +: extraHeaders.map(Header(_, _)) + val headers = Header("Host", "localhost") +: Header(ProtocolMeta.ProtocolVersionHeader, "2026-07-28") +: extraHeaders.map(Header(_, _)) headersHandler.handleJsonRpc(req.asJson, headers) private def shouldBeHeaderMismatch(response: McpResponse): org.scalatest.Assertion = @@ -852,3 +852,61 @@ class McpHandlerSpec extends AnyFlatSpec with Matchers: extractJsonFromResponse(handler.handleJsonRpc(json, Seq.empty)).hcursor.downField("id").focus shouldBe Some( Json.fromLong(1763561090000L) ) + + private def discoverOverHttp(meta: Option[Json], versionHeader: Option[String], extraHeaders: (String, String)*): McpResponse = + val req: JSONRPCMessage = Request(method = "server/discover", params = meta.map(m => Json.obj("_meta" -> m)), id = RequestId("dv")) + val headers = (("Host" -> "localhost") +: ("Mcp-Method" -> "server/discover") +: extraHeaders) ++ + versionHeader.map(ProtocolMeta.ProtocolVersionHeader -> _) + handler.handleJsonRpc(req.asJson, headers.map(Header(_, _))) + + private def errorOf(response: McpResponse): JSONRPCErrorObject = + extractJsonFromResponse(response).as[JSONRPCMessage].getOrElse(fail("decode")) match + case Error(_, _, err) => err + case other => fail(s"Expected Error, got $other") + + private def discoverMeta(version: String = "2026-07-28"): Json = + Json.obj(ProtocolMeta.ProtocolVersionKey -> Json.fromString(version), ProtocolMeta.ClientCapabilities -> Json.obj()) + + it should "answer a modern server/discover whose _meta and header are valid" in: + val response = discoverOverHttp(Some(discoverMeta()), Some("2026-07-28")) + response.statusCode shouldBe sttp.model.StatusCode.Ok + extractJsonFromResponse(response).as[JSONRPCMessage].getOrElse(fail("decode")) match + case Response(_, _, result) => result.as[DiscoverResult].isRight shouldBe true + case other => fail(s"Expected Response, got $other") + + it should "answer a server/discover that declares no protocol version, or a legacy one" in: + discoverOverHttp(None, None).statusCode shouldBe sttp.model.StatusCode.Ok + discoverOverHttp(None, Some("2025-11-25")).statusCode shouldBe sttp.model.StatusCode.Ok + + it should "reject a modern server/discover with missing _meta keys with -32602 and HTTP 400" in: + val missingCapabilities = Json.obj(ProtocolMeta.ProtocolVersionKey -> Json.fromString("2026-07-28")) + val missingVersion = Json.obj(ProtocolMeta.ClientCapabilities -> Json.obj()) + for meta <- List(None, Some(missingCapabilities), Some(missingVersion)) do + val response = discoverOverHttp(meta, Some("2026-07-28")) + withClue(meta): + response.statusCode shouldBe sttp.model.StatusCode.BadRequest + errorOf(response).code shouldBe InvalidParams.code + + it should "reject a server/discover with an unsupported protocol version with -32022, the supported and the requested versions" in: + val response = discoverOverHttp(Some(discoverMeta("v999.0.0")), Some("v999.0.0")) + response.statusCode shouldBe sttp.model.StatusCode.BadRequest + val err = errorOf(response) + err.code shouldBe UnsupportedProtocolVersion.code + err.data.flatMap(_.hcursor.get[List[String]]("supported").toOption) shouldBe Some(ProtocolVersion.supported.map(_.name)) + err.data.flatMap(_.hcursor.get[String]("requested").toOption) shouldBe Some("v999.0.0") + + it should "reject a modern request whose MCP-Protocol-Version header differs from _meta with -32020, even for an unsupported _meta version" in: + val response = discoverOverHttp(Some(discoverMeta("v999.0.0")), Some("2026-07-28")) + response.statusCode shouldBe sttp.model.StatusCode.BadRequest + errorOf(response).code shouldBe HeaderMismatch.code + + it should "reject a modern HTTP request without the MCP-Protocol-Version header with -32020 and HTTP 400" in: + val response = discoverOverHttp(Some(discoverMeta()), None) + response.statusCode shouldBe sttp.model.StatusCode.BadRequest + errorOf(response).code shouldBe HeaderMismatch.code + + it should "reject a modern server/discover over HTTP with a mismatched Mcp-Method header with -32020" in: + val req: JSONRPCMessage = Request(method = "server/discover", params = Some(Json.obj("_meta" -> discoverMeta())), id = RequestId("dm")) + val headers = + Seq(Header("Host", "localhost"), Header(ProtocolMeta.ProtocolVersionHeader, "2026-07-28"), Header("Mcp-Method", "tools/list")) + errorOf(handler.handleJsonRpc(req.asJson, headers)).code shouldBe HeaderMismatch.code