Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion conformance-baseline-2026-07-28.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ server:
- input-required-result-request-state
- input-required-result-result-type
- input-required-result-tampered-state
# full stateless lifecycle (needs subscription serving)
# full stateless lifecycle: only http-server-no-independent-requests-on-stream fails, it needs the
# test_streaming_elicitation tool (multi-round-trip requests) — T14, https://github.com/softwaremill/chimp/issues/252
- server-stateless
# x-mcp-header custom headers in the tool DSL — T13, https://github.com/softwaremill/chimp/issues/251
- http-custom-header-server-validation
Expand Down
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
92 changes: 87 additions & 5 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 All @@ -28,22 +28,104 @@ val work = tool("work")
val server = StreamingMcpServer[Identity]().addStreamingTool(work)
```

Server-wide capabilities are enabled by registering a handler — only what you wire up is advertised: `.withCompletion`, `.withLoggingLevel`, `.withSubscriptions`. `.withLoggingLevel` and `.withSubscriptions` serve only legacy clients: `2026-07-28` removed `logging/setLevel` and `resources/{,un}subscribe`, so a modern client gets a `404` for them (see below).
Server-wide capabilities are enabled by registering a handler — only what you wire up is advertised: `.withCompletion`, `.withLoggingLevel`, `.withSubscriptions`, `.withPublisher`. `.withLoggingLevel` and `.withSubscriptions` serve only legacy clients: `2026-07-28` removed `logging/setLevel` and `resources/{,un}subscribe`, so a modern client gets a `404` for them (see below). `.withPublisher` serves only modern clients (see [publishing list changes and resource updates](#publishing-list-changes-and-resource-updates)).

## Protocol versions

chimp is **dual-era**: it speaks the legacy handshake revisions (`2025-11-25` and earlier, negotiated via `initialize`) and the modern `2026-07-28` revision, where each request carries its protocol version in `_meta` under `io.modelcontextprotocol/protocolVersion` instead of a handshake.

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` |
| `subscriptions/listen` on a server without a publisher, or on the sync HTTP transport | `-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)
```

## Publishing list changes and resource updates

A server tells its clients that its tools, prompts or resources changed, or that a resource was updated, through a `NotificationPublisher`. Create one, give it to the server with `.withPublisher`, and call it from any part of your application, not only from a tool:

- `toolsListChanged()`, `promptsListChanged()`, `resourcesListChanged()` — send the list-changed notification of that list.
- `resourceUpdated(uri)` — send `notifications/resources/updated` for one resource URI.
- `close()` — end all open subscriptions, for example when the server shuts down.

The methods are thread-safe and return `Unit`, not an effect. In an effect system, wrap the call, for example `ZIO.succeed(publisher.toolsListChanged())`.

```scala mdoc:compile-only
import chimp.server.*
import chimp.server.ox.OxServerHttpTransport
import io.circe.Codec
import sttp.shared.Identity
import sttp.tapir.*

case class NoteInput(text: String) derives Codec, Schema

val publisher = NotificationPublisher()

val addNote = tool("add_note")
.input[NoteInput]
.handle: _ =>
publisher.resourcesListChanged()
ToolResult.text("note added")

val server = McpServer[Identity]().addTool(addNote).withPublisher(publisher).streaming
val endpoint = OxServerHttpTransport(List("mcp")).serve(server)
```

A `2026-07-28` client receives these notifications on a [`subscriptions/listen`](https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/subscriptions) stream:

- With a publisher, `server/discover` advertises `listChanged` for tools, prompts and resources, and `subscribe` for resources. The capability of a list is there only when the server has that feature, for example `prompts` only when the server has prompts. The `initialize` result for legacy clients does not change: it advertises no list changes, and `subscribe` only for `.withSubscriptions`.
- The first message on the stream is `notifications/subscriptions/acknowledged`. Its filter is the part of the requested filter that the server honours. The server sends no other notification types.
- Each message on the stream carries the id of the listen request in `_meta`, under `io.modelcontextprotocol/subscriptionId`.
- `notifications/resources/updated` goes only to the streams which list the URI in `resourceSubscriptions`.
- Progress and log notifications do not go on a listen stream. They stay on the stream of their request.
- Over HTTP, a subscription ends when the client closes the stream. The server notices a closed stream at the latest when it next sends on it.
- Over stdio, all subscriptions share the one channel. The client ends one with `notifications/cancelled` that names the listen request. When the input ends, the server ends each open subscription.
- When the server ends a subscription (on `close()`, or at the end of the stdio input), it sends a successful `subscriptions/listen` result with the subscription id. Over stdio, it then sends `notifications/cancelled` for the listen request.

