Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import io.modelcontextprotocol.spec.McpTransportSessionNotFoundException;
import io.modelcontextprotocol.spec.McpTransportStream;
import io.modelcontextprotocol.util.Assert;
import io.modelcontextprotocol.util.Utils;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
Expand Down Expand Up @@ -244,7 +245,7 @@ public Mono<Void> sendMessage(McpSchema.JSONRPCMessage message) {

Disposable connection = webClient.post()
.uri(this.endpoint)
.accept(MediaType.TEXT_EVENT_STREAM, MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON, MediaType.TEXT_EVENT_STREAM)
.headers(httpHeaders -> {
transportSession.sessionId().ifPresent(id -> httpHeaders.add("mcp-session-id", id));
})
Expand Down Expand Up @@ -387,9 +388,14 @@ private static String sessionIdOrPlaceholder(McpTransportSession<?> transportSes
private Flux<McpSchema.JSONRPCMessage> responseFlux(ClientResponse response) {
return response.bodyToMono(String.class).<Iterable<McpSchema.JSONRPCMessage>>handle((responseMessage, s) -> {
try {
McpSchema.JSONRPCMessage jsonRpcResponse = McpSchema.deserializeJsonRpcMessage(objectMapper,
responseMessage);
s.next(List.of(jsonRpcResponse));
if (Utils.hasText(responseMessage) && !responseMessage.trim().equals("{}")) {
McpSchema.JSONRPCMessage jsonRpcResponse = McpSchema.deserializeJsonRpcMessage(objectMapper,
responseMessage);
s.next(List.of(jsonRpcResponse));
}
else {
logger.warn("Received empty response message: {}", responseMessage);
Copy link
Copy Markdown
Member

@chemicL chemicL Jul 18, 2025

Choose a reason for hiding this comment

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

I am a bit worried that if the request body was an MCP Request then we will never complete a pending operation that awaits for it. Please consider adding a check whether the original message was a request and if so send an error to the Flux (using handle's sink).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Unfortunately if we receive an empty response message (e.g. null, " " or {}) there is no way to determine if it is a bogus response from a previous request, compliment notification response or bogus request.
Here we assume that if an empty even is received thread it as incorrect notification response.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think we have to cancel the request's sink though. We end up in this method if the server responded with an application/json content type. That means semantically we are to consume a response here. If there is nothing, we have to clean up the request sink, otherwise we are creating memory leaks and also not really doing the users of the client a favour not letting them know that the request has failed to fulfil the promise of a response.

}
}
catch (IOException e) {
s.error(e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ public Mono<Void> sendMessage(McpSchema.JSONRPCMessage sendMessage) {
String jsonBody = this.toString(sendMessage);

HttpRequest request = requestBuilder.uri(Utils.resolveUri(this.baseUri, this.endpoint))
.header("Accept", TEXT_EVENT_STREAM + ", " + APPLICATION_JSON)
.header("Accept", APPLICATION_JSON + ", " + TEXT_EVENT_STREAM)
.header("Content-Type", APPLICATION_JSON)
.header("Cache-Control", "no-cache")
.POST(HttpRequest.BodyPublishers.ofString(jsonBody))
Expand Down Expand Up @@ -436,11 +436,19 @@ else if (contentType.contains(TEXT_EVENT_STREAM)) {
else if (contentType.contains(APPLICATION_JSON)) {
messageSink.success();
String data = ((ResponseSubscribers.AggregateResponseEvent) responseEvent).data();
try {
return Mono.just(McpSchema.deserializeJsonRpcMessage(objectMapper, data));
if (Utils.hasText(data) && !data.trim().equals("{}")) {

try {
return Mono.just(McpSchema.deserializeJsonRpcMessage(objectMapper, data));
}
catch (IOException e) {
return Mono.error(e);
}
}
catch (IOException e) {
return Mono.error(e);
else {
// No content type means no response body
logger.debug("No content type returned for POST in session {}", sessionRepresentation);
return Mono.empty();
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Same comment as for the WebClient implementation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

it is the same problem as above

}
}
logger.warn("Unknown media type {} returned for POST in session {}", contentType,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,36 +135,46 @@ protected void hookOnSubscribe(Subscription subscription) {

@Override
protected void hookOnNext(String line) {
if (line.isEmpty()) {
// Empty line means end of event
if (this.eventBuilder.length() > 0) {
String eventData = this.eventBuilder.toString();
SseEvent sseEvent = new SseEvent(currentEventId.get(), currentEventType.get(), eventData.trim());

this.sink.next(new SseResponseEvent(responseInfo, sseEvent));
this.eventBuilder.setLength(0);
}
}
else {
if (line.startsWith("data:")) {
var matcher = EVENT_DATA_PATTERN.matcher(line);
if (matcher.find()) {
this.eventBuilder.append(matcher.group(1).trim()).append("\n");
if (this.responseInfo.statusCode() >= 200 && this.responseInfo.statusCode() < 300) {

if (line.isEmpty()) {
// Empty line means end of event
if (this.eventBuilder.length() > 0) {
String eventData = this.eventBuilder.toString();
SseEvent sseEvent = new SseEvent(currentEventId.get(), currentEventType.get(),
eventData.trim());

this.sink.next(new SseResponseEvent(responseInfo, sseEvent));
this.eventBuilder.setLength(0);
}
}
else if (line.startsWith("id:")) {
var matcher = EVENT_ID_PATTERN.matcher(line);
if (matcher.find()) {
this.currentEventId.set(matcher.group(1).trim());
else {
if (line.startsWith("data:")) {
var matcher = EVENT_DATA_PATTERN.matcher(line);
if (matcher.find()) {
this.eventBuilder.append(matcher.group(1).trim()).append("\n");
}
}
}
else if (line.startsWith("event:")) {
var matcher = EVENT_TYPE_PATTERN.matcher(line);
if (matcher.find()) {
this.currentEventType.set(matcher.group(1).trim());
else if (line.startsWith("id:")) {
var matcher = EVENT_ID_PATTERN.matcher(line);
if (matcher.find()) {
this.currentEventId.set(matcher.group(1).trim());
}
}
else if (line.startsWith("event:")) {
var matcher = EVENT_TYPE_PATTERN.matcher(line);
if (matcher.find()) {
this.currentEventType.set(matcher.group(1).trim());
}
}
}
}
else {
// If the response is not successful, emit an error
System.out.println("Received non-successful response: " + this.responseInfo.statusCode());
SseEvent sseEvent = new SseEvent(null, null, null);
this.sink.next(new SseResponseEvent(responseInfo, sseEvent));
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This looks unfinished. Did you intend to use the logger and call sink.error ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yeh good catch. I've mistakenly commit some experiments. Above logic is incorrect.

}
}

@Override
Expand Down
3 changes: 3 additions & 0 deletions mcp/src/main/java/io/modelcontextprotocol/util/Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ public static boolean isEmpty(@Nullable Map<?, ?> map) {
* base URL or URI is malformed
*/
public static URI resolveUri(URI baseUrl, String endpointUrl) {
if (!Utils.hasText(endpointUrl)) {
return baseUrl;
}
URI endpointUri = URI.create(endpointUrl);
if (endpointUri.isAbsolute() && !isUnderBaseUri(baseUrl, endpointUri)) {
throw new IllegalArgumentException("Absolute endpoint URL does not match the base URL.");
Expand Down