Skip to content

feat!: implement SEP-2575 stateless MCP - #985

Open
devcrocod wants to merge 10 commits into
mainfrom
devcrocod/sep-2575-stateless-mcp
Open

devcrocod wants to merge 10 commits into
mainfrom
devcrocod/sep-2575-stateless-mcp

Conversation

@devcrocod

Copy link
Copy Markdown
Contributor

Implements SEP-2575 alongside the legacy handshake era.
Closes #815

  • Per-request _meta envelope; resultType on every result, cache hints (ttlMs/cacheScope)
  • Error codes -32020/-32021/-32022; -32002 no longer emitted
  • server/discover (auto-registered); era-gated method registry
  • Modern Streamable HTTP: POST-only, sessionless, deferred SSE commit
  • Client version negotiation (Legacy/Auto/Pin) + opt-in response cache

Breaking Changes

  • RequestResult.meta: JsonObject? -> ResultMeta?; resultType added to result data classes
  • LATEST_PROTOCOL_VERSION -> 2026-07-28, SUPPORTED_PROTOCOL_VERSIONS deprecated
  • Legacy-only methods answer -32601 on modern connections

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

@devcrocod
devcrocod requested review from e5l and a lite review from Copilot September 8, 2026 11:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

A verified logic issue in ClientConnectionImpl.isMessageAccepted can incorrectly allow log notifications when there is no current request context, which violates the request-scoped opt-in semantics.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

Implements SEP-2575 stateless (request-scoped) MCP alongside the legacy initialize-handshake lifecycle. This updates core wire types/serialization, adds dual-era Streamable HTTP routing and classification, introduces discovery/version negotiation, and adds an opt-in client response cache.

Changes:

  • Add modern/request-scoped lifecycle support: per-request _meta envelope, server/discover, era-gated method surface, and updated error codes.
  • Update core result wire format: ResultMeta, resultType across results, and cache directives (ttlMs/cacheScope) on the spec-defined cacheable results.
  • Add client-side version negotiation (Legacy/Auto/Pin) and a response cache keyed by method/params + invalidated by list-changed notifications.
