|
| 1 | +/* |
| 2 | + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +package software.amazon.smithy.java.mcp.server; |
| 7 | + |
| 8 | +import java.net.URI; |
| 9 | +import java.nio.charset.StandardCharsets; |
| 10 | +import java.time.Duration; |
| 11 | +import java.util.concurrent.CompletableFuture; |
| 12 | +import software.amazon.smithy.java.auth.api.Signer; |
| 13 | +import software.amazon.smithy.java.client.core.ClientTransport; |
| 14 | +import software.amazon.smithy.java.client.http.HttpContext; |
| 15 | +import software.amazon.smithy.java.client.http.JavaHttpClientTransport; |
| 16 | +import software.amazon.smithy.java.context.Context; |
| 17 | +import software.amazon.smithy.java.http.api.HttpRequest; |
| 18 | +import software.amazon.smithy.java.http.api.HttpResponse; |
| 19 | +import software.amazon.smithy.java.io.ByteBufferUtils; |
| 20 | +import software.amazon.smithy.java.io.datastream.DataStream; |
| 21 | +import software.amazon.smithy.java.json.JsonCodec; |
| 22 | +import software.amazon.smithy.java.json.JsonSettings; |
| 23 | +import software.amazon.smithy.java.logging.InternalLogger; |
| 24 | +import software.amazon.smithy.java.mcp.model.JsonRpcErrorResponse; |
| 25 | +import software.amazon.smithy.java.mcp.model.JsonRpcRequest; |
| 26 | +import software.amazon.smithy.java.mcp.model.JsonRpcResponse; |
| 27 | +import software.amazon.smithy.utils.SmithyUnstableApi; |
| 28 | + |
| 29 | +@SmithyUnstableApi |
| 30 | +public final class HttpMcpProxy extends McpServerProxy { |
| 31 | + private static final InternalLogger LOG = InternalLogger.getLogger(HttpMcpProxy.class); |
| 32 | + private static final JsonCodec JSON_CODEC = JsonCodec.builder() |
| 33 | + .settings(JsonSettings.builder().serializeTypeInDocuments(false).useJsonName(true).build()) |
| 34 | + .build(); |
| 35 | + |
| 36 | + private final ClientTransport<HttpRequest, HttpResponse> transport; |
| 37 | + private final URI endpoint; |
| 38 | + private final String name; |
| 39 | + private final Signer<HttpRequest, ?> signer; |
| 40 | + private final Duration timeout; |
| 41 | + |
| 42 | + private HttpMcpProxy(Builder builder) { |
| 43 | + this.transport = builder.transport != null ? builder.transport : new JavaHttpClientTransport(); |
| 44 | + this.endpoint = URI.create(builder.endpoint); |
| 45 | + this.name = builder.name != null ? builder.name : sanitizeName(endpoint.getHost()); |
| 46 | + this.signer = builder.signer; |
| 47 | + this.timeout = builder.timeout != null ? builder.timeout : Duration.ofSeconds(60); |
| 48 | + } |
| 49 | + |
| 50 | + private static String sanitizeName(String host) { |
| 51 | + if (host == null) { |
| 52 | + return "http-proxy-mcp"; |
| 53 | + } |
| 54 | + return host.replaceAll("[^a-zA-Z0-9-]", "-"); |
| 55 | + } |
| 56 | + |
| 57 | + public static final class Builder { |
| 58 | + private String endpoint; |
| 59 | + private String name; |
| 60 | + private Signer<HttpRequest, ?> signer; |
| 61 | + private ClientTransport<HttpRequest, HttpResponse> transport; |
| 62 | + private Duration timeout; |
| 63 | + |
| 64 | + public Builder endpoint(String endpoint) { |
| 65 | + this.endpoint = endpoint; |
| 66 | + return this; |
| 67 | + } |
| 68 | + |
| 69 | + public Builder name(String name) { |
| 70 | + this.name = name; |
| 71 | + return this; |
| 72 | + } |
| 73 | + |
| 74 | + public Builder signer(Signer<HttpRequest, ?> signer) { |
| 75 | + this.signer = signer; |
| 76 | + return this; |
| 77 | + } |
| 78 | + |
| 79 | + public Builder transport(ClientTransport<HttpRequest, HttpResponse> transport) { |
| 80 | + this.transport = transport; |
| 81 | + return this; |
| 82 | + } |
| 83 | + |
| 84 | + public Builder timeout(Duration timeout) { |
| 85 | + this.timeout = timeout; |
| 86 | + return this; |
| 87 | + } |
| 88 | + |
| 89 | + public HttpMcpProxy build() { |
| 90 | + if (endpoint == null || endpoint.isEmpty()) { |
| 91 | + throw new IllegalArgumentException("Endpoint must be provided"); |
| 92 | + } |
| 93 | + return new HttpMcpProxy(this); |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + public static Builder builder() { |
| 98 | + return new Builder(); |
| 99 | + } |
| 100 | + |
| 101 | + @Override |
| 102 | + public CompletableFuture<JsonRpcResponse> rpc(JsonRpcRequest request) { |
| 103 | + try { |
| 104 | + byte[] body = JSON_CODEC.serializeToString(request).getBytes(StandardCharsets.UTF_8); |
| 105 | + LOG.trace("Sending HTTP request to {}", endpoint); |
| 106 | + |
| 107 | + String protocolVersionHeader = protocolVersion != null |
| 108 | + ? protocolVersion |
| 109 | + : ProtocolVersion.defaultVersion().identifier(); |
| 110 | + |
| 111 | + HttpRequest httpRequest = HttpRequest.builder() |
| 112 | + .uri(endpoint) |
| 113 | + .method("POST") |
| 114 | + .withAddedHeader("Content-Type", "application/json") |
| 115 | + .withAddedHeader("Accept", "application/json, text/event-stream") |
| 116 | + .withAddedHeader("MCP-Protocol-Version", protocolVersionHeader) |
| 117 | + .body(DataStream.ofBytes(body, "application/json")) |
| 118 | + .build(); |
| 119 | + |
| 120 | + Context context = Context.create(); |
| 121 | + context.put(HttpContext.HTTP_REQUEST_TIMEOUT, timeout); |
| 122 | + |
| 123 | + if (signer != null) { |
| 124 | + httpRequest = signer.sign(httpRequest, null, context); |
| 125 | + } |
| 126 | + |
| 127 | + HttpResponse response = transport.send(context, httpRequest); |
| 128 | + LOG.trace("Received HTTP response with status: {}", response.statusCode()); |
| 129 | + |
| 130 | + if (response.statusCode() < 200 || response.statusCode() >= 300) { |
| 131 | + return CompletableFuture.completedFuture(handleErrorResponse(response)); |
| 132 | + } |
| 133 | + |
| 134 | + return CompletableFuture.completedFuture(JsonRpcResponse.builder() |
| 135 | + .deserialize(JSON_CODEC.createDeserializer(response.body().asByteBuffer())) |
| 136 | + .build()); |
| 137 | + } catch (Exception e) { |
| 138 | + return CompletableFuture.failedFuture(e); |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + private JsonRpcResponse handleErrorResponse(HttpResponse response) { |
| 143 | + long contentLength = response.body().contentLength(); |
| 144 | + String errorMessage = "HTTP " + response.statusCode(); |
| 145 | + |
| 146 | + if (contentLength > 0) { |
| 147 | + String contentType = response.body().contentType(); |
| 148 | + byte[] bodyBytes = ByteBufferUtils.getBytes(response.body().asByteBuffer()); |
| 149 | + |
| 150 | + if ("application/json".equals(contentType)) { |
| 151 | + try { |
| 152 | + return JsonRpcResponse.builder() |
| 153 | + .deserialize(JSON_CODEC.createDeserializer(bodyBytes)) |
| 154 | + .build(); |
| 155 | + } catch (Exception e) { |
| 156 | + LOG.warn("Failed to deserialize JSON error response", e); |
| 157 | + return JsonRpcResponse.builder() |
| 158 | + .jsonrpc("2.0") |
| 159 | + .error(JsonRpcErrorResponse.builder() |
| 160 | + .code(response.statusCode()) |
| 161 | + .message("HTTP " + response.statusCode() + ": Invalid JSON response") |
| 162 | + .build()) |
| 163 | + .build(); |
| 164 | + } |
| 165 | + } else { |
| 166 | + int length = Math.min(200, bodyBytes.length); |
| 167 | + String errorBody = new String(bodyBytes, 0, length, StandardCharsets.UTF_8); |
| 168 | + errorMessage = errorMessage + ": " + errorBody + (length != bodyBytes.length ? " (truncated)" : ""); |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + return JsonRpcResponse.builder() |
| 173 | + .jsonrpc("2.0") |
| 174 | + .error(JsonRpcErrorResponse.builder() |
| 175 | + .code(response.statusCode()) |
| 176 | + .message(errorMessage) |
| 177 | + .build()) |
| 178 | + .build(); |
| 179 | + } |
| 180 | + |
| 181 | + @Override |
| 182 | + public void start() { |
| 183 | + // HTTP is connectionless, nothing to start |
| 184 | + LOG.debug("HTTP MCP proxy started for endpoint: {}", endpoint); |
| 185 | + } |
| 186 | + |
| 187 | + @Override |
| 188 | + public CompletableFuture<Void> shutdown() { |
| 189 | + // HTTP client doesn't need explicit shutdown |
| 190 | + LOG.debug("HTTP MCP proxy shutdown for endpoint: {}", endpoint); |
| 191 | + return CompletableFuture.completedFuture(null); |
| 192 | + } |
| 193 | + |
| 194 | + @Override |
| 195 | + public String name() { |
| 196 | + return name; |
| 197 | + } |
| 198 | +} |
0 commit comments