```{note}
A listen stream needs a streaming transport. On the sync HTTP transport (`McpServer.endpoint`), the server answers `subscriptions/listen` with `-32601` and advertises no list changes.
```
1 change: 1 addition & 0 deletions docs/server/resources.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
- `serverLogic` — effectful read logic, with the request headers.
- `handleSecured` (synchronous) or `securedServerLogic` (effectful) — logic that also receives the principal made by the server's security logic; usable only on a secured server — see [transport security](transport.md).
- Register with `.addResource` / `.addResourceTemplate`. Subscriptions are wired with `.withSubscriptions`; they serve legacy clients only, as `2026-07-28` removed `resources/{,un}subscribe` (see [protocol versions in server capabilities](capabilities.md)).
- On `2026-07-28`, a client subscribes to resources with the `resourceSubscriptions` filter of `subscriptions/listen`, which replaces `resources/subscribe`. Send the updates with `NotificationPublisher.resourceUpdated(uri)`; the server sends each update only to the streams which list its URI (see [publishing list changes and resource updates](capabilities.md#publishing-list-changes-and-resource-updates)).

```scala mdoc:compile-only
import chimp.server.*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,35 @@ 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 publisher = NotificationPublisher()

private val triggerToolChange = tool("test_trigger_tool_change")
.description("Publishes a tools list change to the open subscriptions")
.input[NoInput]
.handle: _ =>
publisher.toolsListChanged()
ToolResult.text("tools list change published")

private val triggerPromptChange = tool("test_trigger_prompt_change")
.description("Publishes a prompts list change to the open subscriptions")
.input[NoInput]
.handle: _ =>
publisher.promptsListChanged()
ToolResult.text("prompts list change published")

private val staticText = resource("test://static-text")
.name("static-text")
.mimeType("text/plain")
Expand Down Expand Up @@ -184,15 +213,28 @@ 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,
triggerToolChange,
triggerPromptChange
)
.addResources(staticText, staticBinary)
.addResourceTemplate(dataTemplate)
.addPrompts(simplePrompt, argsPrompt, embeddedResourcePrompt, imagePrompt)
.withCompletion((_, _, _) => Completion(values = List("alpha", "beta")))
.withLoggingLevel(_ => ())
.withSubscriptions(ResourceSubscriptions[Identity](_ => (), _ => ()))
.withPublisher(publisher)

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 All @@ -202,6 +244,8 @@ object Main:

val endpoint = OxServerHttpTransport(List("mcp")).serve(streamingServer)

val _ = sys.addShutdownHook(publisher.close())

supervised:
val binding = NettySyncServer().port(requestedPort).addEndpoint(endpoint).start()
println(s"http://127.0.0.1:${binding.port}/mcp")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package chimp.server.ox

import chimp.protocol.JSONRPCMessage
import chimp.server.OutboundSink
import chimp.server.{ListenRequest, OutboundSink, SubscriptionOutput}
import chimp.server.transport.ServerStreamingHttpTransport
import io.circe.Json
import io.circe.syntax.*
Expand Down Expand Up @@ -32,3 +32,14 @@ final class OxServerHttpTransport(path: List[String]) extends ServerStreamingHtt
try handle(sink).foreach(outbound.send)
finally outbound.done()
outbound.foreach(json => emit(ServerSentEvent(data = Some(json.noSpaces))))

private[server] def subscriptionStream(listen: ListenRequest): Flow[ServerSentEvent] =
Flow.usingEmit: emit =>
val outbound = Channel.unlimited[Json]
val subscription = listen.open(new SubscriptionOutput:
def send(message: Json): Unit =
val _ = outbound.sendOrClosed(message)
def close(): Unit =
val _ = outbound.doneOrClosed())
try outbound.foreach(json => emit(ServerSentEvent(data = Some(json.noSpaces))))
finally subscription.cancel()
Loading
Loading