[2.1.0-RC2]-WebClientStreamableHttpTransport: a 2xx application/json response that is not JSON-RPC leaves the request pending until the timeout
Bug description
Our application lets end users connect their own remote MCP servers over Streamable HTTP. They enter the server URL and credentials (API key in the query string or headers), and a "Test connection" button runs initialize + tools/list with WebClientStreamableHttpTransport, so they get immediate feedback on whether the configuration works.
With a wrong API key, the test does not fail. It hangs until the client's initialization timeout and then reports only a TimeoutException, so users can't tell a bad key from an unreachable server. A correct key returns in under a second.
This happens because some hosted MCP services reject requests at an API gateway in front of the MCP endpoint, and the gateway does not answer in JSON-RPC. For example, AMap's https://mcp.amap.com/mcp?key=<wrong key> answers in about a second with:
HTTP/1.1 200 OK
Content-Type: application/json
{"status":"0","info":"INVALID_USER_KEY","infocode":"10001"}
WebClientStreamableHttpTransport drops this response instead of failing the pending request. In sendMessage, the application/json branch calls sink.success() before directResponseFlux parses the body. McpSchema.deserializeJsonRpcMessage then throws IllegalArgumentException("Cannot deserialize JSONRPCMessage: ..."), which reaches onErrorComplete. There, sink.error(t) is a no-op because the sink has already succeeded, so the pending initialize response is never completed and the caller waits for the timeout.
The problem does not occur with the MCP Java SDK's own client transport. Against the same server, the same McpSyncClient with HttpClientStreamableHttpTransport (MCP Java SDK 2.2.0-M2) fails in a few milliseconds with Cannot deserialize JSONRPCMessage: {"status":"0",...}, because it resolves sendMessage() from the first signal of the response. A 401 with the same body also fails immediately with either transport. Since the core client and protocol handling are the same in both cases, the issue appears to be specific to Spring AI's WebClientStreamableHttpTransport in mcp-spring-webflux. It looks like a concrete, real-world case of #5775 (same root cause).
Environment
| Component | Version |
|---|---|
| Spring AI | org.springframework.ai:mcp-spring-webflux:2.1.0-RC2; the transport source is identical on main at 9993102 (2026-11-06) |
| MCP Java SDK | mcp-core / mcp-json-jackson3 2.2.0-M2 |
| Spring Boot | 4.1.0 (Spring Framework 7.0.8, Reactor Netty 1.3.6) |
| JDK | 25.0.1 (the repro compiles with --release 17) |
| OS | Windows 11 |
Minimal reproduction
A Maven project with an MCP server (official SDK server on Spring AI's WebFluxStreamableServerTransportProvider)
behind a tiny API-key gateway, and an MCP client using WebClientStreamableHttpTransport. The gateway mimics the
hosted service: ?key=good-key reaches the MCP server, ?key=wrong-key-401 gets the gateway body with 401,
any other key gets it with 200.
pom.xml
src/main/java/repro/ReproServer.java
src/main/java/repro/ReproClient.java
src/main/resources/simplelogger.properties
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.1.0</version>
<relativePath/>
</parent>
<groupId>repro</groupId>
<artifactId>mcp-streamable-http-non-jsonrpc-200</artifactId>
<version>0.0.1</version>
<properties>
<java.version>17</java.version>
<spring-ai.version>2.1.0-RC2</spring-ai.version>
<mcp-sdk.version>2.2.0-M2</mcp-sdk.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>${spring-ai.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Client WebClientStreamableHttpTransport and server WebFluxStreamableServerTransportProvider -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>mcp-spring-webflux</artifactId>
</dependency>
<dependency>
<groupId>io.modelcontextprotocol.sdk</groupId>
<artifactId>mcp-json-jackson3</artifactId>
<version>${mcp-sdk.version}</version>
</dependency>
<dependency>
<groupId>io.projectreactor.netty</groupId>
<artifactId>reactor-netty-http</artifactId>
</dependency>
<!-- Required by the WebFlux server handler adapter (optional dependency of spring-web) -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.5.0</version>
<configuration>
<!-- Do not wait 15s for Reactor Netty's daemon threads when main returns -->
<cleanupDaemonThreads>false</cleanupDaemonThreads>
</configuration>
</plugin>
</plugins>
</build>
</project>
src/main/java/repro/ReproServer.java
package repro;
import java.net.URI;
import java.util.Map;
import io.modelcontextprotocol.server.McpServer;
import io.modelcontextprotocol.spec.McpSchema;
import io.netty.handler.codec.http.HttpResponseStatus;
import reactor.core.publisher.Mono;
import reactor.netty.http.server.HttpServer;
import reactor.netty.http.server.HttpServerResponse;
import org.springframework.ai.mcp.server.webflux.transport.WebFluxStreamableServerTransportProvider;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunctions;
/**
* An official MCP SDK server on the Spring AI WebFlux Streamable HTTP transport, behind an API-key gateway.
* <p>
* Like a real hosted MCP service (https://mcp.amap.com/mcp?key=...), the gateway answers a wrong key with
* HTTP 200 and a JSON body that is not JSON-RPC:
* <ul>
* <li>{@code ?key=good-key} reaches the MCP server;</li>
* <li>{@code ?key=wrong-key-401} gets the gateway body with 401, for contrast;</li>
* <li>any other key gets the gateway body with 200, as the real service does.</li>
* </ul>
*/
public class ReproServer {
static final String GATEWAY_ERROR = "{\"status\":\"0\",\"info\":\"INVALID_USER_KEY\",\"infocode\":\"10001\"}";
public static void main(String[] args) {
int port = args.length > 0 ? Integer.parseInt(args[0]) : 8080;
var transport = WebFluxStreamableServerTransportProvider.builder().messageEndpoint("/mcp").build();
McpServer.sync(transport)
.serverInfo("repro-server", "1.0.0")
.capabilities(McpSchema.ServerCapabilities.builder().tools(true).build())
.toolCall(McpSchema.Tool.builder("echo", Map.of("type", "object")).description("Echoes text").build(),
(exchange, request) -> McpSchema.CallToolResult.builder()
.addTextContent(String.valueOf(request.arguments().get("text")))
.build())
.build();
var mcp = new ReactorHttpHandlerAdapter(RouterFunctions.toHttpHandler(transport.getRouterFunction()));
var server = HttpServer.create().host("127.0.0.1").port(port).handle((request, response) -> {
System.out.println(request.method() + " " + request.uri());
String query = String.valueOf(URI.create(request.uri()).getQuery());
return switch (query) {
case "key=good-key" -> mcp.apply(request, response);
case "key=wrong-key-401" -> gatewayError(response, HttpResponseStatus.UNAUTHORIZED);
default -> gatewayError(response, HttpResponseStatus.OK);
};
}).bindNow();
System.out.println("MCP server listening on http://127.0.0.1:" + server.port() + "/mcp");
server.onDispose().block();
}
private static Mono<Void> gatewayError(HttpServerResponse response, HttpResponseStatus status) {
return response.status(status)
.header("Content-Type", "application/json")
.sendString(Mono.just(GATEWAY_ERROR))
.then();
}
}
src/main/java/repro/ReproClient.java
package repro;
import java.time.Duration;
import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.spec.McpSchema;
import org.springframework.ai.mcp.client.webflux.transport.WebClientStreamableHttpTransport;
import org.springframework.web.reactive.function.client.WebClient;
/**
* Initializes an official MCP client with each key against {@link ReproServer} and reports how long it takes.
*/
public class ReproClient {
public static void main(String[] args) {
String endpoint = args.length > 0 ? args[0] : "http://127.0.0.1:8080/mcp";
for (String key : new String[] { "good-key", "wrong-key-401", "wrong-key" }) {
initialize(endpoint + "?key=" + key);
}
}
private static void initialize(String url) {
var transport = WebClientStreamableHttpTransport.builder(WebClient.builder()).endpoint(url).build();
var client = McpClient.sync(transport)
.requestTimeout(Duration.ofSeconds(10))
.initializationTimeout(Duration.ofSeconds(10))
.build();
long started = System.nanoTime();
try {
client.initialize();
long elapsed = millisSince(started);
var tools = client.listTools().tools().stream().map(McpSchema.Tool::name).toList();
System.out.printf("%s -> initialized in %d ms, tools=%s%n", url, elapsed, tools);
}
catch (RuntimeException e) {
System.out.printf("%s -> failed after %d ms: %s%n cause: %s%n", url, millisSince(started), e,
e.getCause());
}
finally {
client.close();
}
}
private static long millisSince(long started) {
return (System.nanoTime() - started) / 1_000_000;
}
}
src/main/resources/simplelogger.properties
org.slf4j.simpleLogger.defaultLogLevel=warn
Run the server and the client in two terminals:
mvn -q compile exec:java -Dexec.mainClass=repro.ReproServer
mvn -q exec:java -Dexec.mainClass=repro.ReproClient
Actual behavior
Client output. The good-key time includes one-off class loading for the first client in the JVM and varied from
about 0.8 s to 9 s across runs under exec:java; wrong-key always ended at the configured 10 s timeout, and the
operator named in the TimeoutException varies between runs.
http://127.0.0.1:8080/mcp?key=good-key -> initialized in 852 ms, tools=[echo]
http://127.0.0.1:8080/mcp?key=wrong-key-401 -> failed after 28 ms: java.lang.RuntimeException: Client failed to initialize by explicit API call
cause: io.modelcontextprotocol.spec.McpTransportException: Sending request failed, 401 Unauthorized from POST http://127.0.0.1:8080/mcp
http://127.0.0.1:8080/mcp?key=wrong-key -> failed after 10001 ms: java.lang.RuntimeException: Client failed to initialize by explicit API call
cause: java.util.concurrent.TimeoutException: Did not observe any item or terminal signal within 10000ms in 'map' (and no fallback has been configured)
Server log for the same run. For wrong-key the client receives the gateway reply to initialize, opens a GET
stream as if a session had been established, and then sends nothing until the timeout:
POST /mcp?key=good-key
POST /mcp?key=good-key
GET /mcp?key=good-key
POST /mcp?key=good-key
DELETE /mcp?key=good-key
POST /mcp?key=wrong-key-401
GET /mcp?key=wrong-key-401
POST /mcp?key=wrong-key
GET /mcp?key=wrong-key
With the default INFO level, nothing is logged about the parse failure; the only related line is
Opening an SSE stream failed. This can be safely ignored. from that GET.
Expected behavior
initialize() fails right away, as in the 401 case, and the cause names the response, for example
Cannot deserialize JSONRPCMessage: {"status":"0","info":"INVALID_USER_KEY","infocode":"10001"}.
That is what the SDK's HttpClientStreamableHttpTransport does. Replacing the transport line in ReproClient with
var transport = HttpClientStreamableHttpTransport.builder("http://127.0.0.1:8080").endpoint("/mcp?key=" + key).build();
(io.modelcontextprotocol.client.transport.HttpClientStreamableHttpTransport) prints:
good-key -> initialized in 300 ms
wrong-key-401 -> failed after 10 ms: java.lang.RuntimeException: Client failed to initialize by explicit API call | cause: io.modelcontextprotocol.client.transport.McpHttpClientTransportAuthorizationException: Authorization error when sending message
wrong-key -> failed after 6 ms: java.lang.RuntimeException: Client failed to initialize by explicit API call | cause: java.lang.IllegalArgumentException: Cannot deserialize JSONRPCMessage: {"status":"0","info":"INVALID_USER_KEY","infocode":"10001"}
Analysis
In WebClientStreamableHttpTransport.sendMessage (v2.1.0-RC2):
markInitialized(...)runs for every response before the status is checked (L356-L360), so the gateway reply counts as an initialized session and a GET stream is opened (theGETlines in the server log).- For a 2xx
application/jsonresponse,sink.success()is called before the body is parsed (L393-L399). directResponseFluxcallsMcpSchema.deserializeJsonRpcMessage, which throwsIllegalArgumentExceptionfor a JSON object that is not JSON-RPC (onlyIOExceptionis caught at L530).- The error reaches
onErrorComplete(L416-L429):handleException(t)ends inLifecycleInitializer.handleException, which only acts onMcpTransportSessionNotFoundException, andsink.error(t)is a no-op because the sink already succeeded. The error is dropped, the pendinginitializeresponse inMcpClientSessionis never completed, and the caller waits for the timeout.
A malformed body, or one over the codec's maxInMemorySize (DataBufferLimitException), takes the same path (#5775).
A non-2xx status or an unknown media type errors before sink.success() and fails fast.
The SDK transport avoids this by resolving sendMessage() from the first signal of the response flux
(switchOnFirst, HttpClientStreamableHttpTransport L587-L598),
so a parse error before any message fails the send and therefore the request.
Possible fix
Resolve the delivery sink from the first signal of the response flux, as the SDK transport does, or complete the
pending request with an error when a direct JSON response cannot be parsed. Open PR #5774 takes the second approach
(a synthetic JSON-RPC error response for the request id), but it predates the current requestHandler code.
#5825 ("Fix #5775") was closed without merging.
Workaround
Use a shorter initializationTimeout/requestTimeout, or switch to the SDK's HttpClientStreamableHttpTransport.
Related: #5775, #5774, #5825.
Hi team,
I'd love to take a crack at fixing this! I can see that WebClientStreamableHttpTransport drops the IllegalArgumentException because sink.success() is called too early in the reactive chain.
@git-syl — thank you for the incredible bug report and the runnable reproduction code! I'll use your project to spin up a local test and work on resolving the delivery sink from the first signal (similar to how the SDK transport handles it).
Could you assign this to me?
Hi Spring AI team!
I'd like to contribute to this MCP transport issue.
The behaviour where a successful HTTP response containing an invalid JSON-RPC payload leaves the initialization request pending is particularly interesting.
I'd like to investigate the reactive response handling, error propagation and request completion lifecycle.
I can work on a focused regression test covering non-JSON-RPC responses, parsing failures and proper request termination.
Would this be available for community contribution? I'd appreciate your thoughts on the preferred fix.
Thanks!