atiaomar1978-hub commented on code in PR #25203: URL: https://github.com/apache/camel/pull/25203#discussion_r3722281102
########## 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: Fixed in cc569af443f (also in 6f857dc1902): added LOG.warn when no management HTTP router is found so shared-port fallback is visible in logs. _AI-generated reply on behalf of atiaomar1978-hub_ ########## 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: Fixed in cc569af443f (6f857dc1902): javadoc and main.adoc clarify camel.management.mcpEnabled is only honored when Camel JBang registers JbangDevMcpMainListener (camel run --mcp); route-based MCP uses camel.server.mcpEnabled on HttpServerConfigurationProperties. _AI-generated reply on behalf of atiaomar1978-hub_ ########## 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: Fixed in cc569af443f: switched to resolveMandatoryClass via mandatoryClass() helper for ToolRegistry/ToolContext reflective access. _AI-generated reply on behalf of atiaomar1978-hub_ ########## 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: Kept json-schema-validator test dependency (6f857dc1902 clarifies comment): parent property resolves to 2.0.1 which provides Dialects required by MCP SDK; wiremock transitively pulls 1.5.x without it. Removing it breaks JbangDevMcpServerTest. _AI-generated reply on behalf of atiaomar1978-hub_ ########## 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: Fixed in cc569af443f (6f857dc1902): removed redundant ToolDescriptor builder test; HTTP integration test now asserts inputSchema contains name and required for select_process. _AI-generated reply on behalf of atiaomar1978-hub_ ########## core/camel-main/src/main/java/org/apache/camel/main/HttpManagementServerConfigurationProperties.java: ########## @@ -573,6 +577,41 @@ 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). Currently honored only when Camel JBang registers {@code JbangDevMcpMainListener} (for example + * {@code camel run --mcp}); plain camel-main users should use {@code camel.server.mcpEnabled} for route-based MCP. Review Comment: Addressed in 6f857dc1902: camel.server.mcpEnabled exists on HttpServerConfigurationProperties (see BaseMainSupport.setupMcpServer). Updated javadoc/docs to reference it explicitly instead of implying it is missing. _AI-generated reply on behalf of atiaomar1978-hub_ ########## dsl/camel-jbang/camel-jbang-core/pom.xml: ########## @@ -192,6 +192,35 @@ <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> + <!-- MCP SDK schema validation requires networknt 2.x; wiremock pulls 1.5.x without Dialects --> Review Comment: Clarified in 6f857dc1902: the comment now states 2.0.1 explicitly. ${networknt-json-schema-validator-version} in parent pom.xml is 2.0.1 (not 1.5.9); dependency tree confirms 2.0.1:test on camel-jbang-core. Wiremock brings 1.5.x transitively which lacks Dialects. _AI-generated reply on behalf of atiaomar1978-hub_ -- 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]
