Skip to content

Streamable HTTP: error replies from synchronous handlers are sometimes lost (the worker writing the reply is interrupted mid-flush) #1336

Open

Description

@gsperry

Related: reactor-core issue reactor/reactor-core#4483 (root cause).
Component: synchronous server features, run as Mono.fromCallable(...).subscribeOn(Schedulers.boundedElastic()) (McpServerFeatures, prompt and tool fromSync), with the reply written inline on that worker (McpStreamableServerSession handle → onErrorResume(...) → flatMap(connection::sendMessage)), served by the Spring WebMVC Streamable-HTTP transport WebMvcStreamableServerTransportProvider, which subscribes with block() on the servlet container thread. That transport ships in org.springframework.ai:mcp-spring-webmvc (tested 2.0.2 and 2.1.0-RC2); up to 0.18.5 it shipped as io.modelcontextprotocol.sdk:mcp-spring-webmvc.
Versions seen: mcp-core 2.1.0 with Spring AI 2.0.2 on Spring Boot 4.1.2; Spring AI 2.1.0-RC2 on Spring Boot 4.2.0-RC2; SDK 0.18.5 on Spring Boot 4.0.6, 4.0.9 and 4.1.2; reactor-core 3.8.5 and 3.8.8 (and, by the Spring Boot 4.2.0-RC2 BOM, 3.9.0-RC1 [I]); mcp-core 2.2.0-M2 in the Spring AI 2.1.0-RC2 row; JDK 25. The relevant mcp-core code is the same in 0.18.5, 2.1.0 and 2.2.0.
Labels: [V] verified by a run or by reading the sources; [I] inferred.

Summary

When a synchronous prompt (or tool) handler throws, the server answers with a JSON-RPC error. Under concurrency, a fraction of those error replies never reach the client: the connection closes with zero bytes, or after the response headers and before the terminating chunk. For each zero-byte loss the server logs, from the transport's sendMessage:

Failed to send message to session <id>: ServletResponse failed to flushBuffer: java.io.IOException: The current thread was interrupted

on a boundedElastic thread [V]. Replies from handlers that return normally were not lost [V].

Cause [V, traced]

The thread writing the reply is interrupted by a race in reactor-core's subscribeOn for callables (reactor-core issue linked above, with a Reactor-only reproduction):

  1. The handler throws on the boundedElastic worker. Reactor's CallableSubscribeOnSubscription.run cancels its own subscription (Operators.onOperatorError) and then signals onError downstream on the same worker. The SDK's onErrorResume builds the error reply, and sendMessage writes and flushes it, still on that worker.
  2. Meanwhile the servlet container thread, inside block() in WebMvcStreamableServerTransportProvider.handlePost, finishes MonoSubscribeOnCallable.subscribe. setMainFuture finds the subscription cancelled and disposes the task with Future.cancel(true) (SchedulerTask.dispose), which interrupts the worker.
  3. If the interrupt lands during the flush, the flush throws, sendMessage logs the error above and calls sseBuilder.error(e), and the client gets a closed connection.

An opt-in trace in the attached project records both stacks. The interrupting one, on the container thread [V]:

SchedulerTask.dispose(SchedulerTask.java:130)
FluxSubscribeOnCallable$CallableSubscribeOnSubscription.setMainFuture(FluxSubscribeOnCallable.java:201)
MonoSubscribeOnCallable.subscribe(MonoSubscribeOnCallable.java:53)
... MonoUsingWhen.subscribe ...
Mono.block(Mono.java:1772)
WebMvcStreamableServerTransportProvider.lambda$handlePost$18(WebMvcStreamableServerTransportProvider.java:454)   (0.18.5; Spring AI 2.0.2: lambda$handlePost$19(...java:507))
SseServerResponse.writeToInternal(...)

The losses that end after the headers have no matching server log line; [I] they are probably the same interrupt hitting a later write or the final flush in close(), where the exception is not logged.

Reproduction (attached: lost-reply, a standalone Gradle project with one JUnit test)

A Spring Boot application hosts the transport at /mcp, with one prompt that has a required argument. 16 sessions (one per thread) send prompts/get with the argument missing, so the handler throws and the server answers with an in-process JSON-RPC error. HTTP/1.1, Accept: application/json, text/event-stream, the Mcp-Session-Id header, a unique request id; no retry; a reply that does not arrive complete counts as lost. Two client modes: a new JDK HttpClient per request, and a new plain Socket per request (Connection: close, read to end of stream). -Pvariant=old|current and -PbootVersion=... select the dependencies; -Dlostreply.outcome=result supplies the argument (control); -Dlostreply.traceInterrupts=true records the stacks.

Results [V] (10,000 requests per run, 16 threads, JDK 25; the rate varies with machine and load, so treat it as an order of magnitude):

