Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
d5d7080
feat(T16): add a notification publisher and subscriptions/listen hand…
sideeffffect Nov 19, 2026
55f1a42
feat(T16): serve subscriptions/listen streams over streaming HTTP
sideeffffect Nov 19, 2026
7b7c5b8
feat(T16): serve subscriptions/listen over stdio
sideeffffect Nov 19, 2026
d571e12
feat(T16): add test_trigger_tool_change and test_trigger_prompt_chang…
sideeffffect Nov 19, 2026
80e4520
docs(T16): document the notification publisher and subscriptions/listen
sideeffffect Nov 19, 2026
4ee8dfa
fix(T16): deliver events published right after a subscription is ackn…
sideeffffect Nov 19, 2026
235c54a
fix(T14): send resultType input_required and allow a state-only Input…
sideeffffect Nov 19, 2026
a806842
feat(T14): let tools, prompts and resources end with an input-require…
sideeffffect Nov 19, 2026
344288b
feat(T14): answer an early HTTP error of a streaming call as plain JSON
sideeffffect Nov 19, 2026
bf840a5
test(T14): cover input-required outcomes over stdio and sync HTTP
sideeffffect Nov 19, 2026
1bf4cfa
feat(T14): add the input-required conformance fixtures
sideeffffect Nov 19, 2026
bb33c34
docs(T14): document asking the client for input
sideeffffect Nov 19, 2026
7d6a839
feat(T14): sign and verify the request state with an HMAC-SHA256 signer
sideeffffect Nov 19, 2026
0a380f8
feat(T14): add the request-state conformance fixtures
sideeffffect Nov 19, 2026
4577646
docs(T14): document the request state signer
sideeffffect Nov 19, 2026
ab03498
feat(T13): mark tool input properties with x-mcp-header
sideeffffect Nov 19, 2026
653ae60
feat(T13): validate Mcp-Param headers and Base64 sentinel values
sideeffffect Nov 19, 2026
7f5b892
test(T13): check request headers on the ZIO, Ox and Pekko HTTP servers
sideeffffect Nov 19, 2026
240c0fa
feat(T13): offer an x-mcp-header tool on the conformance server
sideeffffect Nov 19, 2026
25b1646
docs(T13): document x-mcp-header and the request header checks
sideeffffect Nov 19, 2026
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
17 changes: 0 additions & 17 deletions conformance-baseline-2026-07-28.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,25 +12,8 @@ server:
- tasks-request-state-removal
- tasks-required-task-error
- tasks-wire-fields
# server-to-client input requests during tools/call — T5, https://github.com/softwaremill/chimp/issues/243
- input-required-result-basic-elicitation
- input-required-result-basic-list-roots
- input-required-result-basic-sampling
- input-required-result-capability-check
- input-required-result-multiple-input-requests
- input-required-result-multi-round
- input-required-result-non-tool-request
- input-required-result-request-state
- input-required-result-result-type
- input-required-result-tampered-state
# full stateless lifecycle (needs subscription serving)
- server-stateless
# x-mcp-header custom headers in the tool DSL — T13, https://github.com/softwaremill/chimp/issues/251
- http-custom-header-server-validation
# the harness records a failure in a non-primary run of these scenarios (the primary run passes)
- sep-2164-resource-not-found
- input-required-result-missing-input-response
- input-required-result-ignore-extra-params
client:
# OAuth client flows — chimp's client has no full OAuth support yet
- auth/authorization-server-migration
Expand Down
4 changes: 2 additions & 2 deletions core/src/main/scala/chimp/protocol/Mrtr.scala
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ object InputResponse:
* opaque `requestState` the client echoes back on its response, and the modern result envelope fields.
*/
final case class InputRequiredResult(
inputRequests: Map[String, InputRequest],
inputRequests: Option[Map[String, InputRequest]] = None,
requestState: Option[String] = None,
resultType: ResultType = ResultType.Incomplete,
resultType: ResultType = ResultType.InputRequired,
_meta: Option[Map[String, Json]] = None
) derives io.circe.Codec
12 changes: 6 additions & 6 deletions core/src/main/scala/chimp/protocol/Versioning.scala
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,19 @@ object ProtocolMeta:
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).
/** The type of a modern (2026-07-28+) result: `complete` for a finished result, `input_required` for one that needs another round trip
* (MRTR).
*/
enum ResultType(val name: String):
case Complete extends ResultType("complete")
case Incomplete extends ResultType("incomplete")
case InputRequired extends ResultType("input_required")

object ResultType:
given Encoder[ResultType] = Encoder.instance(resultType => Json.fromString(resultType.name))
given Decoder[ResultType] = Decoder.decodeString.emap:
case "complete" => Right(Complete)
case "incomplete" => Right(Incomplete)
case other => Left(s"Unknown result type: $other")
case "complete" => Right(Complete)
case "input_required" => Right(InputRequired)
case other => Left(s"Unknown result type: $other")