File summaries
File Description
kotlin-sdk-server/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/server/StreamableHttpServerTransportTest.kt Adjust handshake-era tests for version constant + result meta type.
kotlin-sdk-server/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/server/StatelessStreamableHttpSessionLifecycleTest.kt Update stateless HTTP lifecycle tests to use handshake version constant.
kotlin-sdk-server/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/server/ModernStreamableHttpTest.kt New tests asserting modern Streamable HTTP contract (status codes, headers, SSE commit behavior).
kotlin-sdk-server/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/server/ServerSessionAssertCapabilityTest.kt Update tests for renamed handshake version constant.
kotlin-sdk-server/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/server/InboundClassificationTest.kt New classifier rung-by-rung tests for modern-vs-legacy inbound routing.
kotlin-sdk-server/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/server/StreamableHttpServerTransport.kt Support dual-era entry by accepting pre-read body; tighten handshake-version validation; use ordered version comparison.
kotlin-sdk-server/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/server/ServerSession.kt Track negotiated handshake protocol version and expose server-info stamping configuration.
kotlin-sdk-server/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/server/Server.kt Add server/discover auto-registration; allow non-subscribing request-scoped sessions; modernize error mapping behavior.
kotlin-sdk-server/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/server/LoggingLevels.kt New helper to compute per-request allowed logging levels under modern lifecycle.
kotlin-sdk-server/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/server/KtorServer.kt Route a single POST endpoint across both lifecycles by classifying the body once.
kotlin-sdk-server/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/server/ClientConnection.kt Enforce per-request capability declaration + modern-era restrictions; update log filtering behavior.
kotlin-sdk-server/api/kotlin-sdk-server.api API dump updates for ServerOptions and ServerSession surface changes.
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/types/WireTest.kt New tests for lifecycle-specific outbound wire shaping and error code mapping.
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/types/ToolsTest.kt Update expected serialization for ResultMeta, resultType, and caching directives.
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/types/TasksTest.kt Update expected serialization for resultType + ResultMeta.
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/types/SamplingTest.kt Update expected serialization for resultType + ResultMeta.
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/types/RootsTest.kt Update expected serialization for resultType + ResultMeta.
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/types/ResultTypeTest.kt New tests for defaulting/validation of resultType across result types.
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/types/ResourcesTest.kt Update expected serialization for resultType + caching directives + ResultMeta.
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/types/RequestTest.kt Update request-meta tests to use envelope conversion and new meta APIs.
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/types/ProtocolVersionsTest.kt New tests ensuring version partitioning and ordering semantics.
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/types/PromptsTest.kt Update expected serialization for resultType + caching directives + ResultMeta.
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/types/MethodEraTest.kt New tests asserting which methods exist in which lifecycle.
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/types/JsonRpcTest.kt Update test to use ResultMeta for response meta.
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/types/InitializeTest.kt Update expected initialize wire shape (now includes resultType in typed form).
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/types/ElicitationTest.kt Update expected serialization for resultType + ResultMeta.
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/types/DiscoveryTest.kt Update discovery request/result parsing expectations for envelope + tolerant cache defaults.
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/types/CompletionTest.kt Update expected serialization for resultType + ResultMeta.
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/types/CommonTypeTest.kt Update tests for new latest version constants and deprecated union behavior.
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/types/CacheableResultTest.kt New tests covering cache directive defaults, validation, and round-tripping.
kotlin-sdk-core/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/shared/ProtocolOutboundCancellationTest.kt Update handshake protocol version constant in tests.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/wire.kt New outbound wire shaping + inbound resultType validation helpers.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/UrlElicitationRequiredException.kt Keep deprecated code accepted while documenting modern removal context.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/tools.kt Add resultType, migrate meta to ResultMeta, implement cacheable result fields/validation.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/tasks.kt Add resultType, migrate meta to ResultMeta, update payload result meta extraction.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/serializers.kt Update polymorphic selection rules for empty/discovery/initialize result decoding.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/sampling.kt Add resultType + ResultMeta to sampling results.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/roots.kt Add resultType + ResultMeta to roots results.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/resources.kt Add resultType, cache directives, and ResultMeta to resource results (+ validation).
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/request.kt Introduce COMPLETE_RESULT_TYPE, reshape RequestResult, add claimedProtocolVersion.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/prompts.kt Add resultType, cache directives, and ResultMeta to prompt results (+ validation).
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/methods.kt Add per-method lifecycle availability declarations.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/mcpHeaders.kt New shared constants + header value encoding/decoding for MCP HTTP headers.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/McpException.kt Keep accepting deprecated peer error codes while documenting intent.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/jsonRpc.kt Add new spec-reserved error codes and deprecate retired ones.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/initialize.kt InitializeResult defaults to latest handshake version; add resultType + ResultMeta.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/era.kt New internal era model and method availability predicate.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/elicitation.kt Add resultType + ResultMeta to elicitation results.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/discovery.kt Discovery request/result types updated for request-scoped lifecycle + cache directives.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/completion.kt Add resultType + ResultMeta to completion results.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/common.kt Split protocol versions by lifecycle; add version ordering helpers; introduce ResultMeta.
kotlin-sdk-core/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/types/caching.kt New cache directives model (CacheScope, CacheableResult).
kotlin-sdk-client/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/client/VersionNegotiationTest.kt New tests for modern probe classifier and fallback/pin behavior.
kotlin-sdk-client/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/client/streamable/http/StreamableHttpClientTransportTest.kt Update expectations for notifications: omit standard MCP headers.
kotlin-sdk-client/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/client/ClientAssertCapabilityTest.kt Update handshake protocol version constant in tests.
kotlin-sdk-client/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/client/VersionNegotiation.kt New client-side discovery probe outcome classifier for lifecycle selection.
kotlin-sdk-client/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/client/StreamableHttpClientTransport.kt Use shared header constants/encoding; restrict standard headers to requests (not notifications).
kotlin-sdk-client/src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/client/ResponseCache.kt New response cache store + invalidation logic driven by notifications.
integration-test/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/testing/ChannelTransportTest.kt Update handshake protocol version constant in integration tests.
integration-test/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/server/ServerSessionInitializeTest.kt Update handshake protocol version constant in integration tests.
integration-test/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/server/ServerResourceTemplateTest.kt Update expected error code for resource-not-found behavior.
integration-test/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/server/SamplingTest.kt Update capability enforcement expectations to structured McpException w/ missing-capability data.
integration-test/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/integration/streamablehttp/StreamableHttpSseReconnectTest.kt Update handshake protocol version constant for SSE reconnect.
integration-test/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/integration/streamablehttp/StreamableHttpIntegrationTest.kt Update handshake protocol version constant in client transport config.
integration-test/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/integration/streamablehttp/StreamableHttpHeartbeatIntegrationTest.kt Update handshake protocol version constant for heartbeat tests.
integration-test/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/integration/ResponseCacheTest.kt New end-to-end tests for client response cache reuse and invalidation behavior.
integration-test/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/integration/RequestScopedLifecycleTest.kt New end-to-end tests for request-scoped envelope semantics and modern-vs-legacy behavior.
integration-test/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/integration/ProtocolConcurrencyIntegrationTest.kt Update decoding path for results given new wire wrapper behavior.
integration-test/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/integration/ModernStreamableHttpStreamTest.kt New real-engine test asserting committed SSE stream ordering/completeness.
integration-test/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/integration/ModernStreamableHttpDisconnectTest.kt New real-engine tests for request-scoped cancellation/disconnect behavior.
integration-test/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/integration/MalformedEnvelopeFieldTest.kt New integration coverage for malformed optional envelope fields handling.
integration-test/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/integration/kotlin/AbstractResourceIntegrationTest.kt Update resource-not-found expectation to INVALID_PARAMS and document rationale.
integration-test/src/jvmTest/kotlin/io/modelcontextprotocol/kotlin/sdk/integration/EraInterleavingTest.kt New integration tests asserting per-request lifecycle interleaving over one connection.
integration-test/src/commonTest/kotlin/io/modelcontextprotocol/kotlin/sdk/client/ClientTest.kt Update legacy tests for protocol version constants + capability-missing exceptions + result read-back.
Review details
  • Files reviewed: 82/82 changed files
  • Comments generated: 1
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +369 to +377
private suspend fun isMessageAccepted(level: LoggingLevel): Boolean {
val extra = currentRequestHandlerExtra()
// Outside a handler there is no request to have opted in, so nothing is deliverable on
// the request-scoped lifecycle and the connection-scoped filter applies on the other.
?: return session.protocolVersion?.let { isModernProtocolVersion(it) } != true &&
acceptedByLevelSetting(level)
if (level !in allowedLogLevels(extra.protocolVersion, extra.meta)) return false
return acceptedByLevelSetting(level)
}