Transport Spring Boot (Spring Framework, Tomcat) Client Lost / attempts Server "interrupted" lines
0.18.5 4.0.6 (7.0.7, 11.0.21) HttpClient 1443 / 30,000 (4.8%) 1410, equal to the zero-byte losses
0.18.5 4.0.6 socket 434 / 20,000 (2.2%) 406, equal to the zero-byte losses
0.18.5 4.0.9 (7.0.10, 11.0.27) HttpClient 22 / 30,000 (0.07%) 22
0.18.5 4.0.9 socket 15 / 20,000 (0.08%) 13
Spring AI 2.0.2 4.1.2 (7.0.10, 11.0.27) HttpClient 21 / 30,000 (0.07%) 18
Spring AI 2.0.2 4.1.2 socket 14 / 20,000 (0.07%) 13
Spring AI 2.1.0-RC2 4.2.0-RC2 (7.1.0-RC2, 11.0.27) HttpClient / socket 11 and 5 / 10,000 (one run each) 11 and 5
control (handler returns): 0.18.5 / Spring AI 2.0.2 4.0.6 / 4.1.2 HttpClient 0 / 10,000 each 0

Most rows were run before the project gained its ok/unexpected counters and the renamed failure kind; the loss logic is unchanged, and no run recorded an unexpected status. In every run the server "interrupted" line count equals the client's zero-byte losses; the rest of the losses ended after the headers. Newer Spring Framework makes the window much smaller (about 66 times fewer losses with HttpClient and about 29 times with the socket from Spring Boot 4.0.6 to 4.0.9), but does not close it. Why Spring Framework 7.0.10 helps is not known [I: it probably changes how long the worker's flush takes relative to the container thread's setMainFuture].

Possible mitigations in the SDK [I, none tested]

  • Catch the handler's exception inside the callable passed to Mono.fromCallable and turn it into the error result there, so the callable does not throw and Reactor does not cancel the subscription (step 1 above never happens).
  • Or do not write the reply on the subscribeOn worker (for example publishOn another scheduler before sendMessage).
  • For users: immediateExecution(true) on the synchronous server runs handlers without subscribeOn, which should avoid the race, at the cost of running handlers on the calling thread.

Ask

  • Would the maintainers take one of the mitigations above while the Reactor issue is open?
  • Would they accept a regression test along the lines of the attached project (a loopback server, 16 threads, a throwing handler, no retry, assert zero lost replies; -Dlostreply.assertNone=true)? A client that retries hides the problem, so the test must count losses with no retry.

lost-reply.zip