/** Whether a cached response may be shared across authorization contexts (`Public`) or not (`Private`). */
enum CacheScope:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,9 @@ class Schema20260728ConformanceSpec extends SchemaConformance:
)
validate(
"InputRequiredResult",
InputRequiredResult(inputRequests = Map("name" -> request), requestState = Some("state-1"))
InputRequiredResult(inputRequests = Some(Map("name" -> request)), requestState = Some("state-1"))
)
InputRequiredResult(requestState = Some("state-1")).asJson.hcursor.get[String]("resultType") shouldBe Right("input_required")

it should "produce CallToolRequestParams carrying inputResponses and requestState that match the spec schema" in:
validate(
Expand Down
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ and [sttp](https://github.com/softwaremill/sttp), supporting the variety of the
server/prompts
server/resources
server/capabilities
server/mrtr
server/examples

.. toctree::
Expand Down
61 changes: 60 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 @@ -44,11 +44,23 @@ A request is **modern** when its `_meta` or its `MCP-Protocol-Version` header de
| `_meta` has no `protocolVersion` or no `clientCapabilities` | `-32602` InvalidParams | `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` |
| `tools/call` with an `Mcp-Param-{name}` header missing, malformed or different from its argument (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).

A modern `tools/call` over HTTP must also carry an `Mcp-Param-{name}` header for each argument that the tool marks with [`x-mcp-header`](tools.md#mirroring-arguments-into-http-headers). The server compares each header with its argument:

- An argument that is present needs its header. An argument that is `null` or absent needs no header, and a header for it is a mismatch.
- Integers are compared numerically, so `42.0` in the header equals `42` in the body. Booleans are `true` or `false`, and strings are compared literally.
- `Mcp-Param-*` headers that match no marked argument are ignored.

`Mcp-Name` and `Mcp-Param-*` values can use the Base64 sentinel form `=?base64?{value}?=`, which carries the UTF-8 bytes of the value. The server decodes a value in this form before the comparison. A sentinel with invalid Base64 (bad padding, characters outside the alphabet) or invalid UTF-8, and a value with characters that are not visible ASCII, space or tab, are a `-32020`. A value without the complete wrapper is compared literally.

Legacy requests and stdio get none of these header checks.

## Request facts

Each handler can read the facts of its request from `ctx.request`, a `RequestInfo`:
Expand All @@ -57,6 +69,7 @@ Each handler can read the facts of its request from `ctx.request`, a `RequestInf
- `clientCapabilities` and `clientInfo` — what the client declares in `_meta`.
- `logLevel` — the per-request log level from `_meta`.
- `progressToken` — the progress token from `_meta`.
- `inputResponses` and `requestState` — on the retry of an input-required outcome, the answers of the client and the echoed state (see [asking the client for input](mrtr.md)).

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`.

Expand All @@ -82,3 +95,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.
```
101 changes: 101 additions & 0 deletions docs/server/mrtr.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# Asking the client for input

In protocol version `2026-07-28`, a server does not send requests to the client while it handles a request. Instead, a handler can end a `tools/call`, `prompts/get` or `resources/read` with an **input-required** outcome. The client gets the input that the handler asks for, and then sends the same request again with the answers. The server keeps no state between the two requests. This is the [multi round-trip requests](https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/mrtr) (MRTR) pattern.

## Requesting input

A tool, prompt or resource handler returns `InputRequired` instead of its result. `InputRequired` names each input request with a key that the handler chooses:

| Input request | What the client does | Client capability that it needs |
|---|---|---|
| `InputRequired.elicitForm(message, schema)` | asks the user to fill in a form | `elicitation` (form mode) |
| `InputRequired.elicitUrl(message, url)` | asks the user to open a URL | `elicitation.url` |
| `InputRequired.sample(params)` | samples its LLM | `sampling` |
| `InputRequired.listRoots` | sends its roots | `roots` |

On the retry, the handler reads the answers under the same keys from `ctx.request`: `elicitResult(key)`, `samplingResult(key)` and `rootsResult(key)`. A handler that never returns `InputRequired` works as before.

```scala mdoc:compile-only
import chimp.server.*
import io.circe.{Codec, Json}
import sttp.shared.Identity
import sttp.tapir.*

case class NoInput() derives Codec, Schema

val nameSchema = Json.obj(
"type" -> Json.fromString("object"),
"properties" -> Json.obj("name" -> Json.obj("type" -> Json.fromString("string")))
)

val greet = tool("greet")
.input[NoInput]
.serverLogicWithContext[Identity]: (_, ctx, _) =>
ctx.request.elicitResult("user_name").flatMap(_.content).flatMap(_.get("name")).flatMap(_.asString) match
case Some(name) => ToolResult.text(s"Hello, $name!")
case None => InputRequired("user_name" -> InputRequired.elicitForm("What is your name?", nameSchema))
```

Prompts and resources use the same `InputRequired` from their `serverLogicWithContext`.

### Several rounds and the request state

A handler can ask again on the retry, as many times as it needs. To remember what happened in the earlier rounds, it attaches a **request state** with `.withRequestState(state)`. The client sends the state back without a change on its retry, and the handler reads it from `ctx.request.requestState`. `InputRequired.withRequestState(state)` makes an outcome that has a state and no input requests: the client then retries at once.

```{warning}
The request state goes through the client, so treat it as input from an attacker. If the state controls authorization, resource access or business logic, protect its integrity with a [request state signer](#protecting-the-request-state).
```

### Missing answers

If the retry does not have an answer that the handler needs, return a new `InputRequired` that asks for it again. Do not fail the request. The client can omit an answer, or send it under a different key. Keys that the handler did not ask for are ignored.

### Client capabilities

A handler can read `ctx.request.clientCapabilities` and ask only for what the client supports. For example, it can ask for sampling when the client declares `sampling`, and for a form if not.

## Rules that chimp enforces

chimp applies these rules, so a handler does not have to:

| Problem | Result |
|---|---|
| an input request that needs a capability which the client did not declare | `-32021` MissingRequiredClientCapability with `data.requiredCapabilities`, HTTP `400` |
| `inputResponses` is not an object, or one of its values is not a sampling, roots or elicitation result | `-32602` InvalidParams, HTTP `400`; the handler does not run |
| `requestState` is not a string | `-32602` InvalidParams, HTTP `400`; the handler does not run |
| `InputRequired` on a legacy (`2025-11-25` or earlier) request | `-32603` InternalError which names protocol version `2026-07-28` |

An `InputRequired` always has at least one input request or a request state. Only `tools/call`, `prompts/get` and `resources/read` can end with it.

On a streaming HTTP server, chimp opens the event stream when the handler sends its first message. If the handler ends with the `-32021` before it sends a message, chimp sends a plain JSON error with HTTP `400`. If the handler already sent a message, for example a progress notification, the `-32021` is the last message on the event stream.

## Protecting the request state

Give the server a `RequestStateSigner` to protect the integrity of all request states:

```scala mdoc:compile-only
import chimp.server.*
import sttp.shared.Identity
import scala.concurrent.duration.*

val secret: Array[Byte] = sys.env("MCP_REQUEST_STATE_SECRET").getBytes("UTF-8")

val server = McpServer[Identity]()
.withRequestStateSigner(RequestStateSigner(secret, ttl = 5.minutes))
```

The handler code does not change. When a handler returns a request state, chimp signs it with HMAC-SHA256. The signature also covers:

- an expiry, after the `ttl` (10 minutes by default),
- the method, the tool or prompt name or the resource URI, and a digest of the arguments of the request,
- on a secured server, the principal: use `withRequestStateSigner(signer, principalId)`, where `principalId` gives a stable identifier of the principal.

On the retry, chimp verifies the state before the handler runs, and gives the handler the original state. If the state was changed, has expired, or belongs to another request or principal, chimp sends `-32602` InvalidParams with HTTP `400`, and the handler does not run.

Security notes:

- The secret must have at least 32 bytes. Keep it in a secret store, not in the code. All instances of the server must use the same secret, or a retry can fail on a different instance.
- When you change the secret, all request states that are in progress become invalid. The clients must start these requests again.
- The signer protects the integrity of the state, not its confidentiality. The client can read the state, so do not put secrets in it.
- The signer does not make a state single-use. Within its lifetime, the client can send the same state again on the same request. If an action must occur only one time, record it on the server.

2 changes: 2 additions & 0 deletions docs/server/prompts.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@ val endpoint = McpServer(prompts = List(greeting)).endpoint(List("mcp"))
```

Prompt messages reuse the `ToolContent` content types, so they can embed images (`ToolContent.Image`) and resources (`ToolContent.ResourceContent`) just like tool results.

A prompt can also ask the client for input before it returns its messages: see [asking the client for input](mrtr.md).
3 changes: 3 additions & 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 All @@ -26,3 +27,5 @@ val endpoint = McpServer(resources = List(readme), resourceTemplates = List(item
```

Returning `Left(ResourceError(...))` (or reading an unknown URI) responds with a JSON-RPC error carrying the offending `uri`.

A resource can also ask the client for input before it returns its contents: see [asking the client for input](mrtr.md).
Loading
Loading