This is an automated email from the ASF dual-hosted git repository.

Croway pushed a commit to branch camel-4.22.x
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/camel-4.22.x by this push:
     new 860bceb444d5 CAMEL-25000: camel-ai-tool - register during route 
warm-up so early requests see every tool
860bceb444d5 is described below

commit 860bceb444d534cb7fb742ed6c585e4de6c53b8e
Author: croway <[email protected]>
AuthorDate: Thu Sep 24 15:12:57 2026 +0200

    CAMEL-25000: camel-ai-tool - register during route warm-up so early 
requests see every tool
    
    ai-tool routes registered only when their consumer started. A route declared
    earlier whose consumer produces immediately (e.g. stream:in) called the LLM
    before later tool routes were registered, silently sending a partial or 
empty
    tool list; mcp-server published partial lists the same way.
    
    The endpoint now registers during route warm-up, which Camel completes for 
all
    routes before starting any route consumer, for routes that start 
automatically.
    The auto-startup check is extracted from RouteService into
    CamelContextHelper.isAutoStartup(Route) so both share one implementation.
    
    Backport of apache/camel#26856 (camel-ai-resource does not exist on 4.22.x).
    
    Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
---
 .../camel/component/ai/tool/AiToolConsumer.java    | 31 ++++++-
 .../camel/component/ai/tool/AiToolEndpoint.java    | 20 +++++
 .../component/ai/tool/AiToolStartupOrderTest.java  | 99 ++++++++++++++++++++++
 .../server/McpServerBridgeStartupOrderTest.java    | 94 ++++++++++++++++++++
 .../org/apache/camel/impl/engine/RouteService.java | 18 +---
 .../support/CamelContextHelperAutoStartupTest.java | 56 ++++++++++++
 .../apache/camel/support/CamelContextHelper.java   | 22 +++++
 design/aiTool.adoc                                 |  7 +-
 8 files changed, 328 insertions(+), 19 deletions(-)

diff --git 
a/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolConsumer.java
 
b/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolConsumer.java
index 1f9c587bb7f4..446cd9918931 100644
--- 
a/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolConsumer.java
+++ 
b/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolConsumer.java
@@ -19,6 +19,7 @@ package org.apache.camel.component.ai.tool;
 import java.util.Map;
 
 import org.apache.camel.Processor;