@e5l e5l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for me locally many tests are flaking:

java.util.concurrent.TimeoutException: testConcurrentRequests() timed out after 60 seconds
	at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:387)
	at java.base/java.util.concurrent.ForkJoinPool.helpJoin(ForkJoinPool.java:2076)
	at java.base/java.util.concurrent.ForkJoinTask.awaitDone(ForkJoinTask.java:423)
	at java.base/java.util.concurrent.ForkJoinTask.join(ForkJoinTask.java:651)
	at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:387)
	at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.tryRemoveAndExec(ForkJoinPool.java:1351)
	at java.base/java.util.concurrent.ForkJoinTask.awaitDone(ForkJoinTask.java:422)
	at java.base/java.util.concurrent.ForkJoinTask.join(ForkJoinTask.java:651)
	at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:387)
	at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1312)
	at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1843)
	at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1808)
	at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:188)
	Suppressed: java.lang.InterruptedException
		at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:58)
		at kotlinx.coroutines.BuildersKt__BuildersKt.runBlockingImpl(Builders.kt:30)
		at kotlinx.coroutines.BuildersKt.runBlockingImpl(Unknown Source)
		at kotlinx.coroutines.BuildersKt__Builders_concurrentKt.runBlockingK(Builders.concurrent.kt:172)
		at kotlinx.coroutines.BuildersKt.runBlockingK(Unknown Source)
		at io.modelcontextprotocol.kotlin.sdk.integration.typescript.AbstractKotlinClientTsServerEdgeCasesTest.testConcurrentRequests(AbstractKotlinClientTsServerEdgeCasesTest.kt:90)
		at java.base/java.lang.reflect.Method.invoke(Method.java:580)
		at io.modelcontextprotocol.kotlin.test.utils.RetryExtension.executeWithRetry(Retry.kt:39)
		at io.modelcontextprotocol.kotlin.test.utils.RetryExtension.interceptTestMethod(Retry.kt:25)
		... 13 more
		Suppressed: java.lang.IllegalStateException: TypeScript HTTP server did not become ready on localhost:61362 within timeout
			at io.modelcontextprotocol.kotlin.sdk.integration.typescript.TypeScriptServer.startHttp(TypeScriptServer.kt:59)
			at io.modelcontextprotocol.kotlin.sdk.integration.typescript.TsTestBase$Companion.getSharedHttpUrl(TsTestBase.kt:61)
			at io.modelcontextprotocol.kotlin.sdk.integration.typescript.TsTestBase.getSharedHttpUrl(TsTestBase.kt)
			at io.modelcontextprotocol.kotlin.sdk.integration.typescript.http.KotlinClientTsServerEdgeCasesTestHttp.serverUrl_delegate$lambda$0(KotlinClientTsServerEdgeCasesTestHttp.kt:11)
			at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:86)
			at io.modelcontextprotocol.kotlin.sdk.integration.typescript.http.KotlinClientTsServerEdgeCasesTestHttp.getServerUrl(KotlinClientTsServerEdgeCasesTestHttp.kt:11)
			at io.modelcontextprotocol.kotlin.sdk.integration.typescript.http.KotlinClientTsServerEdgeCasesTestHttp.useClient(KotlinClientTsServerEdgeCasesTestHttp.kt:13)
			at io.modelcontextprotocol.kotlin.sdk.integration.typescript.AbstractKotlinClientTsServerEdgeCasesTest$testConcurrentRequests$1.invokeSuspend(AbstractKotlinClientTsServerEdgeCasesTest.kt:91)
			at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:34)
			at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:100)
			at kotlinx.coroutines.internal.LimitedDispatcher$Worker.run(LimitedDispatcher.kt:124)
			at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:89)
			at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:586)
			at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:798)
			at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:717)
			at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:704)

