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


##########
core/camel-main/src/main/java/org/apache/camel/main/HttpManagementServerConfigurationProperties.java:
##########
@@ -573,6 +577,39 @@ public HttpManagementServerConfigurationProperties 
withOpenapiUiSpecPath(String
         return this;
     }
 
+    public boolean isMcpEnabled() {
+        return mcpEnabled;
+    }
+
+    /**
+     * Whether to expose dev/diagnostics MCP tools on this management server 
(requires camel-mcp-server on the
+     * classpath). Not intended for production use.
+     */
+    public void setMcpEnabled(boolean mcpEnabled) {

Review Comment:
   This property is documented in `main.adoc` as a general `camel.management.*` 
option, but the only reader is `JbangDevMcpMainListener`, which is registered 
only when `KameletMain` injects it via `mainListenerClasses` for `--mcp`. A 
plain camel-main user who sets `camel.management.mcpEnabled=true` (with 
camel-mcp-server on the classpath) gets no endpoint and no error.
   
   Contrast `camel.server.mcp-enabled`, which camel-main wires via the 
`McpServerFactory` SPI. Either state in the description that this option is 
currently only honored by Camel JBang (`--mcp`), or wire it in camel-main the 
same SPI way so it works (or fails meaningfully) everywhere.



##########
components/camel-ai/camel-mcp-server/src/main/java/org/apache/camel/component/mcp/server/jbang/JbangDevMcpServer.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.jbang;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.CamelContextAware;
+import org.apache.camel.component.ai.tool.AiToolParameterHelper.ParameterDef;
+import org.apache.camel.component.mcp.server.McpServerInfo;
+import org.apache.camel.component.mcp.server.McpServerTool;
+import org.apache.camel.component.mcp.server.McpToolCallHandler;
+import org.apache.camel.component.mcp.server.McpToolCallResult;
+import org.apache.camel.component.mcp.server.vertx.VertxMcpServerEngine;
+import org.apache.camel.component.platform.http.vertx.VertxPlatformHttpRouter;
+import org.apache.camel.support.service.ServiceSupport;
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
+
+/**
+ * Dev/diagnostics MCP server on the management HTTP port, exposing shared 
JBang {@code ToolRegistry} tools through
+ * {@link VertxMcpServerEngine}. JBang classes are resolved reflectively so 
{@code camel-jbang-core} is not required at
+ * compile time.
+ */
+public class JbangDevMcpServer extends ServiceSupport implements 
CamelContextAware {
+
+    private static final String SERVER_NAME = "camel-jbang-dev-tools";
+    private static final String TOOL_REGISTRY = 
"org.apache.camel.dsl.jbang.core.commands.ai.ToolRegistry";
+    private static final String TOOL_CONTEXT = 
"org.apache.camel.dsl.jbang.core.commands.ai.ToolContext";
+
+    private CamelContext camelContext;
+    private String path = "/mcp";
+    private VertxMcpServerEngine engine;
+    private Object toolContext;
+
+    @Override
+    public CamelContext getCamelContext() {
+        return camelContext;
+    }
+
+    @Override
+    public void setCamelContext(CamelContext camelContext) {
+        this.camelContext = camelContext;
+    }
+
+    public String getPath() {
+        return path;
+    }
+
+    public void setPath(String path) {
+        this.path = path;
+    }
+
+    @Override
+    protected void doStart() throws Exception {
+        toolContext = createToolContext();
+
+        engine = new VertxMcpServerEngine();
+        engine.setCamelContext(camelContext);
+        engine.setTargetServerType(resolveTargetServerType());
+        String version = camelContext.getVersion();
+        if (version == null || version.isBlank()) {
+            version = "unknown";
+        }
+        engine.initialize(new McpServerInfo(SERVER_NAME, version, path));
+        engine.start();
+
+        for (Object descriptor : allToolDescriptors()) {
+            engine.toolAdded(toMcpTool(descriptor));
+        }
+    }
+
+    @Override
+    protected void doStop() throws Exception {
+        if (engine != null) {
+            engine.stop();
+            engine = null;
+        }
+        toolContext = null;
+    }
+
+    private McpServerTool toMcpTool(Object descriptor) {
+        String toolName = invokeString(descriptor, "name");
+        McpToolCallHandler handler = arguments -> {
+            try {
+                Object result = executeTool(toolName, 
stringArguments(arguments));
+                return new McpToolCallResult(result != null ? 
result.toString() : "", false);
+            } catch (Exception e) {
+                Throwable failure = e;
+                if (e instanceof InvocationTargetException ite && 
ite.getCause() != null) {
+                    failure = ite.getCause();
+                }
+                String message = failure.getMessage();
+                if (message == null || message.isBlank()) {
+                    message = failure.getClass().getSimpleName();
+                }
+                return new McpToolCallResult(message, true);
+            }
+        };
+        return new McpServerTool() {
+            @Override
+            public String name() {
+                return toolName;
+            }
+
+            @Override
+            public String description() {
+                return invokeString(descriptor, "description");
+            }
+
+            @Override
+            public String inputSchemaJson() {
+                List<?> params = invokeList(descriptor, "params");
+                return params == null || params.isEmpty() ? null : 
buildInputSchemaJson(params);
+            }
+
+            @Override
+            public Map<String, ParameterDef> parameters() {
+                return Map.of();
+            }
+
+            @Override
+            public McpToolCallHandler handler() {
+                return handler;
+            }
+        };
+    }
+
+    private Object createToolContext() throws ReflectiveOperationException {
+        Class<?> contextClass = 
camelContext.getClassResolver().resolveClass(TOOL_CONTEXT);
+        Object context = contextClass.getDeclaredConstructor().newInstance();
+        Method selectProcess = contextClass.getMethod("selectProcess", 
long.class);
+        selectProcess.invoke(context, ProcessHandle.current().pid());
+        return context;
+    }
+
+    @SuppressWarnings("unchecked")
+    private List<Object> allToolDescriptors() throws 
ReflectiveOperationException {
+        Class<?> registry = 
camelContext.getClassResolver().resolveClass(TOOL_REGISTRY);
+        Method allTools = registry.getMethod("allTools");
+        return (List<Object>) allTools.invoke(null);
+    }
+
+    private Object executeTool(String name, Map<String, String> args) throws 
ReflectiveOperationException {
+        Class<?> registry = 
camelContext.getClassResolver().resolveClass(TOOL_REGISTRY);
+        Class<?> contextClass = 
camelContext.getClassResolver().resolveClass(TOOL_CONTEXT);
+        Method execute = registry.getMethod("execute", String.class, 
contextClass, Map.class);
+        return execute.invoke(null, name, toolContext, args);
+    }
+
+    private static String invokeString(Object target, String method) {
+        try {
+            Object value = target.getClass().getMethod(method).invoke(target);
+            return value != null ? value.toString() : null;
+        } catch (ReflectiveOperationException e) {
+            return null;
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    private static List<?> invokeList(Object target, String method) {
+        try {
+            return (List<?>) 
target.getClass().getMethod(method).invoke(target);
+        } catch (ReflectiveOperationException e) {
+            return List.of();
+        }
+    }
+
+    private static String buildInputSchemaJson(List<?> params) {
+        JsonObject schema = new JsonObject();
+        schema.put("type", "object");
+        JsonObject properties = new JsonObject();
+        JsonArray required = new JsonArray();
+        for (Object param : params) {
+            String name = invokeString(param, "name");
+            JsonObject prop = new JsonObject();
+            prop.put("type", invokeString(param, "type"));
+            prop.put("description", invokeString(param, "description"));
+            properties.put(name, prop);
+            if (Boolean.TRUE.equals(invokeBoolean(param, "required"))) {
+                required.add(name);
+            }
+        }
+        schema.put("properties", properties);
+        if (!required.isEmpty()) {
+            schema.put("required", required);
+        }
+        return schema.toJson();
+    }
+
+    private static Boolean invokeBoolean(Object target, String method) {
+        try {
+            return (Boolean) 
target.getClass().getMethod(method).invoke(target);
+        } catch (ReflectiveOperationException e) {
+            return false;
+        }
+    }
+
+    private static Map<String, String> stringArguments(Map<String, Object> 
args) {
+        Map<String, String> out = new LinkedHashMap<>();
+        if (args == null) {
+            return out;
+        }
+        for (Map.Entry<String, Object> entry : args.entrySet()) {
+            if (entry.getValue() != null) {
+                out.put(entry.getKey(), entry.getValue().toString());
+            }
+        }
+        return out;
+    }
+
+    private String resolveTargetServerType() {

Review Comment:
   This fallback makes the shared-port case work, but it silently defeats the 
`127.0.0.1` intent: both `camel.server` and `camel.management` default to port 
8080, and `ManagementHttpServer.doInit` reuses the main 
`VertxPlatformHttpServer` when the ports match. In that case the 
`withHost("127.0.0.1")` set by `KameletMain` is ignored (the reused server was 
built from the main config, host `0.0.0.0`), so `camel run api.yaml --mcp` — 
any app with a platform-http route — serves the ~40 introspection tools on 
`0.0.0.0:8080/mcp`.
   
   The dev console has the same trait, so this may be acceptable for an 
`insecure:dev` flag, but it should not be silent: please log a WARN here when 
no management-typed router is found and the MCP endpoint falls back to the main 
server, and mention the shared-port behavior in the `--mcp` option description.



##########
components/camel-ai/camel-mcp-server/src/main/java/org/apache/camel/component/mcp/server/jbang/JbangDevMcpServer.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.jbang;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.CamelContextAware;
+import org.apache.camel.component.ai.tool.AiToolParameterHelper.ParameterDef;
+import org.apache.camel.component.mcp.server.McpServerInfo;
+import org.apache.camel.component.mcp.server.McpServerTool;
+import org.apache.camel.component.mcp.server.McpToolCallHandler;
+import org.apache.camel.component.mcp.server.McpToolCallResult;
+import org.apache.camel.component.mcp.server.vertx.VertxMcpServerEngine;
+import org.apache.camel.component.platform.http.vertx.VertxPlatformHttpRouter;
+import org.apache.camel.support.service.ServiceSupport;
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
+
+/**
+ * Dev/diagnostics MCP server on the management HTTP port, exposing shared 
JBang {@code ToolRegistry} tools through
+ * {@link VertxMcpServerEngine}. JBang classes are resolved reflectively so 
{@code camel-jbang-core} is not required at
+ * compile time.
+ */
+public class JbangDevMcpServer extends ServiceSupport implements 
CamelContextAware {
+
+    private static final String SERVER_NAME = "camel-jbang-dev-tools";
+    private static final String TOOL_REGISTRY = 
"org.apache.camel.dsl.jbang.core.commands.ai.ToolRegistry";
+    private static final String TOOL_CONTEXT = 
"org.apache.camel.dsl.jbang.core.commands.ai.ToolContext";
+
+    private CamelContext camelContext;
+    private String path = "/mcp";
+    private VertxMcpServerEngine engine;
+    private Object toolContext;
+
+    @Override
+    public CamelContext getCamelContext() {
+        return camelContext;
+    }
+
+    @Override
+    public void setCamelContext(CamelContext camelContext) {
+        this.camelContext = camelContext;
+    }
+
+    public String getPath() {
+        return path;
+    }
+
+    public void setPath(String path) {
+        this.path = path;
+    }
+
+    @Override
+    protected void doStart() throws Exception {
+        toolContext = createToolContext();
+
+        engine = new VertxMcpServerEngine();
+        engine.setCamelContext(camelContext);
+        engine.setTargetServerType(resolveTargetServerType());
+        String version = camelContext.getVersion();
+        if (version == null || version.isBlank()) {
+            version = "unknown";
+        }
+        engine.initialize(new McpServerInfo(SERVER_NAME, version, path));
+        engine.start();
+
+        for (Object descriptor : allToolDescriptors()) {
+            engine.toolAdded(toMcpTool(descriptor));
+        }
+    }
+
+    @Override
+    protected void doStop() throws Exception {
+        if (engine != null) {
+            engine.stop();
+            engine = null;
+        }
+        toolContext = null;
+    }
+
+    private McpServerTool toMcpTool(Object descriptor) {
+        String toolName = invokeString(descriptor, "name");
+        McpToolCallHandler handler = arguments -> {
+            try {
+                Object result = executeTool(toolName, 
stringArguments(arguments));
+                return new McpToolCallResult(result != null ? 
result.toString() : "", false);
+            } catch (Exception e) {
+                Throwable failure = e;
+                if (e instanceof InvocationTargetException ite && 
ite.getCause() != null) {
+                    failure = ite.getCause();
+                }
+                String message = failure.getMessage();
+                if (message == null || message.isBlank()) {
+                    message = failure.getClass().getSimpleName();
+                }
+                return new McpToolCallResult(message, true);
+            }
+        };
+        return new McpServerTool() {
+            @Override
+            public String name() {
+                return toolName;
+            }
+
+            @Override
+            public String description() {
+                return invokeString(descriptor, "description");
+            }
+
+            @Override
+            public String inputSchemaJson() {
+                List<?> params = invokeList(descriptor, "params");
+                return params == null || params.isEmpty() ? null : 
buildInputSchemaJson(params);
+            }
+
+            @Override
+            public Map<String, ParameterDef> parameters() {
+                return Map.of();
+            }
+
+            @Override
+            public McpToolCallHandler handler() {
+                return handler;
+            }
+        };
+    }
+
+    private Object createToolContext() throws ReflectiveOperationException {
+        Class<?> contextClass = 
camelContext.getClassResolver().resolveClass(TOOL_CONTEXT);
+        Object context = contextClass.getDeclaredConstructor().newInstance();
+        Method selectProcess = contextClass.getMethod("selectProcess", 
long.class);
+        selectProcess.invoke(context, ProcessHandle.current().pid());
+        return context;
+    }
+
+    @SuppressWarnings("unchecked")
+    private List<Object> allToolDescriptors() throws 
ReflectiveOperationException {
+        Class<?> registry = 
camelContext.getClassResolver().resolveClass(TOOL_REGISTRY);

Review Comment:
   `ClassResolver.resolveClass` returns `null` when the class is missing, so 
this NPEs on `getMethod` instead of failing with a clear error. 
`resolveMandatoryClass` throws `ClassNotFoundException` naming the class — much 
better startup diagnostics if someone enables `camel.management.mcpEnabled` 
without JBang on the classpath (same in `createToolContext` and `executeTool`).



##########
dsl/camel-jbang/camel-jbang-core/pom.xml:
##########
@@ -192,6 +192,34 @@
             <version>${mockito-version}</version>
             <scope>test</scope>
         </dependency>
+        <dependency>
+            <groupId>org.apache.camel</groupId>
+            <artifactId>camel-platform-http-main</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.camel</groupId>
+            <artifactId>camel-mcp-server</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>io.modelcontextprotocol.sdk</groupId>
+            <artifactId>mcp-core</artifactId>
+            <version>${mcp-java-sdk-version}</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>io.modelcontextprotocol.sdk</groupId>
+            <artifactId>mcp-json-jackson2</artifactId>
+            <version>${mcp-java-sdk-version}</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>com.networknt</groupId>
+            <artifactId>json-schema-validator</artifactId>

Review Comment:
   `json-schema-validator` is not used by either new test (leftover from the 
removed `ToolMcpSchemasTest`?) — can be dropped.



##########
dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/JbangDevMcpServerTest.java:
##########
@@ -0,0 +1,109 @@
+/*
+ * 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.dsl.jbang.core.commands.mcp;
+
+import java.time.Duration;
+import java.util.Map;
+
+import io.modelcontextprotocol.client.McpClient;
+import io.modelcontextprotocol.client.McpSyncClient;
+import 
io.modelcontextprotocol.client.transport.HttpClientStreamableHttpTransport;
+import io.modelcontextprotocol.spec.McpSchema;
+import org.apache.camel.CamelContext;
+import org.apache.camel.component.mcp.server.jbang.JbangDevMcpServer;
+import org.apache.camel.component.platform.http.main.MainHttpServer;
+import org.apache.camel.component.platform.http.main.ManagementHttpServer;
+import org.apache.camel.dsl.jbang.core.commands.ai.ToolDescriptor;
+import org.apache.camel.dsl.jbang.core.commands.ai.ToolRegistry;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.test.AvailablePortFinder;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+class JbangDevMcpServerTest {
+
+    @Test
+    void exposesToolRegistryOnManagementServer() throws Exception {
+        int mainPort = AvailablePortFinder.getNextAvailable();
+        int managementPort = AvailablePortFinder.getNextAvailable();
+
+        CamelContext camelContext = new DefaultCamelContext();
+        JbangDevMcpServer devMcp = new JbangDevMcpServer();
+        McpSyncClient client = null;
+        try {
+            MainHttpServer main = new MainHttpServer();
+            main.setCamelContext(camelContext);
+            main.setHost("127.0.0.1");
+            main.setPort(mainPort);
+            camelContext.addService(main);
+
+            ManagementHttpServer management = new ManagementHttpServer();
+            management.setCamelContext(camelContext);
+            management.setHost("127.0.0.1");
+            management.setPort(managementPort);
+            management.setPath("/");
+            camelContext.addService(management);
+
+            devMcp.setCamelContext(camelContext);
+            devMcp.setPath("/mcp");
+            camelContext.addService(devMcp);
+
+            camelContext.start();
+
+            client = McpClient.sync(
+                    
HttpClientStreamableHttpTransport.builder("http://127.0.0.1:"; + 
managementPort).build())
+                    .requestTimeout(Duration.ofSeconds(10))
+                    .initializationTimeout(Duration.ofSeconds(10))
+                    .build();
+            McpSchema.InitializeResult init = client.initialize();
+            
assertThat(init.serverInfo().name()).isEqualTo("camel-jbang-dev-tools");
+
+            assertThat(client.listTools().tools())
+                    .extracting(McpSchema.Tool::name)
+                    .contains(ToolRegistry.allTools().get(0).name());
+
+            McpSchema.Tool parameterizedTool = 
client.listTools().tools().stream()
+                    .filter(t -> "select_process".equals(t.name()))
+                    .findFirst()
+                    .orElseThrow();
+            assertThat(parameterizedTool.inputSchema()).isNotNull();
+            
assertThat(parameterizedTool.inputSchema().toString()).contains("name");
+
+            McpSchema.CallToolResult result = client.callTool(
+                    new McpSchema.CallToolRequest("list_processes", Map.of()));
+            assertThat(result.isError()).isNotEqualTo(Boolean.TRUE);
+            assertThat(result.content().toString()).contains("processes");
+        } finally {
+            if (client != null) {
+                client.closeGracefully();
+            }
+            camelContext.stop();
+        }
+    }
+
+    @Test
+    void buildsInputSchemaForParameterizedTools() {

Review Comment:
   Nit: this test exercises the `ToolDescriptor` builder (which lives 
elsewhere), not the schema JSON built in `JbangDevMcpServer`. Now that the HTTP 
test asserts `inputSchema` via `listTools`, consider strengthening that 
assertion instead (e.g. also check it contains `"required"` for the mandatory 
param) and dropping or renaming this one.



-- 
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