Skip to content

fix: improve compatibility with non-compliant MCP servers #413

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
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
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.

}
}
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
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
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 @@ -12,6 +12,7 @@
import org.reactivestreams.FlowAdapters;
import org.reactivestreams.Subscription;

import io.modelcontextprotocol.spec.McpError;
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.FluxSink;

Expand Down Expand Up @@ -135,6 +136,7 @@ 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) {
Expand Down Expand Up @@ -164,6 +166,12 @@ else if (line.startsWith("event:")) {
this.currentEventType.set(matcher.group(1).trim());
}
}
else {
// If the response is not successful, emit an error
this.sink.error(new McpError(
"Invalid SSE response. Status code: " + this.responseInfo.statusCode() + " Line: " + line));

}
}
}

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
Loading