Could you please check what is the reason?

}

if (!response.status.isSuccess()) {
val error = StreamableHttpError(response.status.value, response.bodyAsText())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we retry connection with fallback in case of legacy response?

- split the version registry into handshake and modern revisions
- add `resultType` and cache hints to results; result `meta` becomes `ResultMeta`
- add error codes -32020/-32021/-32022; stop emitting -32002
- add `server/discover`, registered on every server
- gate each method by the eras it exists in
- add modern Streamable HTTP: POST-only, sessionless, deferred SSE commit
- add client version negotiation (Legacy/Auto/Pin) and a response cache
- wrap result `meta` in `ResultMeta` and expect `resultType` and cache hints in tests added on main
- use `LATEST_HANDSHAKE_VERSION` in initialize fixtures added on main
- regenerate ABI dumps, including the klib ones
@devcrocod
devcrocod force-pushed the devcrocod/sep-2575-stateless-mcp branch from aa7a9ef to f0e5530 Compare November 16, 2026 16:17
Copilot AI lite review requested due to automatic review settings November 16, 2026 16:17

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Approval is blocked by two critical response-cache isolation flaws that can leak cached data across servers or authorization contexts, plus a capability-check ordering bug that returns the wrong error for removed sampling methods.

4 open issues

Review effort: Lite

Comment on lines +40 to +41
@ExperimentalMcpApi
public data class CacheKey(val method: String, val paramsKey: String = "", val partition: String = "")
Comment on lines +36 to +41
* @property partition the authorization context the result was fetched under, supplied by the
* caller. A [CacheScope.Private] entry is never served across partitions; empty scopes it to this
* client instance.
*/
@ExperimentalMcpApi
public data class CacheKey(val method: String, val paramsKey: String = "", val partition: String = "")
Copilot AI lite review requested due to automatic review settings November 20, 2026 12:36
…ream (#1191)

## Why

Goal: close the confirmed review findings on #985 with atomic fixes.
Follow-up to #985.

A handler that sent a server-to-client request on the request-scoped
lifecycle, for example `ping()` from a tool, put that request on the SSE
response stream. It then waited out its own request timeout (60 s by
default) for an answer no client can send. The 2026-07-28 Streamable
HTTP spec says: "The server **MUST NOT** send independent JSON-RPC
*requests* on this stream."

## What changed

`SingleExchangeTransport.send` throws `McpException(METHOD_NOT_FOUND)`
for a `JSONRPCRequest` and puts nothing on the stream.
`Protocol.request` calls `send` inside its own try, so the caller gets
the refusal at once. The class KDoc now describes what the code does.

## Scope

Only the request-scoped (modern) leg of the stateless endpoint. The
legacy leg and `mcpStreamableHttp` are untouched.

## Tradeoffs

- Guarding `ClientConnection.ping()` the way `listRoots()` is guarded
would cover ping only. The transport guard covers every request, custom
methods included.
- Dropping the request without throwing keeps the stream clean but still
leaves the caller waiting for its timeout.

## Blast Radius

Server code that sends any request from inside a modern handler now gets
`-32601` straight away. Before, it got `-32001` after the timeout.
Notifications and the final response follow the same path as before.

## Verification

- Failing first: `ModernStreamableHttpTest."a server-to-client request
from a handler is refused instead of sent on the response stream"`.
Before the fix the body started with `data:
{"id":"…","method":"ping","jsonrpc":"2.0"}` and the handler saw `-32001`
after 5 s. After the fix it passes in 13 ms.
- Local: `:kotlin-sdk-server:jvmTest`, `:integration-test:jvmTest
--tests "*ModernStreamableHttp*"`, `ktlintCheck detekt checkKotlinAbi`
all pass.
- CI: build
https://github.com/modelcontextprotocol/kotlin-sdk/actions/runs/44268459697
passed on attempt 2. Conformance
https://github.com/modelcontextprotocol/kotlin-sdk/actions/runs/44268464794
passed.
- Attempt 1 failed in `ResponseCacheTest` and
`RequestScopedLifecycleTest` with "The server/discover probe timed out".
Those tests use the in-memory `ChannelTransport`, which this change does
not touch. The same flake hits other branches off the same base.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

A critical active finding remains because the cache key omits server or endpoint identity, allowing cross-server collisions and potential data leakage.

3 open issues
1 resolved since last review

Review effort: Lite

Copilot AI lite review requested due to automatic review settings November 20, 2026 12:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

A critical active issue allows private cached responses to cross client principals when shared stores use the default partition, so the change is not safe to approve.

3 open issues

Review effort: Lite

…1198)

## Why

Goal: turn the confirmed review findings on #985 into atomic fixes.
Follow-up to #985.

A handler that returns `EmptyResult()` explicitly answers a
request-scoped request with `{}`. `EmptyResult.resultType` defaults to
`null`, and the Modern branch of `encodeOutboundResult` never adds the
field. `schema.ts` (`interface Result`) says servers on 2026-07-28 MUST
include `resultType`. Only a handler that returned `null` got
`{"resultType":"complete"}`.

## What changed

`wire.kt`: on `ProtocolEra.Modern`, `encodeOutboundResult` adds
`"resultType": "complete"` when the encoded result has no `resultType`.
A result that already declares one is sent unchanged.

## Scope

Handshake-era output is unchanged, so `{}` still goes to handshake peers
that reject unknown keys.

## Blast Radius

Every request-scoped response now carries `resultType`. Typed results
already did, so in practice this changes explicit `EmptyResult()` and
opaque payloads such as `WireResult` that lack the field.

## Verification

- New test `ProtocolTest.an explicit empty result declares itself
complete on a request-scoped request` failed before the fix with `The
top level object was missing expected field(s) [resultType] ... but
was:<{}>`, and passes after it.
- Local: `./gradlew :kotlin-sdk-core:jvmTest :kotlin-sdk-server:jvmTest
:kotlin-sdk-client:jvmTest :integration-test:jvmTest ktlintCheck detekt
checkKotlinAbi` passes.
- CI (dispatched): build
https://github.com/modelcontextprotocol/kotlin-sdk/actions/runs/44295659333,
conformance
https://github.com/modelcontextprotocol/kotlin-sdk/actions/runs/44295664870

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI lite review requested due to automatic review settings November 20, 2026 13:22

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

A critical active finding shows that shared default response caches can return a private result from one client instance to another, violating the documented isolation guarantee.

3 open issues

Review effort: Lite

## Why
Goal: Auto negotiation reaches a silent legacy stdio server after a
reasonable wait, as the 2026-07-28 stdio backward-compatibility rules
require. Follow-up to #985.

The probe passed no `RequestOptions`, so it waited the full 60 s
`DEFAULT_REQUEST_TIMEOUT` before falling back. Per the spec, legacy
servers answer unknown pre-`initialize` requests "with
implementation-defined errors ... or not at all", and a server that
"does not respond within a reasonable timeout" is legacy. The
`ProbeOutcome.Silent` KDoc already referred to a probe timeout that did
not exist.

## What changed
- `STDIO_PROBE_TIMEOUT = 10.seconds` (internal,
`VersionNegotiation.kt`). `negotiateRequestScoped` uses it when the
probe runs over stdio with a fallback available, and `probeDiscovery`
passes it as the request timeout.
- HTTP probes and `Pin` keep `DEFAULT_REQUEST_TIMEOUT`. Silence never
selects the handshake there, so a slow answer is still worth waiting
for.
- The `VersionNegotiationMode.Auto` KDoc states the ten-second wait.

## Scope
`VersionNegotiationMode.Auto` over `StdioClientTransport`.

## Tradeoffs
- Why 10 s: well beyond the few seconds a warm Node, Python or JVM stdio
server takes to start and answer, and a sixth of the request timeout. A
modern server slower than that to start (a cold `npx` download, say) is
taken for legacy. A dual-era server then connects on the handshake, and
a modern-only one fails with its `initialize` rejection.
- Not configurable. `ClientOptions` has no probe settings, and adding
one is a public API change, not a one-liner. `ProtocolOptions.timeout`
exists, but `Protocol.request` never reads it (pre-existing).

## Blast Radius
Auto clients over stdio whose server stays silent now fall back after 10
s instead of 60 s. Modern servers that answer within 10 s see no change.

## Verification
- `StdioVersionProbeTest` (new, jvmTest): a real `StdioClientTransport`
over pipes and a scripted server that ignores `server/discover`. Before
the fix it failed after 30.3 s with "Error connecting to transport: Not
connected", meaning the client was still waiting on the probe when the
server hung up at half the request timeout. After, it passes in 10.4 s.
- Local: `:kotlin-sdk-client:jvmTest` 69/0, `:integration-test:jvmTest`
159/0, `ktlintCheck detekt checkKotlinAbi` clean.
- Independent of #1195: branched from the stateless base, and `git
merge-tree` with #1195's branch is clean.
- CI: Build
https://github.com/modelcontextprotocol/kotlin-sdk/actions/runs/44296439215
(success on attempt 3). Conformance
https://github.com/modelcontextprotocol/kotlin-sdk/actions/runs/44296443812
(success).
- Attempts 1-2 failed only in `RequestScopedLifecycleTest`, the known
base flake. Its cause: `ChannelTransport` delivers messages before
`AbstractClientTransport.start()` marks it `Operational`, so a server
reply sent in that window fails with "Transport is not ready" and is
lost. That code comes from main and is untouched here. The shorter probe
timeout applies only to `StdioClientTransport`, so it cannot make that
flake more frequent.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI lite review requested due to automatic review settings November 20, 2026 18:58
…RSIONS (#1201)

## Why

Goal: turn the confirmed review findings on #985 into atomic fixes.
Follow-up to #985.

The deprecated `SUPPORTED_PROTOCOL_VERSIONS` silently changed meaning.
At af5d784 it was `["2025-11-25", "2025-06-18", "2025-03-26",
"2024-11-05"]`, newest first and handshake revisions only. On this
branch it became oldest-first and gained `"2026-07-28"`. A caller that
reads `.first()` as the preferred version, or validates `initialize`
against the list, changes behavior with no compile error. Its
`ReplaceWith("HANDSHAKE_PROTOCOL_VERSIONS")` also gives a different
order.

## What changed

- `SUPPORTED_PROTOCOL_VERSIONS` is
`HANDSHAKE_PROTOCOL_VERSIONS.reversed()`, the same value and order as at
af5d784.
- `ReplaceWith` is now `HANDSHAKE_PROTOCOL_VERSIONS.reversed()`, so the
IDE quick-fix keeps behavior.
- The KDoc and deprecation message describe what the list holds.
- `ProtocolVersionsTest` replaces the test that pinned the union with
one that pins the base value and the `ReplaceWith` equivalence.

## Scope

No code in this repository reads the symbol any more (`rg
SUPPORTED_PROTOCOL_VERSIONS` finds only the test and the API dumps).
Only external callers see the change. The signature is unchanged, so no
ABI dump update.

## Verification

- `ProtocolVersionsTest.the deprecated list should keep its
handshake-only newest-first value` failed before the fix with
`Collection should contain exactly: ["2025-11-25", "2025-06-18",
"2025-03-26", "2024-11-05"] but was: ["2024-11-05", "2025-03-26",
"2025-06-18", "2025-11-25", "2026-07-28"]`, and passes after it.
- Local: `./gradlew :kotlin-sdk-core:jvmTest ktlintCheck detekt
checkKotlinAbi` passes.
- CI (dispatched):
https://github.com/modelcontextprotocol/kotlin-sdk/actions/runs/44296964820

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

A critical active finding remains because the default cache partition can cause private responses to leak between clients sharing a store.

3 open issues

Review effort: Lite

Copilot AI lite review requested due to automatic review settings November 20, 2026 19:05

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

A critical active issue allows a shared response cache to return data from one MCP server while connected to another because the cache key lacks server identity.

3 open issues

Review effort: Lite

## Why

Follow-up to #985. Goal: `discover()` describes the server this client
is connected to now. `connect` stored the adopted `server/discover`
result, but nothing cleared it on close or reconnect. After `Auto`
connected to a request-scoped server and the same client later
reconnected and fell back to the handshake, `discover()` still returned
the first server's result. Its KDoc promises `METHOD_NOT_FOUND` on a
handshake connection.

## What changed

`connect` clears the stored discovery result right after attaching the
transport. A reconnect settled by discovery stores the new result as
before. A reconnect settled by the handshake leaves it empty, so
`discover()` asks the server, and a server without `server/discover`
refuses with `METHOD_NOT_FOUND`.

## Scope

One line in `Client.connect`. No public API change.

## Tradeoffs

`discover()` still ignores the result's `ttlMs`, and the result is held
for the whole connection. Honoring it is not a consequence of this fix,
so it is left as a follow-up.

## Blast Radius

Clients that reconnect the same `Client` instance and call `discover()`.

## Verification

- `RequestScopedLifecycleTest > discover is refused after a reconnect
falls back to the handshake`. The client connects to a request-scoped
server, then reconnects to a server with no `server/discover` handler,
and the test asserts the fallback before calling `discover()`. Before
the fix: `Expected an exception of class McpException to be thrown, but
was completed successfully with the result: <DiscoverResult(...)>`, 3 of
3 runs. After: passes.
- Local: `:kotlin-sdk-client:jvmTest`, `:integration-test:jvmTest`,
`ktlintCheck detekt checkKotlinAbi` green.
- CI: Build
https://github.com/modelcontextprotocol/kotlin-sdk/actions/runs/44301946538
(green on attempt 5), Conformance
https://github.com/modelcontextprotocol/kotlin-sdk/actions/runs/44301951404
(green). Attempts 1 to 4 each failed only base tests, which hung at
in-memory `connect`, a hang the base already has.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI lite review requested due to automatic review settings November 20, 2026 19:20

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

A critical active finding shows that private response-cache entries can collide across clients sharing a store, allowing one client’s authorization-scoped result to be served to another.

3 open issues

Review effort: Lite

devcrocod pushed a commit that referenced this pull request Nov 20, 2026
…perational (#1207)

## Why

Follow-up to #985. Goal: remove the CI flake that makes PRs on the
stateless branch green only on rerun. `RequestScopedLifecycleTest` and
`ResponseCacheTest` fail with "server/discover probe timed out" or
"Expected 2026-07-28 but actual was null". Every failing log has `Error
handling request: server/discover ... McpException: Transport is not
ready` from `AbstractClientTransport.send`. The defect is on main.

`AbstractClientTransport.start()` runs `initialize()`, where transports
start their readers, and only then moves to `Operational`. A reader can
hand a request to `Protocol` in that window. The handler's reply hits
the state check in `send()` and is dropped, so the peer waits out its
timeout. Sometimes the error reply gets through instead, and the client
reads it as a refusal and falls back to legacy. The integration tests
start `server.createSession` and `client.connect` concurrently over
`ChannelTransport`, and slow CI runners widen the window.

## What changed

- `AbstractClientTransport` overrides `onMessage` so that handlers wait
on a deferred that `start()` completes right after the `Operational`
transition. Nothing changes once the transport is running.
- ABI dump: `AbstractClientTransport` now declares the `onMessage` it
already inherited (a binary-compatible addition).
- Removed the comment in `ProtocolConcurrencyIntegrationTest` that
described early delivery. It no longer holds.

## Scope

The fix goes in the base class because the pattern is shared.
`ChannelTransport` and `StdioClientTransport` both start readers in
`initialize()` and deliver before `Operational`. `SseClientTransport`
can too, once the endpoint event has arrived.
`StreamableHttpClientTransport` delivers only after a send, so it is
unaffected. Server transports extend `AbstractTransport`, which has no
state gate on `send`.

## Tradeoffs

A subclass whose `initialize()` waits for a JSON-RPC message to be
handled would now block. No transport in this repo does that. The
closest case is an SSE server that breaks the spec by sending a JSON-RPC
event before `endpoint`: `start()` would now hang instead of losing the
reply. Fixing this per transport instead would mean overriding
`start()`, which its KDoc forbids, and repeating the same fix in every
reader.

## Blast Radius

All `AbstractClientTransport` subclasses, including third-party ones,
now get inbound messages only after `start()` returns. Delivery after
that is unchanged.

## Verification

- `ChannelTransportTest.answers a request the peer sent before start
returned` runs the event loop on its own scheduler while `start()` is
suspended. Before the fix: `Expected
JSONRPCResponse(id=NumberId(value=1), ...) but actual was null`, with
`Transport is not ready` in the log. Passes after the fix (JVM, JS,
Wasm).
- `AbstractClientTransportTest.should answer a message received during
initialization once OPERATIONAL`. Before the fix:
`expected:<[JSONRPCResponse(...)]> but was:<[]>`. Passes after the fix.
- Local: `jvmTest` for core, testing, client, server and
integration-test, plus `ktlintCheck detekt checkKotlinAbi`, all green.
- CI on ec7a026:
[Build](https://github.com/modelcontextprotocol/kotlin-sdk/actions/runs/44327698576)
(Linux and iOS simulator) and
[Conformance](https://github.com/modelcontextprotocol/kotlin-sdk/actions/runs/44327698533),
both green.
- Stress loop on the stateless branch: the flake hit 10 of 131 baseline
runs and 0 of 131 runs with this fix, and every baseline failure logged
`Transport is not ready`. Details in [this
comment](#1207 (comment)).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement SEP-2575: Make MCP Stateless

4 participants