+import org.apache.camel.support.CamelContextHelper;
 import org.apache.camel.support.DefaultConsumer;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -47,7 +48,35 @@ public class AiToolConsumer extends DefaultConsumer {
     @Override
     protected void doStart() throws Exception {
         super.doStart();
+        if (registeredSpec == null) {
+            prepare();
+        }
+        register();
+    }
+
+    /**
+     * Registers during route warm-up, which Camel completes for all routes 
before it starts any route consumer, so a
+     * route that sends a request as soon as its consumer starts (such as 
{@code stream:in}) sees every tool. Routes
+     * that are not started automatically are registered when their consumer 
starts.
+     */
+    void registerEarly() throws Exception {
+        if (registeredSpec == null && getRoute() != null && 
CamelContextHelper.isAutoStartup(getRoute())) {
+            prepare();
+            register();
+        }
+    }
 
+    /**
+     * Removes an early registration whose consumer never started, e.g. when 
another route failed to start.
+     */
+    void deregisterEarly() {
+        if (registeredSpec != null && !isStarted()) {
+            deregister();
+            registeredSpec = null;
+        }
+    }
+
+    private void prepare() throws Exception {
         Map<String, String> params = configuration.getParameters();
         String argSchema = configuration.getArgSchema();
         AiToolParameterHelper.validateParameterSourceExclusive(params, 
argSchema);
@@ -82,8 +111,6 @@ public class AiToolConsumer extends DefaultConsumer {
             registeredTags = null;
             registeredInDefaultPool = true;
         }
-
-        register();
     }
 
     @Override
diff --git 
a/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolEndpoint.java
 
b/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolEndpoint.java
index 58eca91e719b..13959fa36d63 100644
--- 
a/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolEndpoint.java
+++ 
b/components/camel-ai/camel-ai-tool/src/main/java/org/apache/camel/component/ai/tool/AiToolEndpoint.java
@@ -51,6 +51,8 @@ public class AiToolEndpoint extends DefaultEndpoint {
     @UriParam(description = "Tool configuration including tags, description, 
and parameter definitions.")
     private AiToolConfiguration configuration;
 
+    private volatile AiToolConsumer consumer;
+
     public AiToolEndpoint(String uri, AiToolComponent component, String 
toolName,
                           AiToolConfiguration configuration) {
         super(uri, component);
@@ -70,6 +72,7 @@ public class AiToolEndpoint extends DefaultEndpoint {
     public Consumer createConsumer(Processor processor) throws Exception {
         AiToolConsumer consumer = new AiToolConsumer(this, processor);
         configureConsumer(consumer);
+        this.consumer = consumer;
         return consumer;
     }
 
@@ -84,4 +87,21 @@ public class AiToolEndpoint extends DefaultEndpoint {
     public void setConfiguration(AiToolConfiguration configuration) {
         this.configuration = configuration;
     }
+
+    @Override
+    protected void doStart() throws Exception {
+        super.doStart();
+        // the endpoint is started during route warm-up, before any route 
consumer is started
+        if (consumer != null) {
+            consumer.registerEarly();
+        }
+    }
+
+    @Override
+    protected void doStop() throws Exception {
+        if (consumer != null) {
+            consumer.deregisterEarly();
+        }
+        super.doStop();
+    }
 }
diff --git 
a/components/camel-ai/camel-ai-tool/src/test/java/org/apache/camel/component/ai/tool/AiToolStartupOrderTest.java
 
b/components/camel-ai/camel-ai-tool/src/test/java/org/apache/camel/component/ai/tool/AiToolStartupOrderTest.java
new file mode 100644
index 000000000000..ca4682e77501
--- /dev/null
+++ 
b/components/camel-ai/camel-ai-tool/src/test/java/org/apache/camel/component/ai/tool/AiToolStartupOrderTest.java
@@ -0,0 +1,99 @@
+/*
+ * 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.ai.tool;
+
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Consumer;
+import org.apache.camel.Processor;
+import org.apache.camel.Producer;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.support.DefaultConsumer;
+import org.apache.camel.support.DefaultEndpoint;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Tools must be registered before any route consumer starts, so a route 
declared before the ai-tool routes (such as
+ * {@code stream:in}) that sends a request immediately on start sees all of 
them.
+ */
+class AiToolStartupOrderTest extends CamelTestSupport {
+
+    private final List<String> seenByFirstConsumer = new 
CopyOnWriteArrayList<>();
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            public void configure() {
+                // declared first: its consumer starts before the ai-tool 
consumers
+                from(new 
ProbeEndpoint(getContext())).routeId("probe").log("probe");
+
+                from("ai-tool:no_params?tags=devops&description=No parameters")
+                        .setBody(constant("ok"));
+
+                from("ai-tool:with_params?tags=devops&description=With 
parameters"
+                     + 
"&parameter.service=string&parameter.service.description=The service")
+                        .setBody(constant("ok"));
+
+                from("ai-tool:not_started?tags=devops&description=Route not 
auto started")
+                        .autoStartup(false)
+                        .setBody(constant("ok"));
+            }
+        };
+    }
+
+    @Test
+    void toolsAreRegisteredBeforeTheFirstRouteConsumerStarts() {
+        assertThat(seenByFirstConsumer).containsExactlyInAnyOrder("no_params", 
"with_params");
+    }
+
+    @Test
+    void toolOfRouteNotAutoStartedIsNotRegistered() {
+        assertThat(AiToolRegistry.getOrCreate(context).getToolsByTag("devops"))
+                .extracting(AiToolSpec::getName)
+                .containsExactlyInAnyOrder("no_params", "with_params");
+    }
+
+    private final class ProbeEndpoint extends DefaultEndpoint {
+
+        ProbeEndpoint(CamelContext camelContext) {
+            super("probe://first", null);
+            setCamelContext(camelContext);
+        }
+
+        @Override
+        public Producer createProducer() {
+            throw new UnsupportedOperationException();
+        }
+
+        @Override
+        public Consumer createConsumer(Processor processor) {
+            return new DefaultConsumer(this, processor) {
+                @Override
+                protected void doStart() throws Exception {
+                    super.doStart();
+                    
AiToolRegistry.getOrCreate(getCamelContext()).getToolsByTag("devops")
+                            .forEach(spec -> 
seenByFirstConsumer.add(spec.getName()));
+                }
+            };
+        }
+    }
+}
diff --git 
a/components/camel-ai/camel-mcp-server-api/src/test/java/org/apache/camel/component/mcp/server/McpServerBridgeStartupOrderTest.java
 
b/components/camel-ai/camel-mcp-server-api/src/test/java/org/apache/camel/component/mcp/server/McpServerBridgeStartupOrderTest.java
new file mode 100644
index 000000000000..752e7738dd66
--- /dev/null
+++ 
b/components/camel-ai/camel-mcp-server-api/src/test/java/org/apache/camel/component/mcp/server/McpServerBridgeStartupOrderTest.java
@@ -0,0 +1,94 @@
+/*
+ * 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;
+
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Consumer;
+import org.apache.camel.Processor;
+import org.apache.camel.Producer;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.support.DefaultConsumer;
+import org.apache.camel.support.DefaultEndpoint;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * The MCP engine accepts clients before the routes start, so all tools must 
be published before any route consumer
+ * starts, otherwise an early {@code tools/list} returns a partial list.
+ */
+class McpServerBridgeStartupOrderTest extends CamelTestSupport {
+
+    private final RecordingMcpServerEngine engine = new 
RecordingMcpServerEngine();
+    private final List<String> seenByFirstConsumer = new 
CopyOnWriteArrayList<>();
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        CamelContext camelContext = super.createCamelContext();
+        camelContext.getRegistry().bind("mcpServerEngine", engine);
+        McpServerConfiguration configuration = new McpServerConfiguration();
+        configuration.setTags("crm");
+        camelContext.addService(new McpServerBridge(configuration));
+        return camelContext;
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            public void configure() {
+                // declared first: its consumer starts before the ai-tool 
consumers
+                from(new 
ProbeEndpoint(getContext())).routeId("probe").log("probe");
+
+                from("ai-tool:query_db?tags=crm&description=Query the 
database&parameter.id=string")
+                        .setBody(constant("ok"));
+            }
+        };
+    }
+
+    @Test
+    void toolsArePublishedBeforeTheFirstRouteConsumerStarts() {
+        assertThat(seenByFirstConsumer).containsExactly("query_db");
+    }
+
+    private final class ProbeEndpoint extends DefaultEndpoint {
+
+        ProbeEndpoint(CamelContext camelContext) {
+            super("probe://first", null);
+            setCamelContext(camelContext);
+        }
+
+        @Override
+        public Producer createProducer() {
+            throw new UnsupportedOperationException();
+        }
+
+        @Override
+        public Consumer createConsumer(Processor processor) {
+            return new DefaultConsumer(this, processor) {
+                @Override
+                protected void doStart() throws Exception {
+                    super.doStart();
+                    seenByFirstConsumer.addAll(engine.tools().keySet());
+                }
+            };
+        }
+    }
+}
diff --git 
a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/RouteService.java
 
b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/RouteService.java
index dfc11a66b058..02e8933fb2a0 100644
--- 
a/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/RouteService.java
+++ 
b/core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/RouteService.java
@@ -45,9 +45,9 @@ import org.apache.camel.spi.LifecycleStrategy;
 import org.apache.camel.spi.RouteIdAware;
 import org.apache.camel.spi.RoutePolicy;
 import org.apache.camel.spi.StartupStepRecorder;
+import org.apache.camel.support.CamelContextHelper;
 import org.apache.camel.support.ChildServiceSupport;
 import org.apache.camel.support.EventHelper;
-import org.apache.camel.support.PatternHelper;
 import org.apache.camel.support.service.ServiceHelper;
 import org.slf4j.MDC;
 
@@ -163,21 +163,7 @@ public class RouteService extends ChildServiceSupport {
     }
 
     public boolean isAutoStartup() {
-        if (!getCamelContext().isAutoStartup()) {
-            return false;
-        }
-        if (!getRoute().isAutoStartup()) {
-            return false;
-        }
-        if (getCamelContext().getAutoStartupExcludePattern() != null) {
-            String[] patterns = 
getCamelContext().getAutoStartupExcludePattern().split(",");
-            String id = getRoute().getRouteId();
-            String url = getRoute().getEndpoint().getEndpointUri();
-            if (PatternHelper.matchPatterns(id, patterns) || 
PatternHelper.matchPatterns(url, patterns)) {
-                return false;
-            }
-        }
-        return true;
+        return CamelContextHelper.isAutoStartup(getRoute());
     }
 
     protected void doSetup() throws Exception {
diff --git 
a/core/camel-core/src/test/java/org/apache/camel/support/CamelContextHelperAutoStartupTest.java
 
b/core/camel-core/src/test/java/org/apache/camel/support/CamelContextHelperAutoStartupTest.java
new file mode 100644
index 000000000000..4af640d6a282
--- /dev/null
+++ 
b/core/camel-core/src/test/java/org/apache/camel/support/CamelContextHelperAutoStartupTest.java
@@ -0,0 +1,56 @@
+/*
+ * 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.support;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.builder.RouteBuilder;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class CamelContextHelperAutoStartupTest extends ContextTestSupport {
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        CamelContext camelContext = super.createCamelContext();
+        
camelContext.setAutoStartupExcludePattern("excludedById,direct://excludedByUri");
+        return camelContext;
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:auto").routeId("auto").to("mock:result");
+                
from("direct:manual").routeId("manual").autoStartup(false).to("mock:result");
+                from("direct:byId").routeId("excludedById").to("mock:result");
+                
from("direct:excludedByUri").routeId("byUri").to("mock:result");
+            }
+        };
+    }
+
+    @Test
+    public void testIsAutoStartup() {
+        assertTrue(CamelContextHelper.isAutoStartup(context.getRoute("auto")));
+        
assertFalse(CamelContextHelper.isAutoStartup(context.getRoute("manual")));
+        
assertFalse(CamelContextHelper.isAutoStartup(context.getRoute("excludedById")));
+        
assertFalse(CamelContextHelper.isAutoStartup(context.getRoute("byUri")));
+    }
+}
diff --git 
a/core/camel-support/src/main/java/org/apache/camel/support/CamelContextHelper.java
 
b/core/camel-support/src/main/java/org/apache/camel/support/CamelContextHelper.java
index 2148b81353a3..60ec1b4d4cd7 100644
--- 
a/core/camel-support/src/main/java/org/apache/camel/support/CamelContextHelper.java
+++ 
b/core/camel-support/src/main/java/org/apache/camel/support/CamelContextHelper.java
@@ -34,6 +34,7 @@ import org.apache.camel.NamedNode;
 import org.apache.camel.NamedRoute;
 import org.apache.camel.NoSuchBeanException;
 import org.apache.camel.NoSuchEndpointException;
+import org.apache.camel.Route;
 import org.apache.camel.RuntimeCamelException;
 import org.apache.camel.clock.Clock;
 import org.apache.camel.clock.EventClock;
@@ -551,6 +552,27 @@ public final class CamelContextHelper {
         return 0;
     }
 
+    /**
+     * Whether the given route is started automatically when its CamelContext 
starts, taking into account the
+     * CamelContext and route <tt>autoStartup</tt> options and the 
CamelContext <tt>autoStartupExcludePattern</tt>.
+     *
+     * @param  route the route
+     * @return       <tt>true</tt> if the route is started automatically
+     */
+    public static boolean isAutoStartup(Route route) {
+        CamelContext camelContext = route.getCamelContext();
+        if (Boolean.FALSE.equals(camelContext.isAutoStartup()) || 
Boolean.FALSE.equals(route.isAutoStartup())) {
+            return false;
+        }
+        String exclude = camelContext.getAutoStartupExcludePattern();
+        if (exclude != null) {
+            String[] patterns = exclude.split(",");
+            return !PatternHelper.matchPatterns(route.getRouteId(), patterns)
+                    && 
!PatternHelper.matchPatterns(route.getEndpoint().getEndpointUri(), patterns);
+        }
+        return true;
+    }
+
     /**
      * A helper method to access a camel context properties with a prefix
      *
diff --git a/design/aiTool.adoc b/design/aiTool.adoc
index 782023cbbbe5..522425a239da 100644
--- a/design/aiTool.adoc
+++ b/design/aiTool.adoc
@@ -343,7 +343,12 @@ URI syntax: `ai-tool:toolName[?options]`
 
 Lifecycle (managed by `AiToolConsumer`):
 
-* **`doStart()`**: builds `AiToolSpec` from configuration, registers in 
`AiToolRegistry`
+* **route warm-up** (`AiToolEndpoint.doStart()`): builds `AiToolSpec` from 
configuration and registers in
+  `AiToolRegistry`, if the route is started automatically. Camel warms up all 
routes before it starts any route
+  consumer, so a route that sends a request as soon as it starts (such as 
`stream:in`) sees every tool regardless of
+  route order.
+* **`doStart()`**: registers in `AiToolRegistry` (building the spec first when 
the route was not started
+  automatically, or is restarted)
 * **`doStop()`**: deregisters from `AiToolRegistry`, clears state
 * **`doSuspend()`**: deregisters from `AiToolRegistry` (keeps state for resume)
 * **`doResume()`**: re-registers in `AiToolRegistry` using saved state

Reply via email to