|
| 1 | +package io.quarkiverse.langchain4j.mcp.test; |
| 2 | + |
| 3 | +import java.util.Map; |
| 4 | +import java.util.Random; |
| 5 | +import java.util.concurrent.CompletableFuture; |
| 6 | +import java.util.concurrent.ConcurrentHashMap; |
| 7 | +import java.util.concurrent.ScheduledExecutorService; |
| 8 | +import java.util.concurrent.TimeUnit; |
| 9 | +import java.util.concurrent.atomic.AtomicLong; |
| 10 | + |
| 11 | +import jakarta.inject.Inject; |
| 12 | +import jakarta.ws.rs.Consumes; |
| 13 | +import jakarta.ws.rs.POST; |
| 14 | +import jakarta.ws.rs.Path; |
| 15 | +import jakarta.ws.rs.Produces; |
| 16 | +import jakarta.ws.rs.core.Context; |
| 17 | +import jakarta.ws.rs.core.MediaType; |
| 18 | +import jakarta.ws.rs.core.Response; |
| 19 | +import jakarta.ws.rs.sse.Sse; |
| 20 | +import jakarta.ws.rs.sse.SseEventSink; |
| 21 | + |
| 22 | +import org.jboss.logging.Logger; |
| 23 | +import org.jboss.resteasy.reactive.RestStreamElementType; |
| 24 | + |
| 25 | +import com.fasterxml.jackson.databind.JsonNode; |
| 26 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 27 | +import com.fasterxml.jackson.databind.node.ObjectNode; |
| 28 | + |
| 29 | +public abstract class AbstractMockHttpMcpServer { |
| 30 | + |
| 31 | + private final AtomicLong ID_GENERATOR = new AtomicLong(new Random().nextLong(1000, 5000)); |
| 32 | + |
| 33 | + private static Logger logger = Logger.getLogger(MockHttpMcpServer.class); |
| 34 | + |
| 35 | + private volatile boolean shouldRespondToPing = true; |
| 36 | + |
| 37 | + // key = operation ID of the ping |
| 38 | + // value = future that will be completed when the ping response for that ID is received |
| 39 | + final Map<Long, CompletableFuture<Void>> pendingPings = new ConcurrentHashMap<>(); |
| 40 | + |
| 41 | + private volatile SseEventSink sink; |
| 42 | + private volatile Sse sse; |
| 43 | + private final ObjectMapper objectMapper = new ObjectMapper(); |
| 44 | + private volatile boolean initializationNotificationReceived = false; |
| 45 | + |
| 46 | + @Inject |
| 47 | + ScheduledExecutorService scheduledExecutorService; |
| 48 | + |
| 49 | + @Path("/sse") |
| 50 | + @Produces(MediaType.SERVER_SENT_EVENTS) |
| 51 | + @RestStreamElementType(MediaType.TEXT_PLAIN) |
| 52 | + public void sse(@Context SseEventSink sink, @Context Sse sse) { |
| 53 | + this.sink = sink; |
| 54 | + this.sse = sse; |
| 55 | + sink.send(sse.newEventBuilder() |
| 56 | + .id("id") |
| 57 | + .name("endpoint") |
| 58 | + .mediaType(MediaType.TEXT_PLAIN_TYPE) |
| 59 | + .data("/" + getEndpoint() + "/post") |
| 60 | + .build()); |
| 61 | + } |
| 62 | + |
| 63 | + protected abstract String getEndpoint(); |
| 64 | + |
| 65 | + @Path("/post") |
| 66 | + @Consumes(MediaType.APPLICATION_JSON) |
| 67 | + @POST |
| 68 | + public Response post(JsonNode message) { |
| 69 | + if (message.get("method") != null) { |
| 70 | + String method = message.get("method").asText(); |
| 71 | + if (method.equals("notifications/cancelled")) { |
| 72 | + return Response.ok().build(); |
| 73 | + } |
| 74 | + if (method.equals("notifications/initialized")) { |
| 75 | + if (initializationNotificationReceived) { |
| 76 | + return Response.serverError().entity("Duplicate 'notifications/initialized' message").build(); |
| 77 | + } |
| 78 | + initializationNotificationReceived = true; |
| 79 | + return Response.ok().build(); |
| 80 | + } |
| 81 | + String operationId = message.get("id").asText(); |
| 82 | + if (method.equals("initialize")) { |
| 83 | + initialize(operationId); |
| 84 | + } else if (method.equals("tools/list")) { |
| 85 | + ensureInitialized(); |
| 86 | + listTools(operationId); |
| 87 | + } else if (method.equals("tools/call")) { |
| 88 | + ensureInitialized(); |
| 89 | + if (message.get("params").get("name").asText().equals("add")) { |
| 90 | + executeAddOperation(message, operationId); |
| 91 | + } else if (message.get("params").get("name").asText().equals("logging")) { |
| 92 | + executeLoggingOperation(message, operationId); |
| 93 | + } else if (message.get("params").get("name").asText().equals("longRunningOperation")) { |
| 94 | + executeLongRunningOperation(message, operationId); |
| 95 | + } else { |
| 96 | + return Response.serverError().entity("Unknown operation").build(); |
| 97 | + } |
| 98 | + |
| 99 | + } else if (method.equals("ping")) { |
| 100 | + if (shouldRespondToPing) { |
| 101 | + ObjectNode result = buildPongMessage(operationId); |
| 102 | + sink.send(sse.newEventBuilder() |
| 103 | + .name("message") |
| 104 | + .data(result) |
| 105 | + .build()); |
| 106 | + } else { |
| 107 | + logger.info("Ignoring ping request"); |
| 108 | + } |
| 109 | + return Response.accepted().build(); |
| 110 | + } |
| 111 | + } else { |
| 112 | + // if 'method' is null, the message is probably a ping response |
| 113 | + long id = message.get("id").asLong(); |
| 114 | + CompletableFuture<Void> future = pendingPings.remove(id); |
| 115 | + if (future != null) { |
| 116 | + future.complete(null); |
| 117 | + } else { |
| 118 | + return Response.serverError().entity("Received a ping response with unknown ID " + id).build(); |
| 119 | + } |
| 120 | + } |
| 121 | + return Response.accepted().build(); |
| 122 | + } |
| 123 | + |
| 124 | + private ObjectNode buildPongMessage(String operationId) { |
| 125 | + ObjectNode pong = objectMapper.createObjectNode(); |
| 126 | + pong.put("jsonrpc", "2.0"); |
| 127 | + pong.put("id", operationId); |
| 128 | + pong.put("result", objectMapper.createObjectNode()); |
| 129 | + return pong; |
| 130 | + } |
| 131 | + |
| 132 | + private void executeLoggingOperation(JsonNode message, String operationId) { |
| 133 | + ObjectNode logData = objectMapper.createObjectNode(); |
| 134 | + logData.put("message", "This is a log message"); |
| 135 | + ObjectNode log = buildLoggingMessage(logData); |
| 136 | + sink.send(sse.newEventBuilder() |
| 137 | + .name("message") |
| 138 | + .data(log) |
| 139 | + .build()); |
| 140 | + ObjectNode result = buildToolResult(operationId, "OK"); |
| 141 | + sink.send(sse.newEventBuilder() |
| 142 | + .name("message") |
| 143 | + .data(result) |
| 144 | + .build()); |
| 145 | + } |
| 146 | + |
| 147 | + private ObjectNode buildLoggingMessage(JsonNode message) { |
| 148 | + ObjectNode log = objectMapper.createObjectNode(); |
| 149 | + log.put("jsonrpc", "2.0"); |
| 150 | + log.put("method", "notifications/message"); |
| 151 | + ObjectNode params = objectMapper.createObjectNode(); |
| 152 | + log.set("params", params); |
| 153 | + params.put("level", "info"); |
| 154 | + params.put("logger", getEndpoint()); |
| 155 | + params.set("data", message); |
| 156 | + return log; |
| 157 | + } |
| 158 | + |
| 159 | + private ObjectNode buildToolResult(String operationId, String result) { |
| 160 | + ObjectNode resultNode = objectMapper.createObjectNode(); |
| 161 | + resultNode.put("id", operationId); |
| 162 | + resultNode.put("jsonrpc", "2.0"); |
| 163 | + ObjectNode resultContent = objectMapper.createObjectNode(); |
| 164 | + resultNode.set("result", resultContent); |
| 165 | + resultContent.putArray("content") |
| 166 | + .addObject() |
| 167 | + .put("type", "text") |
| 168 | + .put("text", result); |
| 169 | + return resultNode; |
| 170 | + } |
| 171 | + |
| 172 | + // throw an exception if we haven't received the 'notifications/initialized' message yet |
| 173 | + private void ensureInitialized() { |
| 174 | + if (!initializationNotificationReceived) { |
| 175 | + throw new IllegalStateException("The client has not sent the 'notifications/initialized' message yet"); |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + private void listTools(String operationId) { |
| 180 | + String response = getToolsListResponse().formatted(operationId); |
| 181 | + sink.send(sse.newEventBuilder() |
| 182 | + .name("message") |
| 183 | + .data(response) |
| 184 | + .build()); |
| 185 | + } |
| 186 | + |
| 187 | + protected abstract String getToolsListResponse(); |
| 188 | + |
| 189 | + private void initialize(String operationId) { |
| 190 | + ObjectNode initializeResponse = objectMapper.createObjectNode(); |
| 191 | + initializeResponse |
| 192 | + .put("id", operationId) |
| 193 | + .put("jsonrpc", "2.0") |
| 194 | + .putObject("result") |
| 195 | + .put("protocolVersion", "2024-11-05"); |
| 196 | + sink.send(sse.newEventBuilder() |
| 197 | + .name("message") |
| 198 | + .data(initializeResponse) |
| 199 | + .build()); |
| 200 | + } |
| 201 | + |
| 202 | + private void executeAddOperation(JsonNode message, String operationId) { |
| 203 | + int a = message.get("params").get("arguments").get("a").asInt(); |
| 204 | + int b = message.get("params").get("arguments").get("b").asInt(); |
| 205 | + int additionResult = a + b; |
| 206 | + ObjectNode result = buildToolResult(operationId, "The sum of " + a + " and " + b + " is " + additionResult + "."); |
| 207 | + sink.send(sse.newEventBuilder() |
| 208 | + .name("message") |
| 209 | + .data(result) |
| 210 | + .build()); |
| 211 | + } |
| 212 | + |
| 213 | + private void executeLongRunningOperation(JsonNode message, String operationId) { |
| 214 | + int duration = message.get("params").get("arguments").get("duration").asInt(); |
| 215 | + scheduledExecutorService.schedule(() -> { |
| 216 | + ObjectNode result = buildToolResult(operationId, "Operation completed."); |
| 217 | + sink.send(sse.newEventBuilder() |
| 218 | + .name("message") |
| 219 | + .data(result) |
| 220 | + .build()); |
| 221 | + }, duration, TimeUnit.SECONDS); |
| 222 | + } |
| 223 | + |
| 224 | + long sendPing() { |
| 225 | + ObjectNode initializeResponse = objectMapper.createObjectNode(); |
| 226 | + long id = ID_GENERATOR.incrementAndGet(); |
| 227 | + initializeResponse |
| 228 | + .put("id", id) |
| 229 | + .put("jsonrpc", "2.0") |
| 230 | + .put("method", "ping"); |
| 231 | + sink.send(sse.newEventBuilder() |
| 232 | + .name("message") |
| 233 | + .data(initializeResponse) |
| 234 | + .build()); |
| 235 | + pendingPings.put(id, new CompletableFuture<>()); |
| 236 | + return id; |
| 237 | + } |
| 238 | + |
| 239 | + void stopRespondingToPings() { |
| 240 | + shouldRespondToPing = false; |
| 241 | + } |
| 242 | +} |
0 commit comments