Skip to content

Commit 1cf7903

Browse files
authored
Refactor HttpClient-based transports to use Publisher instead of Subscriber (#1079)
HttpClient-based transports used to capture the enclosing sseSink in the subscriber, leading to HttpClient leaks when the client was closed. This PR addresses this, and adds many other improvements to HttpClient-based transports. This has no public API change. Improved transport reliability: - Closed transports no longer keep their `HttpClient` alive, so selector threads and memory stop piling up - `closeGracefully()` now releases open connections even when the session DELETE fails, e.g. when the server is down - `connect()` on the legacy SSE transport no longer hangs when it gets the stream ends (error, stream closed,`closeGracefully()`, ...) before the first event or - `sendMessage()` on Streamable HTTP no longer hangs when the SSE stream is closed without response or before the response arrives - Responses the client never reads are always released (e.g. `DELETE`), so connections go back to the pool. Errors surface immediately instead of as timeouts: - On Streamable HTTP, a JSON response that can't be read (malformed, or over maxResponseSize) now fails the request immediately with the real cause, instead of a TimeoutException after requestTimeout` - A server that answers a request with an empty JSON body now makes that request fail instead of silently timing out. An empty body in reply to a notification is still tolerated. - Server-caused errors are now McpTransportException instead of a plain RuntimeException, and the message includes the response body the server sent. - Errors that happen after connect() or sendMessage() has already completed now reach the transport's exception handler instead of Reactor "onErrorDropped" logs. - A 404 or 400 invalidates the session only if the request that got it carried a session id. Fixes a race condition where are reconnect got a new session while another request was already in flight (with the old session). The old request could have ended up invalidating the new session. Performance - Large SSE responses, such as multi-MB tool results, are no longer slow to receive. SSE parsing spec compliance - Unknown fields such as retry: are ignored instead of failing the stream with "Invalid SSE response". - The event type resets after each event, so a message that follows a named event is no longer misclassified and dropped. - A data: line containing U+2028, U+2029 or U+0085 is no longer truncated. - The legacy SSE transport skips empty "primer" events and unknown event types instead of failing. - An empty id: clears the last event id. Fixes #547 Fixes #620 Fixes #1042 Fixes #1047 Fixes #1147 Signed-off-by: Daniel Garnier-Moiroux <git@garnier.wf> Signed-off-by: Dariusz Jędrzejczyk <dariusz.jedrzejczyk@broadcom.com>
1 parent c7fef64 commit 1cf7903

22 files changed

Lines changed: 2809 additions & 1456 deletions

‎mcp-core/src/main/java/io/modelcontextprotocol/client/transport/HttpClientSseClientTransport.java‎

Lines changed: 89 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,11 @@
1111
import java.net.http.HttpResponse;
1212
import java.time.Duration;
1313
import java.util.List;
14-
import java.util.concurrent.CompletableFuture;
14+
import java.util.Optional;
1515
import java.util.concurrent.atomic.AtomicReference;
1616
import java.util.function.Consumer;
1717
import java.util.function.Function;
1818

19-
import io.modelcontextprotocol.client.transport.ResponseSubscribers.ResponseEvent;
2019
import io.modelcontextprotocol.client.transport.customizer.McpAsyncHttpClientRequestCustomizer;
2120
import io.modelcontextprotocol.client.transport.customizer.McpSyncHttpClientRequestCustomizer;
2221
import io.modelcontextprotocol.common.McpTransportContext;
@@ -390,70 +389,93 @@ public Mono<Void> connect(Function<Mono<JSONRPCMessage>, Mono<JSONRPCMessage>> h
390389
var transportContext = ctx.getOrDefault(McpTransportContext.KEY, McpTransportContext.EMPTY);
391390
return Mono.from(this.httpRequestCustomizer.customize(builder, "GET", uri, null, transportContext));
392391
}).flatMap(requestBuilder -> Mono.create(sink -> {
393-
Disposable connection = Flux.<ResponseEvent>create(
394-
sseSink -> this.httpClient
395-
.sendAsync(requestBuilder.build(),
396-
responseInfo -> ResponseSubscribers.sseToBodySubscriber(responseInfo, sseSink,
397-
this.maxResponseSize))
398-
.exceptionallyCompose(e -> {
399-
sseSink.error(e);
400-
return CompletableFuture.failedFuture(e);
401-
}))
402-
.map(responseEvent -> (ResponseSubscribers.SseResponseEvent) responseEvent)
403-
.flatMap(responseEvent -> {
392+
Disposable connection = ResponseBodyHandlers.sendAsync(this.httpClient, requestBuilder.build())
393+
.flatMapMany(response -> {
404394
if (isClosing) {
405-
return Mono.empty();
395+
// The body is handed over as a publisher and the connection is
396+
// only released once it is subscribed to. It is an SSE stream
397+
// that may never end, so it is cancelled rather than drained.
398+
return ResponseBodyHandlers.cancel(response.body());
406399
}
407400

408-
int statusCode = responseEvent.responseInfo().statusCode();
401+
int statusCode = response.statusCode();
409402

410403
if (statusCode >= 200 && statusCode < 300) {
411-
try {
412-
if (ENDPOINT_EVENT_TYPE.equals(responseEvent.sseEvent().event())) {
413-
String messageEndpointUri = responseEvent.sseEvent().data();
414-
try {
415-
messageEndpointValidator.validate(uri, messageEndpointUri);
416-
}
417-
catch (InvalidSseMessageEndpointException e) {
418-
sink.error(e);
419-
this.messageEndpointSink.tryEmitError(e);
420-
return Flux.error(e);
421-
}
422-
if (this.messageEndpointSink.tryEmitValue(messageEndpointUri).isSuccess()) {
423-
sink.success();
424-
return Flux.empty(); // No further processing needed
425-
}
426-
else {
427-
sink.error(new RuntimeException("Failed to handle SSE endpoint event"));
428-
}
404+
Flux<String> lines = ResponseBodyHandlers.decodeLines(response.body(), this.maxResponseSize);
405+
return ResponseBodyHandlers.decodeSseResponse(lines, this.maxResponseSize);
406+
}
407+
else {
408+
return ResponseBodyHandlers.readThenError(response.body(), this.maxResponseSize,
409+
"Failed to connect to SSE stream: " + statusCode);
410+
}
411+
})
412+
// Every successfully processed event yields exactly one element, empty
413+
// when it carries no message, so that the first one can mark the
414+
// connection as established.
415+
.<Optional<JSONRPCMessage>>handle((sseEvent, events) -> {
416+
try {
417+
if (ENDPOINT_EVENT_TYPE.equals(sseEvent.event())) {
418+
String messageEndpointUri = sseEvent.data();
419+
try {
420+
messageEndpointValidator.validate(uri, messageEndpointUri);
421+
}
422+
catch (InvalidSseMessageEndpointException e) {
423+
this.messageEndpointSink.tryEmitError(e);
424+
events.error(e);
425+
return;
429426
}
430-
else if (MESSAGE_EVENT_TYPE.equals(responseEvent.sseEvent().event())) {
431-
JSONRPCMessage message = McpSchema.deserializeJsonRpcMessage(jsonMapper,
432-
responseEvent.sseEvent().data());
433-
sink.success();
434-
return Flux.just(message);
427+
if (this.messageEndpointSink.tryEmitValue(messageEndpointUri).isSuccess()) {
428+
events.next(Optional.empty());
435429
}
436430
else {
437-
logger.debug("Received unrecognized SSE event type: {}", responseEvent.sseEvent());
438-
sink.success();
431+
events.error(new McpTransportException("Failed to handle SSE endpoint event"));
439432
}
440433
}
441-
catch (IOException e) {
442-
sink.error(new McpTransportException("Error processing SSE event", e));
434+
else if (MESSAGE_EVENT_TYPE.equals(sseEvent.event())) {
435+
String data = sseEvent.data();
436+
if (data == null || data.isBlank()) {
437+
logger.debug("Skipping SSE event with empty data (stream primer)");
438+
events.next(Optional.empty());
439+
}
440+
else {
441+
events.next(Optional.of(McpSchema.deserializeJsonRpcMessage(jsonMapper, data)));
442+
}
443+
}
444+
else {
445+
logger.debug("Received unrecognized SSE event type: {}", sseEvent);
446+
events.next(Optional.empty());
443447
}
444448
}
445-
return Flux.<McpSchema.JSONRPCMessage>error(
446-
new RuntimeException("Failed to send message: " + responseEvent));
447-
449+
catch (IOException e) {
450+
events.error(new McpTransportException("Error processing SSE event", e));
451+
}
448452
})
449-
.flatMap(jsonRpcMessage -> handler.apply(Mono.just(jsonRpcMessage)))
453+
// connect() is resolved by the first signal only: any later failure is
454+
// merely logged below, as connect() has already completed by then.
455+
.switchOnFirst((first, events) -> {
456+
if (first.hasValue()) {
457+
sink.success();
458+
}
459+
else if (first.isOnError()) {
460+
sink.error(first.getThrowable());
461+
}
462+
else if (first.isOnComplete()) {
463+
sink.error(new McpTransportException("SSE stream closed before any event was received"));
464+
}
465+
return events;
466+
})
467+
.<JSONRPCMessage>handle((message, messages) -> message.ifPresent(messages::next))
468+
.flatMap(message -> handler.apply(Mono.just(message)))
450469
.onErrorComplete(t -> {
451470
if (!isClosing) {
452471
logger.warn("SSE stream observed an error", t);
453-
sink.error(t);
454472
}
455473
return true;
456474
})
475+
// A closeGracefully() before the first signal cancels the stream:
476+
// complete
477+
// connect() instead of leaving it pending. A no-op once it has resolved.
478+
.doOnCancel(sink::success)
457479
.doFinally(s -> {
458480
Disposable ref = this.sseSubscription.getAndSet(null);
459481
if (ref != null && !ref.isDisposed()) {
@@ -486,17 +508,7 @@ public Mono<Void> sendMessage(JSONRPCMessage message) {
486508
}
487509

488510
return this.serializeMessage(message)
489-
.flatMap(body -> sendHttpPost(messageEndpointUri, body).handle((response, sink) -> {
490-
if (response.statusCode() != 200 && response.statusCode() != 201 && response.statusCode() != 202
491-
&& response.statusCode() != 206) {
492-
sink.error(new RuntimeException("Sending message failed with a non-OK HTTP code: "
493-
+ response.statusCode() + " - " + response.body()));
494-
}
495-
else {
496-
sink.next(response);
497-
sink.complete();
498-
}
499-
}))
511+
.flatMap(body -> sendHttpPost(messageEndpointUri, body))
500512
.doOnError(error -> {
501513
if (!isClosing) {
502514
logger.error("Error sending message: {}", error.getMessage());
@@ -517,7 +529,16 @@ private Mono<String> serializeMessage(final JSONRPCMessage message) {
517529
});
518530
}
519531

520-
private Mono<HttpResponse<String>> sendHttpPost(final String endpoint, final String body) {
532+
/**
533+
* POSTs {@code body} to {@code endpoint} and consumes the response, failing if the
534+
* server did not accept the message.
535+
*
536+
* <p>
537+
* The response body is streamed rather than aggregated: it is only read as text when
538+
* a non-OK status makes it part of the failure message, and discarded otherwise.
539+
* Either way it has to be consumed, or the connection is never released.
540+
*/
541+
private Mono<Void> sendHttpPost(final String endpoint, final String body) {
521542
final URI requestUri = Utils.resolveUri(baseUri, endpoint);
522543
return Mono.deferContextual(ctx -> {
523544
var builder = this.requestBuilder.copy()
@@ -529,8 +550,15 @@ private Mono<HttpResponse<String>> sendHttpPost(final String endpoint, final Str
529550
return Mono.from(this.httpRequestCustomizer.customize(builder, "POST", requestUri, body, transportContext));
530551
}).flatMap(customizedBuilder -> {
531552
var request = customizedBuilder.build();
532-
return Mono.fromFuture(
533-
httpClient.sendAsync(request, ResponseSubscribers.boundedStringBodyHandler(this.maxResponseSize)));
553+
return ResponseBodyHandlers.sendAsync(this.httpClient, request).flatMap(response -> {
554+
int statusCode = response.statusCode();
555+
if (statusCode == 200 || statusCode == 201 || statusCode == 202 || statusCode == 206) {
556+
return ResponseBodyHandlers.drain(response.body(), this.maxResponseSize).then();
557+
}
558+
return ResponseBodyHandlers.decodeAggregateResponse(response.body(), this.maxResponseSize)
559+
.flatMap(text -> Mono.error(new McpTransportException(
560+
"Sending message failed with a non-OK HTTP code: " + statusCode + " - " + text)));
561+
});
534562
});
535563
}
536564

0 commit comments

Comments
 (0)