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

Closed
wants to merge 5 commits into from
Closed
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 @@ -287,7 +288,7 @@ else if (mediaType.isCompatibleWith(MediaType.APPLICATION_JSON)) {
logger.trace("Received response to POST for session {}", sessionRepresentation);
// communicate to caller the message was delivered
sink.success();
return responseFlux(response);
return directResponseFlux(message, response);
}
else {
logger.warn("Unknown media type {} returned for POST in session {}", contentType,
Expand Down Expand Up @@ -384,14 +385,22 @@ private static String sessionIdOrPlaceholder(McpTransportSession<?> transportSes
return transportSession.sessionId().orElse("[missing_session_id]");
}

private Flux<McpSchema.JSONRPCMessage> responseFlux(ClientResponse response) {
private Flux<McpSchema.JSONRPCMessage> directResponseFlux(McpSchema.JSONRPCMessage sentMessage,
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 (sentMessage instanceof McpSchema.JSONRPCNotification && Utils.hasText(responseMessage)) {
logger.warn("Notification: {} received non-compliant response: {}", sentMessage, responseMessage);
s.complete();
}
else {
McpSchema.JSONRPCMessage jsonRpcResponse = McpSchema.deserializeJsonRpcMessage(objectMapper,
responseMessage);
s.next(List.of(jsonRpcResponse));
}
}
catch (IOException e) {
// TODO: this should be a McpTransportError
s.error(e);
}
}).flatMapIterable(Function.identity());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -342,9 +342,9 @@ public String toString(McpSchema.JSONRPCMessage message) {
}
}

public Mono<Void> sendMessage(McpSchema.JSONRPCMessage sendMessage) {
public Mono<Void> sendMessage(McpSchema.JSONRPCMessage sentMessage) {
return Mono.create(messageSink -> {
logger.debug("Sending message {}", sendMessage);
logger.debug("Sending message {}", sentMessage);

final AtomicReference<Disposable> disposableRef = new AtomicReference<>();
final McpTransportSession<Disposable> transportSession = this.activeSession.get();
Expand All @@ -355,10 +355,10 @@ public Mono<Void> sendMessage(McpSchema.JSONRPCMessage sendMessage) {
requestBuilder = requestBuilder.header("mcp-session-id", transportSession.sessionId().get());
}

String jsonBody = this.toString(sendMessage);
String jsonBody = this.toString(sentMessage);

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,10 +436,16 @@ else if (contentType.contains(TEXT_EVENT_STREAM)) {
else if (contentType.contains(APPLICATION_JSON)) {
messageSink.success();
String data = ((ResponseSubscribers.AggregateResponseEvent) responseEvent).data();
if (sentMessage instanceof McpSchema.JSONRPCNotification && Utils.hasText(data)) {
logger.warn("Notification: {} received non-compliant response: {}", sentMessage, data);
return Mono.empty();
}

try {
return Mono.just(McpSchema.deserializeJsonRpcMessage(objectMapper, data));
}
catch (IOException e) {
// TODO: this should be a McpTransportError
return Mono.error(e);
}
}
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,13 @@ else if (line.startsWith("event:")) {
this.currentEventType.set(matcher.group(1).trim());
}
}
else {
// If the response is not successful, emit an error
// TODO: This should be a McpTransportError
this.sink.error(new McpError(
Copy link
Member

Choose a reason for hiding this comment

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

I believe this should be a McpTransportError, please keep a note of it :)

"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