Skip to content
Open
9 changes: 5 additions & 4 deletions core/src/main/scala/chimp/protocol/Ids.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions core/src/main/scala/chimp/protocol/Versioning.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand All @@ -29,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).
*/
Expand Down
43 changes: 39 additions & 4 deletions docs/server/capabilities.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -36,14 +36,49 @@ 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` |

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)
```
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -184,15 +197,25 @@ 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)
.withCompletion((_, _, _) => Completion(values = List("alpha", "beta")))
.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
Expand Down
Original file line number Diff line number Diff line change
@@ -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}
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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(
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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}
Expand Down Expand Up @@ -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)
Expand All @@ -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] =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -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.*
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -43,22 +44,22 @@ 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],
token: String
)(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],
Expand All @@ -74,7 +75,7 @@ class ZioMcpServerHttpSpec
.scoped(
backend,
uri"http://localhost:$port/mcp",
ProtocolVersion.Latest,
clientProtocolVersion,
ClientTransport.defaultTimeout,
headers = headers
)
Expand Down
Loading
Loading