Skip to content

feat: implement HttpClient Streamable HTTP transport #337

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 13 commits into from
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 @@ -79,7 +79,7 @@ public abstract class AbstractMcpAsyncClientResiliencyTests {
host = "http://" + ipAddressViaToxiproxy + ":" + portViaToxiproxy;
}

private static void disconnect() {
static void disconnect() {
long start = System.nanoTime();
try {
// disconnect
Expand All @@ -96,7 +96,7 @@ private static void disconnect() {
}
}

private static void reconnect() {
static void reconnect() {
long start = System.nanoTime();
try {
proxy.toxics().get("RESET_UPSTREAM").remove();
Expand All @@ -110,7 +110,7 @@ private static void reconnect() {
}
}

private static void restartMcpServer() {
static void restartMcpServer() {
container.stop();
container.start();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
Expand Down Expand Up @@ -135,7 +136,7 @@ public static Builder builder(String baseUri) {
public Mono<Void> connect(Function<Mono<McpSchema.JSONRPCMessage>, Mono<McpSchema.JSONRPCMessage>> handler) {
return Mono.deferContextual(ctx -> {
this.handler.set(handler);
if (openConnectionOnStartup) {
if (this.openConnectionOnStartup) {
logger.debug("Eagerly opening connection on startup");
return this.reconnect(null).onErrorComplete(t -> {
logger.warn("Eager connect failed ", t);
Expand Down Expand Up @@ -286,6 +287,7 @@ else if (statusCode == BAD_REQUEST) {

}).<McpSchema
.JSONRPCMessage>flatMap(jsonrpcMessage -> this.handler.get().apply(Mono.just(jsonrpcMessage)))
.onErrorMap(CompletionException.class, t -> t.getCause())
.onErrorComplete(t -> {
this.handleException(t);
return true;
Expand Down Expand Up @@ -373,7 +375,7 @@ public Mono<Void> sendMessage(McpSchema.JSONRPCMessage sendMessage) {
else {
logger.debug("SSE connection established successfully");
}
})).onErrorComplete().subscribe();
})).onErrorMap(CompletionException.class, t -> t.getCause()).onErrorComplete().subscribe();
Copy link
Member

Choose a reason for hiding this comment

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

this is not necessary, since it's swallowed in the next operator. And that's ok since we emit the throwable to the sink. We can clean this up afterwards.


}).flatMap(responseEvent -> {
if (transportSession.markInitialized(
Expand Down Expand Up @@ -464,19 +466,25 @@ else if (statusCode == BAD_REQUEST) {

return Flux.<McpSchema.JSONRPCMessage>error(
new RuntimeException("Failed to send message: " + responseEvent));
}).flatMap(jsonRpcMessage -> this.handler.get().apply(Mono.just(jsonRpcMessage))).onErrorComplete(t -> {
// handle the error first
this.handleException(t);
// inform the caller of sendMessage
messageSink.error(t);
return true;
}).doFinally(s -> {
logger.debug("SendMessage finally: {}", s);
Disposable ref = disposableRef.getAndSet(null);
if (ref != null) {
transportSession.removeConnection(ref);
}
}).contextWrite(messageSink.contextView()).subscribe();
})
.flatMap(jsonRpcMessage -> this.handler.get().apply(Mono.just(jsonRpcMessage)))
.onErrorMap(CompletionException.class, t -> t.getCause())
.onErrorComplete(t -> {
// handle the error first
this.handleException(t);
// inform the caller of sendMessage
messageSink.error(t);
return true;
})
.doFinally(s -> {
logger.debug("SendMessage finally: {}", s);
Disposable ref = disposableRef.getAndSet(null);
if (ref != null) {
transportSession.removeConnection(ref);
}
})
.contextWrite(messageSink.contextView())
.subscribe();

disposableRef.set(connection);
transportSession.addConnection(connection);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,20 @@
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.FluxSink;

/**
* Utility class providing various {@link BodySubscriber} implementations for handling
* different types of HTTP response bodies in the context of Model Context Protocol (MCP)
* clients.
*
* <p>
* Defines subscribers for processing Server-Sent Events (SSE), aggregate responses, and
* bodiless responses.
*
* @author Christian Tzolov
* @author Dariusz Jędrzejczyk
*/
class ResponseSubscribers {

/**
* Represents a Server-Sent Event with its standard fields.
*
* @param id the event ID, may be {@code null}
* @param event the event type, may be {@code null} (defaults to "message")
* @param data the event payload data, never {@code null}
*/
record SseEvent(String id, String event, String data) {
}

Expand Down Expand Up @@ -115,10 +120,6 @@ public SseLineSubscriber(ResponseInfo responseInfo, FluxSink<ResponseEvent> sink
this.responseInfo = responseInfo;
}

/**
* Initializes the subscription and sets up disposal callback.
* @param subscription the {@link Subscription} to the upstream line source
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {

Expand All @@ -132,12 +133,6 @@ protected void hookOnSubscribe(Subscription subscription) {
});
}

/**
* Processes each line from the SSE stream according to the SSE protocol. Empty
* lines trigger event emission, other lines are parsed for data, id, or event
* type.
* @param line the line to process from the SSE stream
*/
@Override
protected void hookOnNext(String line) {
if (line.isEmpty()) {
Expand Down Expand Up @@ -172,9 +167,6 @@ else if (line.startsWith("event:")) {
}
}

/**
* Called when the upstream line source completes normally.
*/
@Override
protected void hookOnComplete() {
if (this.eventBuilder.length() > 0) {
Expand All @@ -185,10 +177,6 @@ protected void hookOnComplete() {
this.sink.complete();
}

/**
* Called when an error occurs in the upstream line source.
* @param throwable the error that occurred
*/
@Override
protected void hookOnError(Throwable throwable) {
this.sink.error(throwable);
Expand Down Expand Up @@ -225,10 +213,6 @@ public AggregateSubscriber(ResponseInfo responseInfo, FluxSink<ResponseEvent> si
this.responseInfo = responseInfo;
}

/**
* Initializes the subscription and sets up disposal callback.
* @param subscription the {@link Subscription} to the upstream line source
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {
sink.onRequest(subscription::request);
Expand All @@ -237,18 +221,11 @@ protected void hookOnSubscribe(Subscription subscription) {
sink.onDispose(subscription::cancel);
}

/**
* Aggregate each line from the Http response.
* @param line next line to process from the Http response
*/
@Override
protected void hookOnNext(String line) {
this.eventBuilder.append(line).append("\n");
}

/**
* Called when the upstream line source completes normally.
*/
@Override
protected void hookOnComplete() {
if (this.eventBuilder.length() > 0) {
Expand All @@ -258,10 +235,6 @@ protected void hookOnComplete() {
this.sink.complete();
}

/**
* Called when an error occurs in the upstream line source.
* @param throwable the error that occurred
*/
@Override
protected void hookOnError(Throwable throwable) {
this.sink.error(throwable);
Expand All @@ -283,10 +256,6 @@ public BodilessResponseLineSubscriber(ResponseInfo responseInfo, FluxSink<Respon
this.responseInfo = responseInfo;
}

/**
* Initializes the subscription and sets up disposal callback.
* @param subscription the {@link Subscription} to the upstream line source
*/
@Override
protected void hookOnSubscribe(Subscription subscription) {

Expand All @@ -300,9 +269,6 @@ protected void hookOnSubscribe(Subscription subscription) {
});
}

/**
* Called when the upstream line source completes normally.
*/
@Override
protected void hookOnComplete() {
// emit dummy event to be able to inspect the response info
Expand All @@ -313,10 +279,6 @@ protected void hookOnComplete() {
this.sink.complete();
}

/**
* Called when an error occurs in the upstream line source.
* @param throwable the error that occurred
*/
@Override
protected void hookOnError(Throwable throwable) {
this.sink.error(throwable);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/*
* Copyright 2024-2024 the original author or authors.
*/
package io.modelcontextprotocol.client;

import eu.rekawek.toxiproxy.Proxy;
Expand Down Expand Up @@ -35,6 +38,7 @@
*
* @author Dariusz Jędrzejczyk
*/
Copy link
Member

Choose a reason for hiding this comment

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

We need to add a note that it's a copy from mcp-test module as we do in other copied test classes to make sure we keep them in sync.

// KEEP IN SYNC with the class in mcp-test module
public abstract class AbstractMcpAsyncClientResiliencyTests {

private static final Logger logger = LoggerFactory.getLogger(AbstractMcpAsyncClientResiliencyTests.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

package io.modelcontextprotocol.client;

import java.util.concurrent.CompletionException;
import java.io.IOException;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
Expand All @@ -28,7 +28,7 @@ void testPingWithExactExceptionType() {

disconnect();

StepVerifier.create(mcpAsyncClient.ping()).expectError(CompletionException.class).verify();
StepVerifier.create(mcpAsyncClient.ping()).expectError(IOException.class).verify();

reconnect();

Expand Down