Title: `HttpServletStreamableServerTransportProvider` removes session on non-fatal failure · Issue #952 · modelcontextprotocol/java-sdk · GitHub
Open Graph Title: `HttpServletStreamableServerTransportProvider` removes session on non-fatal failure · Issue #952 · modelcontextprotocol/java-sdk
X Title: `HttpServletStreamableServerTransportProvider` removes session on non-fatal failure · Issue #952 · modelcontextprotocol/java-sdk
Description: Bug description We use the MCP Java SDK as via our dependency on Spring AI. Our CI/CD test coverage for our MCP implementation fails regularly with a race condition when dealing with intentional error conditions. We could not reproduce i...
Open Graph Description: Bug description We use the MCP Java SDK as via our dependency on Spring AI. Our CI/CD test coverage for our MCP implementation fails regularly with a race condition when dealing with intentional er...
X Description: Bug description We use the MCP Java SDK as via our dependency on Spring AI. Our CI/CD test coverage for our MCP implementation fails regularly with a race condition when dealing with intentional er...
Opengraph URL: https://github.com/modelcontextprotocol/java-sdk/issues/952
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"`HttpServletStreamableServerTransportProvider` removes session on non-fatal failure","articleBody":"**Bug description**\nWe use the MCP Java SDK as via our dependency on Spring AI. Our CI/CD test coverage for our MCP implementation fails regularly with a race condition when dealing with intentional error conditions. We could not reproduce it locally on dev machines, but via logging eventually found a workaround to what appears to be a problem in HttpServletStreamableTransportProvider.\n\n**Environment**\nVersions 1.1.1, 1.1.2, and 2.0.0-M2 of the Java SDK. Prerelease versions of Spring AI 2.0, including 2.0.0-M5 and 2.0.0-M4. Java 25.\n\n**Steps to reproduce**\n\nSee attached for a standalone repro. The error manifested for us as a race condition but always of this form:\n\n```\n java.lang.RuntimeException: MCP session with server terminated\n at io.modelcontextprotocol.spec.McpClientSession.lambda$dismissPendingResponses$1(McpClientSession.java:128)\n at java.base/java.util.concurrent.ConcurrentHashMap.forEach(ConcurrentHashMap.java:1619)\n at io.modelcontextprotocol.spec.McpClientSession.dismissPendingResponses(McpClientSession.java:126)\n at io.modelcontextprotocol.spec.McpClientSession.close(McpClientSession.java:304)\n at io.modelcontextprotocol.client.LifecycleInitializer$DefaultInitialization.close(LifecycleInitializer.java:225)\n at io.modelcontextprotocol.client.LifecycleInitializer.handleException(LifecycleInitializer.java:257)\n at io.modelcontextprotocol.client.transport.HttpClientStreamableHttpTransport.handleException(HttpClientStreamableHttpTransport.java:231)\n at io.modelcontextprotocol.client.transport.HttpClientStreamableHttpTransport.lambda$sendMessage$33(HttpClientStreamableHttpTransport.java:641)\n at reactor.core.publisher.FluxOnErrorReturn$ReturnSubscriber.onError(FluxOnErrorReturn.java:172)\n at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:107)\n at reactor.core.publisher.Operators.error(Operators.java:198)\n at reactor.core.publisher.FluxError.subscribe(FluxError.java:44)\n at reactor.core.publisher.Flux.subscribe(Flux.java:8888)\n at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:104)\n at reactor.core.publisher.FluxFlatMap$FlatMapMain.checkTerminated(FluxFlatMap.java:847)\n at reactor.core.publisher.FluxFlatMap$FlatMapMain.drainLoop(FluxFlatMap.java:613)\n at reactor.core.publisher.FluxFlatMap$FlatMapMain.drain(FluxFlatMap.java:593)\n at reactor.core.publisher.FluxFlatMap$FlatMapMain.onError(FluxFlatMap.java:456)\n at reactor.core.publisher.SerializedSubscriber.onError(SerializedSubscriber.java:125)\n at reactor.core.publisher.FluxRetryWhen$RetryWhenMainSubscriber.whenError(FluxRetryWhen.java:230)\n at reactor.core.publisher.FluxRetryWhen$RetryWhenOtherSubscriber.onError(FluxRetryWhen.java:282)\n at reactor.core.publisher.FluxFlatMap$FlatMapMain.checkTerminated(FluxFlatMap.java:847)\n at reactor.core.publisher.FluxFlatMap$FlatMapMain.drainLoop(FluxFlatMap.java:613)\n at reactor.core.publisher.FluxFlatMap$FlatMapMain.drain(FluxFlatMap.java:593)\n at reactor.core.publisher.FluxFlatMap$FlatMapMain.onError(FluxFlatMap.java:456)\n at reactor.core.publisher.FluxFlatMap$FlatMapMain.onNext(FluxFlatMap.java:419)\n at reactor.core.publisher.SinkManyEmitterProcessor.drain(SinkManyEmitterProcessor.java:480)\n at reactor.core.publisher.SinkManyEmitterProcessor.tryEmitNext(SinkManyEmitterProcessor.java:278)\n at reactor.core.publisher.SinkManySerialized.tryEmitNext(SinkManySerialized.java:100)\n at reactor.core.publisher.InternalManySink.emitNext(InternalManySink.java:27)\n at reactor.core.publisher.FluxRetryWhen$RetryWhenMainSubscriber.onError(FluxRetryWhen.java:195)\n at reactor.core.publisher.FluxFlatMap$FlatMapMain.checkTerminated(FluxFlatMap.java:847)\n at reactor.core.publisher.FluxFlatMap$FlatMapMain.drainLoop(FluxFlatMap.java:613)\n at reactor.core.publisher.FluxFlatMap$FlatMapMain.drain(FluxFlatMap.java:593)\n at reactor.core.publisher.FluxFlatMap$FlatMapMain.onError(FluxFlatMap.java:456)\n at reactor.core.publisher.FluxFlatMap$FlatMapMain.onNext(FluxFlatMap.java:419)\n at reactor.core.publisher.MonoFlatMapMany$FlatMapManyInner.onNext(MonoFlatMapMany.java:251)\n at reactor.core.publisher.FluxCreate$BufferAsyncSink.drain(FluxCreate.java:887)\n at reactor.core.publisher.FluxCreate$BufferAsyncSink.next(FluxCreate.java:812)\n at reactor.core.publisher.FluxCreate$SerializedFluxSink.next(FluxCreate.java:164)\n at io.modelcontextprotocol.client.transport.ResponseSubscribers$AggregateSubscriber.hookOnComplete(ResponseSubscribers.java:263)\n at reactor.core.publisher.BaseSubscriber.onComplete(BaseSubscriber.java:200)\n at org.reactivestreams.FlowAdapters$FlowToReactiveSubscriber.onComplete(FlowAdapters.java:221)\n at java.net.http/jdk.internal.net.http.LineSubscriberAdapter$LineSubscription.loop(LineSubscriberAdapter.java:430)\n at java.net.http/jdk.internal.net.http.common.SequentialScheduler$LockingRestartableTask.run(SequentialScheduler.java:182)\n at java.net.http/jdk.internal.net.http.common.SequentialScheduler$CompleteRestartableTask.run(SequentialScheduler.java:149)\n at java.net.http/jdk.internal.net.http.common.SequentialScheduler$SchedulableTask.run(SequentialScheduler.java:207)\n at java.net.http/jdk.internal.net.http.common.SequentialScheduler.runOrSchedule(SequentialScheduler.java:280)\n at java.net.http/jdk.internal.net.http.common.SequentialScheduler.runOrSchedule(SequentialScheduler.java:233)\n at java.net.http/jdk.internal.net.http.LineSubscriberAdapter$LineSubscription.signalComplete(LineSubscriberAdapter.java:193)\n at java.net.http/jdk.internal.net.http.LineSubscriberAdapter.onComplete(LineSubscriberAdapter.java:114)\n at java.net.http/jdk.internal.net.http.common.HttpBodySubscriberWrapper.complete(HttpBodySubscriberWrapper.java:293)\n at java.net.http/jdk.internal.net.http.common.HttpBodySubscriberWrapper.onComplete(HttpBodySubscriberWrapper.java:401)\n at java.net.http/jdk.internal.net.http.ResponseContent$ChunkedBodyParser.accept(ResponseContent.java:220)\n at java.net.http/jdk.internal.net.http.ResponseContent$ChunkedBodyParser.accept(ResponseContent.java:131)\n at java.net.http/jdk.internal.net.http.Http1Response$BodyReader.handle(Http1Response.java:708)\n at java.net.http/jdk.internal.net.http.Http1Response$BodyReader.handle(Http1Response.java:636)\n at java.net.http/jdk.internal.net.http.Http1Response$Receiver.accept(Http1Response.java:528)\n at java.net.http/jdk.internal.net.http.Http1Response$BodyReader.tryAsyncReceive(Http1Response.java:666)\n at java.net.http/jdk.internal.net.http.Http1AsyncReceiver.flush(Http1AsyncReceiver.java:233)\n at java.net.http/jdk.internal.net.http.common.SequentialScheduler$LockingRestartableTask.run(SequentialScheduler.java:182)\n at java.net.http/jdk.internal.net.http.common.SequentialScheduler$CompleteRestartableTask.run(SequentialScheduler.java:149)\n at java.net.http/jdk.internal.net.http.common.SequentialScheduler$TryEndDeferredCompleter.complete(SequentialScheduler.java:324)\n at java.net.http/jdk.internal.net.http.common.SequentialScheduler$CompleteRestartableTask.run(SequentialScheduler.java:151)\n at java.net.http/jdk.internal.net.http.common.SequentialScheduler$SchedulableTask.run(SequentialScheduler.java:207)\n at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1090)\n at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:614)\n at java.base/java.lang.Thread.run(Thread.java:1474)\n Suppressed: java.lang.Exception: #block terminated with an error\n at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:104)\n at reactor.core.publisher.Mono.block(Mono.java:1773)\n at io.modelcontextprotocol.client.McpSyncClient.callTool(McpSyncClient.java:236)\n at org.labkey.professional.McpServerTest.callTool(McpServerTest.java:358)\n at org.labkey.professional.McpServerTest.callToolExpectingFailure(McpServerTest.java:342)\n at org.labkey.professional.McpServerTest.testBadTableParameters(McpServerTest.java:566)\n at org.labkey.professional.McpServerTest.getSourceForSavedQuery(McpServerTest.java:522)\n at org.labkey.professional.McpServerTest.invokeTools(McpServerTest.java:327)\n at org.labkey.professional.McpServerTest.testAdminAccess(McpServerTest.java:254)\n at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)\n at java.base/java.lang.reflect.Method.invoke(Method.java:565)\n at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)\n at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)\n```\n\n**Expected behavior**\nThe session should continue to process requests and respond to the client without fatal errors.\n\n**Minimal Complete Reproducible example**\nSee attached.\n\n[mcp-sdk-bug-repro.zip](https://github.com/user-attachments/files/27574476/mcp-sdk-bug-repro.zip)\n\n```bash\ncd mcp-sdk-bug-repro\nmvn -q test\n```\n\nThe test in `src/test/java/io/modelcontextprotocol/bug/SessionRemovalBugReproTest.java`:\n\n1. Builds a real `HttpServletStreamableServerTransportProvider` and a minimal `McpSyncServer` with a single tool.\n2. Issues an `initialize` POST and captures the server-assigned `mcp-session-id`.\n3. Issues a `tools/call` POST whose response writer is wired to a `Writer` that **accepts the writes** (so the SDK successfully serializes the SSE event into the response body) but **throws `IOException` on `flush()`** — exactly what an OutputStream backed by a closed socket does. This sets `PrintWriter.trouble = true` so `writer.checkError()` returns `true`.\n4. Asserts that:\n - The full SSE event payload was written to the response (data was delivered).\n - The session was removed from the SDK's `sessions` map (verified via reflection).\n5. Issues a second `tools/call` POST with the same session id and asserts that the SDK responds `404 Session not found` — proving the session is unrecoverable from the client's perspective even though the prior call's response was actually delivered.\n\nThe test deterministically reproduces what is otherwise a flaky race between a fast client closing its socket and the server's post-write `checkError()`.\n\n**Workaround**\nWrap the response in an `HttpServletResponseWrapper` that returns a `PrintWriter` whose `checkError()` always returns `false`. This suppresses the false positive at the cost of closing the (already broken) post-write disconnect detection. Apply only on the POST path — keep `checkError` honest for the long-lived GET listening stream.\n\n```\n private static class _LoggingResponseWrapper extends HttpServletResponseWrapper\n {\n private final String requestUri;\n private _LoggingPrintWriter loggingWriter;\n\n _LoggingResponseWrapper(HttpServletResponse response, String requestUri)\n {\n super(response);\n this.requestUri = requestUri;\n }\n\n @Override\n public PrintWriter getWriter() throws IOException\n {\n if (loggingWriter == null)\n loggingWriter = new _LoggingPrintWriter(super.getWriter(), requestUri);\n return loggingWriter;\n }\n }\n\n private static class _LoggingPrintWriter extends PrintWriter\n {\n private final String requestUri;\n\n _LoggingPrintWriter(PrintWriter delegate, String requestUri)\n {\n super(delegate);\n this.requestUri = requestUri;\n }\n\n @Override\n public boolean checkError()\n {\n // Workaround for MCP SDK 1.1.2 bug in HttpServletStreamableServerTransportProvider.sendEvent\n // (https://github.com/modelcontextprotocol/java-sdk). After writing/flushing an SSE event,\n // sendEvent calls writer.checkError() and throws \"Client disconnected\" if it returns true.\n // The catch block in sendMessage then removes the MCP session from the sessions map - even\n // though the SSE event data was already delivered to the client. For streamable HTTP, each\n // POST is a single-event exchange, so a client closing its socket after receiving the\n // response is normal HTTP/1.1 behavior, not an MCP session termination. The race between\n // the client's socket close and the server's checkError() call is exactly what makes this\n // test flaky on TeamCity. Returning false suppresses the false positive; if the client\n // truly lost data, it will retry on a fresh connection.\n boolean actual = super.checkError();\n if (actual)\n {\n LOG.info(\"MCP checkError suppressed (returning false): uri={}\", requestUri);\n }\n return false;\n }\n }\n```","author":{"url":"https://github.com/labkey-jeckels","@type":"Person","name":"labkey-jeckels"},"datePublished":"2026-05-10T21:43:59.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":2},"url":"https://github.com/952/java-sdk/issues/952"}
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:f1eb6797-61e9-6a61-53ee-4d3e78dfd9df |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | BAEA:1AF5CD:CD4C81:1131B4D:6A5B5ADC |
| html-safe-nonce | d2f4a2e07364069e64aaf562f02dce30772182bf2dfa17e71b813c70b2617bdc |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCQUVBOjFBRjVDRDpDRDRDODE6MTEzMUI0RDo2QTVCNUFEQyIsInZpc2l0b3JfaWQiOiIyODc1Njc0NDExNDQwMTE0ODQiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 860ac49042c7cf9c8800cde44ed31dcf75bd09cb598a8a36f6a7b9b5a9625019 |
| hovercard-subject-tag | issue:4416926487 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/modelcontextprotocol/java-sdk/952/issue_layout |
| twitter:image | https://opengraph.githubassets.com/402cbc51103e7873ae8fc2164b8a54ebf550805ec0300134305b30338c6917d2/modelcontextprotocol/java-sdk/issues/952 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/402cbc51103e7873ae8fc2164b8a54ebf550805ec0300134305b30338c6917d2/modelcontextprotocol/java-sdk/issues/952 |
| og:image:alt | Bug description We use the MCP Java SDK as via our dependency on Spring AI. Our CI/CD test coverage for our MCP implementation fails regularly with a race condition when dealing with intentional er... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | labkey-jeckels |
| hostname | github.com |
| expected-hostname | github.com |
| None | 5290d7e14309ad1e76106a9c4237bd1041517e83ea182c8ab756752cb0c6940b |
| turbo-cache-control | no-preview |
| go-import | github.com/modelcontextprotocol/java-sdk git https://github.com/modelcontextprotocol/java-sdk.git |
| octolytics-dimension-user_id | 182288589 |
| octolytics-dimension-user_login | modelcontextprotocol |
| octolytics-dimension-repository_id | 919609219 |
| octolytics-dimension-repository_nwo | modelcontextprotocol/java-sdk |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 919609219 |
| octolytics-dimension-repository_network_root_nwo | modelcontextprotocol/java-sdk |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 9c975978430e9ad293956f2bbdaf153b1bd84a99 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
Viewport: width=device-width