|
| 1 | +/* |
| 2 | + * Copyright 2024 - 2024 the original author or authors. |
| 3 | + */ |
| 4 | + |
| 5 | +package io.modelcontextprotocol.client.transport; |
| 6 | + |
| 7 | +import java.net.URI; |
| 8 | +import java.net.http.HttpClient; |
| 9 | +import java.net.http.WebSocket; |
| 10 | +import java.time.Duration; |
| 11 | +import java.util.concurrent.CompletableFuture; |
| 12 | +import java.util.concurrent.CompletionStage; |
| 13 | +import java.util.concurrent.atomic.AtomicReference; |
| 14 | +import java.util.function.Consumer; |
| 15 | +import java.util.function.Function; |
| 16 | + |
| 17 | +import org.slf4j.Logger; |
| 18 | +import org.slf4j.LoggerFactory; |
| 19 | + |
| 20 | +import com.fasterxml.jackson.core.type.TypeReference; |
| 21 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 22 | + |
| 23 | +import io.modelcontextprotocol.spec.McpClientTransport; |
| 24 | +import io.modelcontextprotocol.spec.McpSchema; |
| 25 | +import io.modelcontextprotocol.util.Assert; |
| 26 | +import reactor.core.publisher.Mono; |
| 27 | +import reactor.core.publisher.Sinks; |
| 28 | +import reactor.util.retry.Retry; |
| 29 | + |
| 30 | +/** |
| 31 | + * The WebSocket (WS) implementation of the |
| 32 | + * {@link io.modelcontextprotocol.spec.McpTransport} that follows the MCP HTTP with WS |
| 33 | + * transport specification, using Java's HttpClient. |
| 34 | + * |
| 35 | + * @author Aliaksei Darafeyeu |
| 36 | + */ |
| 37 | +public class WebSocketClientTransport implements McpClientTransport { |
| 38 | + |
| 39 | + private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketClientTransport.class); |
| 40 | + |
| 41 | + private final HttpClient httpClient; |
| 42 | + |
| 43 | + private final ObjectMapper objectMapper; |
| 44 | + |
| 45 | + private final URI uri; |
| 46 | + |
| 47 | + private final AtomicReference<WebSocket> webSocketRef = new AtomicReference<>(); |
| 48 | + |
| 49 | + private final AtomicReference<TransportState> state = new AtomicReference<>(TransportState.DISCONNECTED); |
| 50 | + |
| 51 | + private final Sinks.Many<Throwable> errorSink = Sinks.many().multicast().onBackpressureBuffer(); |
| 52 | + |
| 53 | + /** |
| 54 | + * The constructor for the WebSocketClientTransport. |
| 55 | + * @param uri the URI to connect to |
| 56 | + * @param clientBuilder the HttpClient builder |
| 57 | + * @param objectMapper the ObjectMapper for JSON serialization/deserialization |
| 58 | + */ |
| 59 | + WebSocketClientTransport(final URI uri, final HttpClient.Builder clientBuilder, final ObjectMapper objectMapper) { |
| 60 | + this.uri = uri; |
| 61 | + this.httpClient = clientBuilder.build(); |
| 62 | + this.objectMapper = objectMapper; |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * Creates a new WebSocketClientTransport instance with the specified URI. |
| 67 | + * @param uri the URI to connect to |
| 68 | + * @return a new Builder instance |
| 69 | + */ |
| 70 | + public static Builder builder(final URI uri) { |
| 71 | + return new Builder().uri(uri); |
| 72 | + } |
| 73 | + |
| 74 | + /** |
| 75 | + * The state of the Transport connection. |
| 76 | + */ |
| 77 | + public enum TransportState { |
| 78 | + |
| 79 | + DISCONNECTED, CONNECTING, CONNECTED, CLOSED |
| 80 | + |
| 81 | + } |
| 82 | + |
| 83 | + /** |
| 84 | + * A builder for creating instances of WebSocketClientTransport. |
| 85 | + */ |
| 86 | + public static class Builder { |
| 87 | + |
| 88 | + private URI uri; |
| 89 | + |
| 90 | + private final HttpClient.Builder clientBuilder = HttpClient.newBuilder() |
| 91 | + .version(HttpClient.Version.HTTP_1_1) |
| 92 | + .connectTimeout(Duration.ofSeconds(10)); |
| 93 | + |
| 94 | + private ObjectMapper objectMapper = new ObjectMapper(); |
| 95 | + |
| 96 | + public Builder uri(final URI uri) { |
| 97 | + this.uri = uri; |
| 98 | + return this; |
| 99 | + } |
| 100 | + |
| 101 | + public Builder customizeClient(final Consumer<HttpClient.Builder> clientCustomizer) { |
| 102 | + Assert.notNull(clientCustomizer, "clientCustomizer must not be null"); |
| 103 | + clientCustomizer.accept(clientBuilder); |
| 104 | + return this; |
| 105 | + } |
| 106 | + |
| 107 | + public Builder objectMapper(final ObjectMapper objectMapper) { |
| 108 | + this.objectMapper = objectMapper; |
| 109 | + return this; |
| 110 | + } |
| 111 | + |
| 112 | + public WebSocketClientTransport build() { |
| 113 | + return new WebSocketClientTransport(uri, clientBuilder, objectMapper); |
| 114 | + } |
| 115 | + |
| 116 | + } |
| 117 | + |
| 118 | + public Mono<Void> connect(final Function<Mono<McpSchema.JSONRPCMessage>, Mono<McpSchema.JSONRPCMessage>> handler) { |
| 119 | + if (!state.compareAndSet(TransportState.DISCONNECTED, TransportState.CONNECTING)) { |
| 120 | + return Mono.error(new IllegalStateException("WebSocket is already connecting or connected")); |
| 121 | + } |
| 122 | + |
| 123 | + return Mono.fromFuture(httpClient.newWebSocketBuilder().buildAsync(uri, new WebSocket.Listener() { |
| 124 | + private final StringBuilder messageBuffer = new StringBuilder(); |
| 125 | + |
| 126 | + @Override |
| 127 | + public void onOpen(WebSocket webSocket) { |
| 128 | + webSocketRef.set(webSocket); |
| 129 | + state.set(TransportState.CONNECTED); |
| 130 | + } |
| 131 | + |
| 132 | + @Override |
| 133 | + public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) { |
| 134 | + messageBuffer.append(data); |
| 135 | + if (last) { |
| 136 | + final String fullMessage = messageBuffer.toString(); |
| 137 | + messageBuffer.setLength(0); |
| 138 | + try { |
| 139 | + final McpSchema.JSONRPCMessage msg = McpSchema.deserializeJsonRpcMessage(objectMapper, |
| 140 | + fullMessage); |
| 141 | + handler.apply(Mono.just(msg)).subscribe(); |
| 142 | + } |
| 143 | + catch (Exception e) { |
| 144 | + errorSink.tryEmitNext(e); |
| 145 | + LOGGER.error("Error processing WS event", e); |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + webSocket.request(1); |
| 150 | + return CompletableFuture.completedFuture(null); |
| 151 | + } |
| 152 | + |
| 153 | + @Override |
| 154 | + public void onError(WebSocket webSocket, Throwable error) { |
| 155 | + errorSink.tryEmitNext(error); |
| 156 | + state.set(TransportState.CLOSED); |
| 157 | + LOGGER.error("WS connection error", error); |
| 158 | + } |
| 159 | + |
| 160 | + @Override |
| 161 | + public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) { |
| 162 | + state.set(TransportState.CLOSED); |
| 163 | + return CompletableFuture.completedFuture(null); |
| 164 | + } |
| 165 | + |
| 166 | + })).then(); |
| 167 | + } |
| 168 | + |
| 169 | + @Override |
| 170 | + public Mono<Void> sendMessage(McpSchema.JSONRPCMessage message) { |
| 171 | + |
| 172 | + return Mono.defer(() -> { |
| 173 | + WebSocket ws = webSocketRef.get(); |
| 174 | + if (ws == null && state.get() == TransportState.CONNECTING) { |
| 175 | + return Mono.error(new IllegalStateException("WebSocket is connecting.")); |
| 176 | + } |
| 177 | + |
| 178 | + if (ws == null || state.get() == TransportState.DISCONNECTED || state.get() == TransportState.CLOSED) { |
| 179 | + return Mono.error(new IllegalStateException("WebSocket is closed.")); |
| 180 | + } |
| 181 | + |
| 182 | + try { |
| 183 | + String json = objectMapper.writeValueAsString(message); |
| 184 | + return Mono.fromFuture(ws.sendText(json, true)).then(); |
| 185 | + } |
| 186 | + catch (Exception e) { |
| 187 | + return Mono.error(e); |
| 188 | + } |
| 189 | + }).retryWhen(Retry.backoff(3, Duration.ofSeconds(3)).filter(err -> { |
| 190 | + if (err instanceof IllegalStateException) { |
| 191 | + return err.getMessage().equals("WebSocket is connecting."); |
| 192 | + } |
| 193 | + return true; |
| 194 | + })).onErrorResume(e -> { |
| 195 | + LOGGER.error("Failed to send message after retries", e); |
| 196 | + errorSink.tryEmitNext(e); |
| 197 | + return Mono.error(new IllegalStateException("WebSocket send failed after retries", e)); |
| 198 | + }); |
| 199 | + |
| 200 | + } |
| 201 | + |
| 202 | + @Override |
| 203 | + public Mono<Void> closeGracefully() { |
| 204 | + WebSocket webSocket = webSocketRef.getAndSet(null); |
| 205 | + if (webSocket != null && state.get() == TransportState.CONNECTED) { |
| 206 | + state.set(TransportState.CLOSED); |
| 207 | + return Mono.fromFuture(webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "Closing")).then(); |
| 208 | + } |
| 209 | + return Mono.empty(); |
| 210 | + } |
| 211 | + |
| 212 | + @Override |
| 213 | + public <T> T unmarshalFrom(Object data, TypeReference<T> typeRef) { |
| 214 | + return objectMapper.convertValue(data, typeRef); |
| 215 | + } |
| 216 | + |
| 217 | + public TransportState getState() { |
| 218 | + return state.get(); |
| 219 | + } |
| 220 | + |
| 221 | +} |
0 commit comments