Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
49 changes: 48 additions & 1 deletion docs/server/capabilities.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ 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

Expand All @@ -45,6 +45,7 @@ A request is **modern** when its `_meta` or its `MCP-Protocol-Version` header de
| 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).
Expand Down Expand Up @@ -82,3 +83,49 @@ val ask = tool("ask")

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 @@ -145,6 +145,22 @@ object Main:
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 @@ -206,14 +222,17 @@ object Main:
mixedTool,
embeddedResourceTool,
jsonSchemaTool,
missingCapabilityTool
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, perRequestLoggingTool)

Expand All @@ -225,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()
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,15 @@ package chimp.server.ox

import chimp.protocol.JSONRPCMessage
import chimp.server.transport.ServerStreamingStdioTransport
import chimp.server.{McpHandler, OutboundSink, RequestInfo, SinkStreamingServerContext, StreamingMcpServer, StreamingServerContext}
import chimp.server.{
McpHandler,
OutboundSink,
RequestInfo,
SinkStreamingServerContext,
StdioSubscriptions,
StreamingMcpServer,
StreamingServerContext
}
import chimp.transport.{StdioFraming, StdioLineReader}
import io.circe.syntax.*
import io.circe.{parser, Json}
Expand All @@ -24,7 +32,7 @@ final class OxServerStdioTransport(

def serve(server: StreamingMcpServer[Identity]): Unit =
given MonadError[Identity] = IdentityMonad
val handler = new McpHandler[Identity, StreamingServerContext[Identity]](server)
val handler = new McpHandler[Identity, StreamingServerContext[Identity]](server, canListen = true)
val reader = StdioLineReader(in, maxLineLength)
val writer = BufferedWriter(OutputStreamWriter(out, StandardCharsets.UTF_8))

Expand All @@ -42,12 +50,17 @@ final class OxServerStdioTransport(
val makeContext: RequestInfo => StreamingServerContext[Identity] =
info => SinkStreamingServerContext(sink, info)

reader.lines
.filter(_.nonEmpty)
.foreach: line =>
parser.parse(line) match
case Right(json) => handler.handleJsonRpc(json, Nil, makeContext).body.foreach(outbound.send)
case Left(error) => log.warn(s"Failed to parse JSON-RPC line: ${error.getMessage}; raw: $line")
val subscriptions = StdioSubscriptions(handler, json => { val _ = outbound.sendOrClosed(json) })

try
reader.lines
.filter(_.nonEmpty)
.foreach: line =>
parser.parse(line) match
case Right(json) =>
if !subscriptions.accept(json) then handler.handleJsonRpc(json, Nil, makeContext).body.foreach(outbound.send)
case Left(error) => log.warn(s"Failed to parse JSON-RPC line: ${error.getMessage}; raw: $line")
finally subscriptions.endAll()

outbound.done()
writerFork.join()
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import chimp.server.{
tool,
McpServer,
McpServerStreamingTests,
McpServerSubscriptionHttpTests,
McpServerTests,
SecuredMcpServer,
SecuredMcpServerStreamingTests,
Expand All @@ -31,11 +32,13 @@ import sttp.tapir.Schema
import sttp.tapir.server.netty.sync.{NettySyncServer, OxStreams}
import sttp.tapir.server.ServerEndpoint

import java.net.URI
import scala.concurrent.Future

class OxMcpServerHttpSpec
extends McpServerTests[Identity]
with McpServerStreamingTests[Identity]
with McpServerSubscriptionHttpTests[Identity]
with SecuredMcpServerTests[Identity]
with SecuredMcpServerStreamingTests[Identity]
with SyncToFuture:
Expand All @@ -55,6 +58,10 @@ class OxMcpServerHttpSpec
try test(McpClient.bidirectional(transport, clientInfo, protocolVersion = clientProtocolVersion))
finally transport.close()

override protected def withStreamingHttpEndpoint(server: StreamingMcpServer[Identity])(test: URI => Assertion): Future[Assertion] =
withHttpServer(OxServerHttpTransport(List("mcp")).serve(server)): (port, _, _) =>
test(URI.create(s"http://localhost:$port/mcp"))

override protected def withSecuredServer(
server: SecuredMcpServer[Identity, String, String, User],
token: String
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package chimp.server.pekko

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 @@ -57,3 +57,16 @@ final class PekkoServerHttpTransport(
queue.complete()
NotUsed
.map(json => ServerSentEvent(data = Some(json.noSpaces)))

private[server] def subscriptionStream(listen: ListenRequest): EventStream =
Source
.queue[Json](outboundBufferSize, OverflowStrategy.backpressure, maxConcurrentSends)
.mapMaterializedValue: queue =>
listen.open(new SubscriptionOutput:
def send(message: Json): Unit =
val _ = PekkoOutbound.offer(queue, message)
def close(): Unit = queue.complete())
.watchTermination(): (subscription, done) =>
done.onComplete(_ => subscription.cancel())
NotUsed
.map(json => ServerSentEvent(data = Some(json.noSpaces)))
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,15 @@ package chimp.server.pekko

import chimp.protocol.JSONRPCMessage
import chimp.server.transport.ServerStreamingStdioTransport
import chimp.server.{McpHandler, OutboundSink, RequestInfo, SinkStreamingServerContext, StreamingMcpServer, StreamingServerContext}
import chimp.server.{
McpHandler,
OutboundSink,
RequestInfo,
SinkStreamingServerContext,
StdioSubscriptions,
StreamingMcpServer,
StreamingServerContext
}
import chimp.transport.{McpLineTooLongException, StdioFraming}
import io.circe.syntax.*
import io.circe.{parser, Json}
Expand All @@ -28,7 +36,7 @@ final class PekkoServerStdioTransport(
private given MonadError[Future] = FutureMonad()

def serve(server: StreamingMcpServer[Future]): Future[Unit] =
val handler = new McpHandler[Future, StreamingServerContext[Future]](server)
val handler = new McpHandler[Future, StreamingServerContext[Future]](server, canListen = true)

val (outbound, writing) = Source
.queue[Json](PekkoOutbound.defaultBufferSize, OverflowStrategy.backpressure, PekkoOutbound.defaultMaxConcurrentSends)
Expand All @@ -42,30 +50,36 @@ final class PekkoServerStdioTransport(
val makeContext: RequestInfo => StreamingServerContext[Future] =
info => SinkStreamingServerContext(sink, info)

val subscriptions = StdioSubscriptions(handler, json => { val _ = PekkoOutbound.offer(outbound, json) })

val reading = StreamConverters
.fromInputStream(() => in)
.via(Framing.delimiter(ByteString("\n"), maximumFrameLength = maxLineLength, allowTruncation = true))
.mapError { case _: Framing.FramingException => McpLineTooLongException(maxLineLength) }
.map(_.utf8String.trim)
.filter(_.nonEmpty)
.mapAsync(1)(line => handleLine(handler, makeContext, outbound, line))
.mapAsync(1)(line => handleLine(handler, subscriptions, makeContext, outbound, line))
.runWith(Sink.ignore)

reading.transformWith: result =>
subscriptions.endAll()
outbound.complete()
writing.transform(_ => result.map(_ => ()))

private def handleLine(
handler: McpHandler[Future, StreamingServerContext[Future]],
subscriptions: StdioSubscriptions,
makeContext: RequestInfo => StreamingServerContext[Future],
outbound: SourceQueueWithComplete[Json],
line: String
): Future[Unit] =
parser.parse(line) match
case Right(json) =>
handler
.handleJsonRpc(json, Nil, makeContext)
.flatMap(response => response.body.fold(Future.unit)(body => PekkoOutbound.offer(outbound, body)))
if subscriptions.accept(json) then Future.unit
else
handler
.handleJsonRpc(json, Nil, makeContext)
.flatMap(response => response.body.fold(Future.unit)(body => PekkoOutbound.offer(outbound, body)))
case Left(error) =>
log.warn(s"Failed to parse JSON-RPC line: ${error.getMessage}; raw: $line")
Future.unit
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import chimp.server.transport.SecuredServerStreamingHttpTransport
import chimp.server.{
McpServer,
McpServerStreamingTests,
McpServerSubscriptionHttpTests,
McpServerTests,
SecuredMcpServer,
SecuredMcpServerStreamingTests,
Expand All @@ -24,12 +25,14 @@ import sttp.model.Uri.UriContext
import sttp.tapir.server.pekkohttp.PekkoHttpServerInterpreter
import sttp.tapir.server.ServerEndpoint

import java.net.URI
import scala.concurrent.duration.DurationInt
import scala.concurrent.{ExecutionContext, Future}
import scala.concurrent.{blocking, ExecutionContext, Future}

class PekkoMcpServerHttpSpec
extends McpServerTests[Future]
with McpServerStreamingTests[Future]
with McpServerSubscriptionHttpTests[Future]
with SecuredMcpServerTests[Future]
with SecuredMcpServerStreamingTests[Future]
with PekkoToFuture:
Expand All @@ -45,6 +48,15 @@ class PekkoMcpServerHttpSpec
withHttpServer(PekkoServerHttpTransport(List("mcp")).serve(server), Nil): transport =>
McpClient.bidirectional(transport, clientInfo).flatMap(test)

override protected def withStreamingHttpEndpoint(server: StreamingMcpServer[Future])(test: URI => Assertion): Future[Assertion] =
given ExecutionContext = actorSystem.dispatcher
Http()
.newServerAt("localhost", 0)
.bind(PekkoHttpServerInterpreter().toRoute(PekkoServerHttpTransport(List("mcp")).serve(server)))
.flatMap: binding =>
Future(blocking(test(URI.create(s"http://localhost:${binding.localAddress.getPort}/mcp"))))
.transformWith(result => binding.terminate(5.seconds).transform(_ => result))

override protected def withSecuredServer(
server: SecuredMcpServer[Future, String, String, User],
token: String
Expand Down
Loading