Croway commented on code in PR #30343:
URL: https://github.com/apache/camel/pull/30343#discussion_r4615425568


##########
components/camel-ai/camel-mcp-server/src/main/java/org/apache/camel/component/mcp/server/vertx/VertxMcpStreamableServerTransportProvider.java:
##########
@@ -499,9 +532,142 @@ private void handlePost(RoutingContext ctx, Context 
connection) throws Exception
             badRequestErrors.add("application/json required in Accept header");
         }
 
+        String body = ctx.body().asString();
+        if (!sessionsEnabled || protocolEra != McpProtocolEra.LEGACY) {
+            routePost(ctx, connection, body, badRequestErrors);
+            return;
+        }
+        handleSessionPost(ctx, connection, body, badRequestErrors);
+    }
+
+    /**
+     * Serves a POST when the endpoint does more than the legacy protocol 
versions with sessions: protocol version
+     * 2026-07-28, or the legacy versions without sessions. The body decides 
which protocol version a request belongs to
+     * (see {@link McpProtocolEraClassifier}).
+     */
+    private void routePost(RoutingContext ctx, Context connection, String 
body, List<String> badRequestErrors)
+            throws Exception {
+        if (protocolEra == McpProtocolEra.MODERN) {
+            if (respondBadRequest(connection, ctx, badRequestErrors)) {
+                return;
+            }
+            // a legacy initialize is answered by the modern server with the 
versions it supports
+            modernTransport.handle(body, new VertxHeaderAccessor(ctx), 
toTransportContext(ctx), ctx.response(),
+                    connection);
+            return;
+        }
+        Object tree;
+        try {
+            tree = jsonMapper.readValue(body, Object.class);
+        } catch (Exception e) {
+            LOG.debug("Invalid MCP message: {}", e.getMessage());
+            respondError(connection, ctx, 400, 
McpSchema.ErrorCodes.PARSE_ERROR, "Invalid message format");
+            return;
+        }
+        McpProtocolEraClassifier.Verdict verdict
+                = 
McpProtocolEraClassifier.classify(ctx.request().getHeader(PROTOCOL_VERSION), 
tree);
+        if (verdict.rejected()) {
+            respondError(connection, ctx, 400, 
McpProtocolEraClassifier.HEADER_MISMATCH, verdict.message());
+            return;
+        }
+        if (verdict.era() == McpProtocolEraClassifier.Era.MODERN) {
+            if (modernTransport == null) {
+                // the legacy era without sessions: never serve a 2026-07-28 
request as a legacy one
+                respondUnsupportedVersion(connection, ctx, tree);

Review Comment:
   This one is intended. On the MCP Streamable HTTP transport, a POSTed 
notification the server cannot accept is answered with an HTTP error status, 
and the body may be a JSON-RPC error without an id: "If the server cannot 
accept the input, it MUST return an HTTP error status code (e.g., 400 Bad 
Request). The HTTP response body MAY comprise a JSON-RPC error response that 
has no `id`" (same wording from 2025-03-26 to 2026-07-28). A 202 would tell the 
client the notification was accepted.
   
   This path is only reached with `mcp-protocol-era=legacy` and 
`mcp-stateless=true`, where 2026-07-28 is not served; with the default `dual`, 
such a notification goes to the 2026-07-28 transport and gets 202. Both cases 
are now asserted in `VertxMcpProtocolEraTest` (d1216f1), which also changes the 
error of this path to `-32600` (see the reply to davsclaus).
   
   _Claude Code on behalf of Croway_



##########
components/camel-ai/camel-mcp-server/src/main/java/org/apache/camel/component/mcp/server/vertx/VertxMcpStreamableServerTransportProvider.java:
##########
@@ -499,9 +532,142 @@ private void handlePost(RoutingContext ctx, Context 
connection) throws Exception
             badRequestErrors.add("application/json required in Accept header");
         }
 
+        String body = ctx.body().asString();
+        if (!sessionsEnabled || protocolEra != McpProtocolEra.LEGACY) {
+            routePost(ctx, connection, body, badRequestErrors);
+            return;
+        }
+        handleSessionPost(ctx, connection, body, badRequestErrors);
+    }
+
+    /**
+     * Serves a POST when the endpoint does more than the legacy protocol 
versions with sessions: protocol version
+     * 2026-07-28, or the legacy versions without sessions. The body decides 
which protocol version a request belongs to
+     * (see {@link McpProtocolEraClassifier}).
+     */
+    private void routePost(RoutingContext ctx, Context connection, String 
body, List<String> badRequestErrors)
+            throws Exception {
+        if (protocolEra == McpProtocolEra.MODERN) {
+            if (respondBadRequest(connection, ctx, badRequestErrors)) {
+                return;
+            }
+            // a legacy initialize is answered by the modern server with the 
versions it supports
+            modernTransport.handle(body, new VertxHeaderAccessor(ctx), 
toTransportContext(ctx), ctx.response(),
+                    connection);
+            return;
+        }
+        Object tree;
+        try {
+            tree = jsonMapper.readValue(body, Object.class);
+        } catch (Exception e) {
+            LOG.debug("Invalid MCP message: {}", e.getMessage());
+            respondError(connection, ctx, 400, 
McpSchema.ErrorCodes.PARSE_ERROR, "Invalid message format");
+            return;
+        }
+        McpProtocolEraClassifier.Verdict verdict
+                = 
McpProtocolEraClassifier.classify(ctx.request().getHeader(PROTOCOL_VERSION), 
tree);
+        if (verdict.rejected()) {
+            respondError(connection, ctx, 400, 
McpProtocolEraClassifier.HEADER_MISMATCH, verdict.message());
+            return;
+        }
+        if (verdict.era() == McpProtocolEraClassifier.Era.MODERN) {
+            if (modernTransport == null) {
+                // the legacy era without sessions: never serve a 2026-07-28 
request as a legacy one
+                respondUnsupportedVersion(connection, ctx, tree);
+                return;
+            }
+            if (respondBadRequest(connection, ctx, badRequestErrors)) {
+                return;
+            }
+            modernTransport.handle(body, new VertxHeaderAccessor(ctx), 
toTransportContext(ctx), ctx.response(),
+                    connection);
+            return;
+        }
+        if (sessionsEnabled) {
+            // exactly as with the legacy era, including which messages need 
the Accept header
+            handleSessionPost(ctx, connection, body, badRequestErrors);
+            return;
+        }
+        if (respondBadRequest(connection, ctx, badRequestErrors)) {
+            return;
+        }
+        handleStatelessPost(ctx, connection, body);
+    }
+
+    /**
+     * Serves a client of a legacy protocol version without a session.
+     */
+    private void handleStatelessPost(RoutingContext ctx, Context connection, 
String body) throws Exception {
+        McpSchema.JSONRPCMessage message;
+        try {
+            message = McpSchema.deserializeJsonRpcMessage(jsonMapper, body);
+        } catch (Exception e) {
+            LOG.debug("Invalid MCP message: {}", e.getMessage());
+            respondError(connection, ctx, 400, 
McpSchema.ErrorCodes.PARSE_ERROR, "Invalid message format");
+            return;
+        }
+        VertxMcpStatelessServerTransport.Answer answer = 
statelessTransport.handle(toTransportContext(ctx), message);
+        if (answer == null) {
+            respondError(connection, ctx, 400, 
McpSchema.ErrorCodes.INVALID_REQUEST,
+                    "The server accepts either requests or notifications");
+        } else if (answer.body() == null) {
+            endWithStatus(connection, ctx, answer.status());
+        } else {
+            connection.runOnContext(v -> ctx.response()
+                    .setStatusCode(answer.status())
+                    .putHeader("Content-Type", APPLICATION_JSON)
+                    .end(answer.body()));
+        }
+    }
+
+    /**
+     * Answers a request of a protocol version this endpoint does not serve 
(2026-07-28 or an unknown one, on an
+     * endpoint that serves only the legacy versions without sessions) with 
HTTP 400 and an UnsupportedProtocolVersion
+     * error naming the versions it supports, so a client that also speaks a 
legacy version falls back to
+     * {@code initialize}.
+     */
+    private void respondUnsupportedVersion(Context connection, RoutingContext 
ctx, Object tree) {
+        Object id = tree instanceof Map<?, ?> message ? message.get("id") : 
null;
+        String requested = ctx.request().getHeader(PROTOCOL_VERSION);
+        if (tree instanceof Map<?, ?> message && message.get("params") 
instanceof Map<?, ?> params
+                && params.get("_meta") instanceof Map<?, ?> meta
+                && 
meta.get(McpProtocolEraClassifier.PROTOCOL_VERSION_META_KEY) instanceof String 
version) {
+            requested = version;
+        }
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("supported", McpProtocolEraClassifier.LEGACY_VERSIONS);
+        data.put("requested", requested);
+        Map<String, Object> error = new LinkedHashMap<>();
+        error.put("code", 
McpProtocolEraClassifier.UNSUPPORTED_PROTOCOL_VERSION);
+        error.put("message", "Unsupported protocol version");
+        error.put("data", data);
+        Map<String, Object> response = new LinkedHashMap<>();
+        response.put("jsonrpc", McpSchema.JSONRPC_VERSION);
+        if (id != null) {

Review Comment:
   Same transport rule: the error response for input the server cannot accept 
"has no `id`". Since d1216f1 this path uses the shared `errorBody`, like the 
endpoint's other rejections before dispatch (Origin, Host, Content-Type, 
missing session), so none of them carries an id.
   
   _Claude Code on behalf of Croway_



##########
components/camel-ai/camel-mcp-server/src/main/java/org/apache/camel/component/mcp/server/vertx/VertxMcpModernTransport.java:
##########
@@ -0,0 +1,422 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.mcp.server.vertx;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+
+import io.modelcontextprotocol.common.McpTransportContext;
+import io.modelcontextprotocol.json.McpJsonMapper;
+import io.modelcontextprotocol.modern.JsonRpc;
+import io.modelcontextprotocol.modern.JsonRpc.JSONRPCMessage;
+import io.modelcontextprotocol.modern.JsonRpc.JSONRPCNotification;
+import io.modelcontextprotocol.modern.JsonRpc.JSONRPCRequest;
+import io.modelcontextprotocol.modern.JsonRpc.JSONRPCResponse;
+import io.modelcontextprotocol.modern.JsonRpc.JSONRPCResponse.JSONRPCError;
+import io.modelcontextprotocol.modern.McpHttp;
+import io.modelcontextprotocol.modern.McpSchema;
+import io.modelcontextprotocol.modern.McpSchema.ErrorCodes;
+import io.modelcontextprotocol.modern.server.McpHeaders;
+import io.modelcontextprotocol.modern.server.McpRequestContext;
+import io.modelcontextprotocol.modern.server.McpRequestManager;
+import io.modelcontextprotocol.modern.server.McpServer;
+import io.modelcontextprotocol.modern.server.McpTransportResponse;
+import io.modelcontextprotocol.modern.server.RequestStateCodec;
+import io.modelcontextprotocol.modern.server.feature.McpChangeFeed;
+import io.modelcontextprotocol.modern.server.feature.PromptsFeature;
+import io.modelcontextprotocol.modern.server.feature.ResourcesFeature;
+import io.modelcontextprotocol.modern.server.feature.ToolsFeature;
+import io.modelcontextprotocol.modern.server.transport.McpHeaderDecoder;
+import io.modelcontextprotocol.server.transport.HeaderAccessor;
+import io.vertx.core.Context;
+import io.vertx.core.http.HttpServerResponse;
+import org.apache.camel.component.mcp.server.McpServerIcon;
+import org.apache.camel.component.mcp.server.McpServerInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import reactor.core.Disposable;
+import reactor.core.Disposables;
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+import reactor.core.scheduler.Schedulers;
+
+/**
+ * Serves requests of MCP protocol version 2026-07-28 and later: stateless, 
one self-contained request per POST,
+ * answered with a single JSON object or a Server-Sent Events stream scoped to 
that request.
+ * <p>
+ * This is the Vert.x counterpart of the POST handling of the MCP SDK's {@code 
HttpServletMcpTransport}; the HTTP
+ * concerns shared with the other protocol versions (routes, origin, host and 
OAuth checks) stay in
+ * {@link VertxMcpStreamableServerTransportProvider}, which calls {@link 
#handle} on a worker thread. A request's
+ * {@code Mcp-Method}, {@code MCP-Protocol-Version} and {@code Mcp-Name} 
headers are checked against its body before it
+ * reaches the {@link McpRequestManager}; a mismatch is answered with HTTP 400 
and error {@code -32020}. A
+ * {@code subscriptions/listen} stream does not hold a worker thread, and a 
stream that the client closes is cancelled.
+ */
+final class VertxMcpModernTransport {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(VertxMcpModernTransport.class);
+
+    static final Duration DEFAULT_KEEP_ALIVE_INTERVAL = Duration.ofSeconds(30);
+
+    private static final String APPLICATION_JSON = "application/json";
+    private static final String TEXT_EVENT_STREAM = "text/event-stream";
+    private static final String KEEP_ALIVE_FRAME = ":\n\n";
+    // the handshake of the protocol versions before 2026-07-28 (the SDK 
constant is deprecated)
+    private static final String METHOD_INITIALIZE = "initialize";
+
+    /**
+     * The HTTP status of each JSON-RPC error code, as the MCP SDK's servlet 
transport answers them; any other code is
+     * answered with HTTP 200.
+     */
+    private static final Map<Integer, Integer> ERROR_STATUSES = Map.of(
+            ErrorCodes.PARSE_ERROR, 400,
+            ErrorCodes.INVALID_REQUEST, 400,
+            ErrorCodes.INVALID_PARAMS, 400,
+            ErrorCodes.HEADER_MISMATCH, 400,
+            ErrorCodes.MISSING_REQUIRED_CLIENT_CAPABILITY, 400,
+            ErrorCodes.UNSUPPORTED_PROTOCOL_VERSION, 400,
+            ErrorCodes.METHOD_NOT_FOUND, 404);
+
+    /**
+     * Camel tools, resources and prompts never answer with an {@code 
InputRequiredResult}, so no request state is ever
+     * sealed, and a request state sent by a client cannot have come from this 
server. This also spares the
+     * multi-instance warning of the SDK's default codec, whose per-process 
key Camel would never use.
+     */
+    private static final RequestStateCodec NO_REQUEST_STATE = new 
RequestStateCodec() {
+        @Override
+        public String seal(McpRequestContext ctx, String state) {
+            throw new IllegalStateException("Camel MCP server never asks the 
client for input");
+        }
+
+        @Override
+        public String open(McpRequestContext ctx, String sealed) {
+            return null;
+        }
+    };
+
+    private final McpRequestManager requestManager;
+    private final McpJsonMapper jsonMapper;
+    private final Duration keepAliveInterval;
+
+    VertxMcpModernTransport(McpRequestManager requestManager, McpJsonMapper 
jsonMapper, Duration keepAliveInterval) {
+        this.requestManager = requestManager;
+        this.jsonMapper = jsonMapper;
+        this.keepAliveInterval = keepAliveInterval;
+    }
+
+    /**
+     * Builds the transport over an MCP SDK modern server that serves the 
tools, resources and prompts of the catalog
+     * and tells listening clients when a list changes.
+     */
+    static VertxMcpModernTransport create(
+            McpServerInfo info, McpModernCatalog catalog, McpChangeFeed 
changes, McpJsonMapper jsonMapper,
+            Duration keepAliveInterval) {
+        McpServer.Builder builder = McpServer.builder()
+                .serverInfo(buildServerInfo(info))
+                .jsonMapper(jsonMapper)
+                .feature(ToolsFeature.ofSync(catalog.toolRepository()))
+                .feature(ResourcesFeature.ofSync(catalog.resourceRepository()))
+                .feature(PromptsFeature.ofSync(catalog.promptRepository()))
+                .subscriptions(changes)
+                .requestStateCodec(NO_REQUEST_STATE);
+        if (info.instructions() != null && !info.instructions().isBlank()) {
+            builder.instructions(info.instructions());
+        }
+        return new VertxMcpModernTransport(builder.build(), jsonMapper, 
keepAliveInterval);
+    }
+
+    private static McpSchema.Implementation buildServerInfo(McpServerInfo 
info) {
+        McpSchema.Implementation.Builder builder = 
McpSchema.Implementation.builder(info.serverName(), info.version());
+        if (info.title() != null && !info.title().isBlank()) {
+            builder.title(info.title());
+        }
+        if (info.description() != null && !info.description().isBlank()) {
+            builder.description(info.description());
+        }
+        if (info.websiteUrl() != null && !info.websiteUrl().isBlank()) {
+            builder.websiteUrl(info.websiteUrl());
+        }
+        if (info.icons() != null && !info.icons().isEmpty()) {
+            
builder.icons(info.icons().stream().map(VertxMcpModernTransport::buildIcon).toList());
+        }
+        return builder.build();
+    }
+
+    private static McpSchema.Icon buildIcon(McpServerIcon icon) {
+        McpSchema.Icon.Builder builder = McpSchema.Icon.builder(icon.src());
+        if (icon.mimeType() != null && !icon.mimeType().isBlank()) {
+            builder.mimeType(icon.mimeType());
+        }
+        if (icon.sizes() != null && !icon.sizes().isEmpty()) {
+            builder.sizes(icon.sizes());
+        }
+        if (icon.theme() != null && !icon.theme().isBlank()) {
+            builder.theme(icon.theme());
+        }
+        return builder.build();
+    }
+
+    /**
+     * Ends the {@code subscriptions/listen} streams.
+     */
+    void closeGracefully() {
+        if (requestManager instanceof McpServer server) {
+            server.closeGracefully();
+        }
+    }
+
+    /**
+     * Handles one POST on the calling (worker) thread; every write goes 
through the connection's event-loop context.
+     *
+     * @param body             the request body
+     * @param headers          the request headers
+     * @param transportContext the caller identity of the request
+     * @param response         the HTTP response
+     * @param connection       the event-loop context of the connection
+     */
+    void handle(
+            String body, HeaderAccessor headers, McpTransportContext 
transportContext,
+            HttpServerResponse response, Context connection) {
+        JSONRPCMessage message;
+        try {
+            message = JsonRpc.deserializeMessage(jsonMapper, body);

Review Comment:
   Deliberate: the body is parsed once into plain JSON values to decide the 
protocol version, then each side uses the SDK's own deserializer 
(`JsonRpc.deserializeMessage` for 2026-07-28, 
`McpSchema.deserializeJsonRpcMessage` for the older versions), so validation 
and error answers stay those of the SDK's own transports. The extra parse only 
happens in `dual`/stateless mode, on small JSON-RPC bodies; as davsclaus notes, 
it fits a follow-up if it ever shows up in a profile.
   
   _Claude Code on behalf of Croway_



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to