Activity

  1. Shanmukh-l33t commented on Nov 14, 2026

    @Shanmukh-l33t

    I reproduced this in mcp-core and confirmed the mechanism you traced, then found a change in this repo that removes the trigger. Branch, RED→GREEN numbers and the limits of what I verified are below.

    Confirmation of the cause

    Checked against main at 79c74be with reactor-core 3.9.0-RC1 (what this repo's reactor-bom 2026.0.0-RC1 resolves to), so all three versions you listed are covered:

    • McpServerFeatures.AsyncPromptSpecification.fromSync (and the tool, resource, resourceTemplate and completion variants) runs the sync handler as Mono.fromCallable(...) with subscribeOn(Schedulers.boundedElastic()).
    • McpStreamableServerSessionStream.handle (McpStreamableServerSession.java:513) maps the result, onErrorResume builds the JSON-RPC error, and .flatMap(this.connection::sendMessage) (:551) writes it — all on that worker.
    • The transport subscribes with block() on the container thread (HttpServletStreamableServerTransportProvider.java:653 here; handlePost in the Spring WebMVC transport, as you traced).

    The reactor side, in 3.9.0-RC1 bytecode/sources:

    1. CallableSubscribeOnSubscription.run (FluxSubscribeOnCallable) calls actual.onError(Operators.onOperatorError(this, ex, ctx)).
    2. Operators.onOperatorError(Subscription, Throwable, Object, Context) does Exceptions.throwIfFatal then subscription.cancel() before returning the error (bytecode: invokeinterface Subscription.cancel at offset 9). That is the self-cancel: state = HAS_CANCELLED, and mainFuture is swapped for DISPOSED (FluxSubscribeOnCallable.java:144-149).
    3. onError then runs the downstream on that same worker — onErrorResume → error reply → sendMessage → flush.
    4. Back on the subscribing thread, MonoSubscribeOnCallable.subscribe:53 reaches parent.setMainFuture(...), finds DISPOSED, and calls c.dispose() on the task it just scheduled (FluxSubscribeOnCallable.java:197-201).
    5. SchedulerTask.dispose runs f.cancel(thread != Thread.currentThread()) — the caller is not the worker, so cancel(true) interrupts the worker still inside step 3 (SchedulerTask.java:130, same line as your trace).

    So: the interrupt is Reactor's (reactor/reactor-core#4483), and nothing in this repo interrupts anything. But the throw that arms it is the SDK's own — the handler's failure crossing the subscribeOn boundary. If the failure is turned into an error signal one step later, inside the deferred subscription, run takes its non-throwing path, nothing cancels, and setMainFuture stores the task instead of disposing it.

    Change

    Branch fix/1336-streamable-http-error-reply-loss on my fork, two commits from 79c74be:

    main...Shanmukh-l33t:java-sdk:fix/1336-streamable-http-error-reply-loss

    McpServerFeatures gains one private helper, used by the five fromSync adapters (prompt, tool, resource, resource template, completion):

    private static <T> Mono<T> fromSyncHandler(Callable<T> handler, boolean immediateExecution) {
        Mono<T> result = Mono.defer(() -> {
            try {
                return Mono.justOrEmpty(handler.call());
            }
            catch (Throwable ex) {
                Exceptions.throwIfFatal(ex);
                return Mono.error(ex);
            }
        });
        return immediateExecution ? result : result.subscribeOn(Schedulers.boundedElastic());
    }

    Nothing else changes: the handler still runs on a boundedElastic worker, the error still arrives at onErrorResume as the same throwable (so the client gets the same JSON-RPC error), null results still complete empty, immediateExecution(true) still runs inline, and fatal throwables still propagate as before via Exceptions.throwIfFatal.

    RED → GREEN

    Test: mcp-test/src/test/java/io/modelcontextprotocol/server/StreamableHttpSyncHandlerErrorReplyTests.java. One streamable session, 16 threads × 100 prompts/get against a sync prompt handler that throws, a fresh transport per request whose write is interruptible (the flush aborts when the writing thread is interrupted, like a servlet or NIO flush). Counters: replies that reached the transport, writes that started with the interrupt flag already set, writes interrupted mid-flush, failed subscriptions.

    • RED, same test file against pristine 79c74be (git checkout upstream/main -- .../McpServerFeatures.java, rebuilt): Outcome[requests=1600, replies=1367, writeAttempts=1600, interruptedAtEntry=89, interruptedDuringFlush=144, failedSubscriptions=233] → 233/1600 (14.6%) error replies lost, every loss accounted for by an interrupt (89 arrived before the write, 144 landed inside the flush). Two earlier runs of the harness: 197/1600 and 230/1600.
    • Control, same harness with a handler that returns a result: 1600/1600, no interrupts.
    • GREEN, branch: Outcome[requests=1600, replies=1600, writeAttempts=1600, interruptedAtEntry=0, interruptedDuringFlush=0, failedSubscriptions=0] — 4 runs (2 of them with this final version of the test file), all 1600/1600 with zero interrupted writes. Handler threads observed [boundedElastic-1 … boundedElastic-19], asserted, so the fix cannot buy the replies by moving blocking handlers onto the container thread.
    • ./mvnw -pl mcp-core,mcp-test spring-javaformat:validate passes. Existing suites re-run on the branch: mcp-test StdioMcpSyncServerTests 34/34, HttpServletStreamableSyncServerTests 34/34, StdioMcpAsyncServerTests 34/34; mcp-core server/spec tests 110/110.

    Reproduce: ./mvnw -o -pl mcp-core -DskipTests install && ./mvnw -o -pl mcp-test -Dtest=StreamableHttpSyncHandlerErrorReplyTests test (drop -o if your Maven repo isn't populated).

    Limits

    • This is a mitigation, not a fix for #4483: Reactor still disposes a cancelled subscription with an interrupt. It removes the SDK's self-cancel for sync handlers; any other Mono.fromCallable(...).subscribeOn(...) whose downstream does interruptible work on the worker is still exposed.
    • io.modelcontextprotocol.modern.server.feature.SyncAdapters.call has the identical shape (Mono.fromCallable + subscribeOn(boundedElastic)). I did not change it: I have not verified whether a reply is written inline on that worker in the modern path, so I did not want to touch it unverified. It is the obvious follow-up if you want the whole SDK closed.
    • The test widens the flush window (a 2 ms interruptible sleep instead of a real flush) so the race is observable in a unit test; that is why the loss rate here is 12-15% instead of the 0.07-4.8% you measured over loopback HTTP. It is not a substitute for your end-to-end reproduction, and I did not run it against the Spring WebMVC transport.
    • Losing a reply because the client really went away is unchanged and out of scope.

    For the maintainers

    Would you take this shape — the handler's failure becoming an error signal from inside the deferred subscription, with no scheduler change? If you would rather keep fromCallable untouched and wait for Reactor, then the honest answer to the issue's question is that immediateExecution(true) avoids the race today, at the cost of running sync handlers on the transport's thread — with a blocking block() transport, the offload is not buying concurrency anyway.

    Disclosure: I used an AI agent (Hermes Agent, Nous Research) to read the sources, write the harness and the patch, and run the builds. Every command and output quoted above comes from this machine (JDK 21, reactor-core 3.9.0-RC1), and I have reviewed the change and stand behind it. Per CONTRIBUTING I have not opened a PR as an unassigned external contributor; the branch is there if you want it as one.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions