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

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new 0a914a2c0bd2 chore: camel-jbang - catalog doc answers for EIP 
sections, many reads without a write, and a foreign camelVersion (#31389)
0a914a2c0bd2 is described below

commit 0a914a2c0bd28ebaacc7b63cdca4bcec696fea01
Author: Claus Ibsen <[email protected]>
AuthorDate: Sat Dec 5 08:57:00 2026 +0100

    chore: camel-jbang - catalog doc answers for EIP sections, many reads 
without a write, and a foreign camelVersion (#31389)
    
    Found in a local-model benchmark night with qwen4:35b-a3b-nvfp4, where 54 
of 72 failed steps ended at the tool-call
    limit without a write:
    
    - camel_catalog_doc docPage now returns a section of an EIP page (split, 
onException, ...), as it does for a component.
      It was ignored without a word, so a model asked for one section after 
another. When there is no such section, the
      answer says so, with the sections there are, or that the EIP has no doc 
page with sections, and for rest names the
      component page.
    - After 10 catalog answers in a row without a write, each catalog answer of 
the MCP server adds a nextStep note to
      write the file. A write or edit, or another tool such as validating a 
draft, starts the count again.
    - camel_catalog_doc and camel_catalog_find say when the answer is for 
another Camel version than the CLI's (or the
      integration's), and the camelVersion descriptions no longer give an 
example version (4.17.0 was copied by the model).
    
    
    Claude-Session: https://claude.ai/code/session_016Y4dDi5iQNgtHrDdz2NpwF
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 .../dsl/jbang/core/commands/ai/AuthoringTools.java | 53 +++++++++++++---
 .../dsl/jbang/core/commands/ai/CatalogDocs.java    | 39 ++++++++++++
 .../jbang/core/commands/ai/RepeatedToolCalls.java  | 46 ++++++++++++++
 .../dsl/jbang/core/commands/ai/ToolContext.java    | 17 ++++++
 .../commands/ai/AuthoringToolsVersionNoteTest.java | 70 ++++++++++++++++++++++
 .../jbang/core/commands/ai/CatalogDocsTest.java    | 23 +++++++
 .../core/commands/ai/RepeatedToolCallsTest.java    | 35 +++++++++++
 .../jbang/core/commands/mcp/AuthoringTools.java    | 25 +++++++-
 .../core/commands/mcp/RepeatedCallSessions.java    | 29 +++++++++
 .../dsl/jbang/core/commands/mcp/ToolArgDocs.java   |  4 +-
 .../core/commands/mcp/AuthoringToolsRootsTest.java |  8 +--
 .../core/commands/mcp/AuthoringToolsTest.java      | 35 +++++++++--
 .../commands/mcp/McpSecurityInterceptorTest.java   |  7 ++-
 13 files changed, 368 insertions(+), 23 deletions(-)

diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/AuthoringTools.java
 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/AuthoringTools.java
index e2515748ebb3..bf8c875a4694 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/AuthoringTools.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/AuthoringTools.java
@@ -75,7 +75,9 @@ import static 
org.apache.camel.dsl.jbang.core.commands.ai.ToolDescriptor.tool;
 public final class AuthoringTools {
 
     static final String NAME_DESC = "Integration name or pid (default: the 
selected one, or the only one running)";
-    static final String VERSION_DESC = "Camel version to answer for (default: 
the CLI's own, or the selected integration's)";
+    static final String VERSION_DESC
+            = "Camel version to answer for; leave it out for the CLI's own or 
the selected integration's, unless the"
+              + " project runs another Camel version";
     public static final String EDITS_DESC
             = "Several changes to the file in one call, applied in order and 
written once, so it is never reloaded"
               + " half done, e.g. a to: direct:x and the route from direct:x:"
@@ -138,13 +140,13 @@ public final class AuthoringTools {
                             + " checks the options against the catalog. When 
that answer was cut, it named the sections"
                             + " it left out: docPage=<section title> returns 
one of them.")
                 .executor((ctx, args) -> {
-                    applyVersion(ctx, args);
+                    String versionNote = applyVersionWithNote(ctx, args);
                     // the Kamelets of the release the project runs with 
(CAMEL-27762)
-                    return CatalogDocs.catalogDoc(ctx.catalog(), 
args.get("name"), args.get("endpoint"),
+                    return 
withVersionNote(CatalogDocs.catalogDoc(ctx.catalog(), args.get("name"), 
args.get("endpoint"),
                             args.get("kind"), args.get("optionsFilter"), 
args.get("includeOptions"),
                             bool(args, "includeHeaders", false), bool(args, 
"includeDoc", false),
                             args.get("docPage"), integer(args, "limit", -1),
-                            
KameletDefinitions.projectVersion(ctx.projectDirectory())).toJson();
+                            
KameletDefinitions.projectVersion(ctx.projectDirectory())), 
versionNote).toJson();
                 }));
 
         registry.accept(tool("camel_catalog_find",
@@ -163,10 +165,10 @@ public final class AuthoringTools {
                 .repeatHint("Use a match from the earlier answer, or ask with 
another term; then write the file with"
                             + " camel_write_file.")
                 .executor((ctx, args) -> {
-                    applyVersion(ctx, args);
-                    return CatalogDocs.find(ctx.catalog(), args.get("term"), 
args.get("kind"),
-                            integer(args, "limit", 10), 
KameletDefinitions.projectVersion(ctx.projectDirectory()))
-                            .toJson();
+                    String versionNote = applyVersionWithNote(ctx, args);
+                    return withVersionNote(CatalogDocs.find(ctx.catalog(), 
args.get("term"), args.get("kind"),
+                            integer(args, "limit", 10), 
KameletDefinitions.projectVersion(ctx.projectDirectory())),
+                            versionNote).toJson();
                 }));
 
         registry.accept(tool("camel_catalog_sample",
@@ -2882,6 +2884,41 @@ public final class AuthoringTools {
 
     // ---- argument helpers ----
 
+    /** The Camel version of the CLI's own catalog: the catalog tools answer 
for it when no version is set. */
+    private static final String OWN_VERSION = new 
org.apache.camel.catalog.DefaultCamelCatalog().getCatalogVersion();
+
+    /**
+     * As {@link #applyVersion(ToolContext, Map)}, and returns the note for 
the answer when the call asked for another
+     * version than the one the tools answer for without it, or null. A model 
can add a version nobody gave it: in the
+     * local-model benchmark (qwen4, Dec 2026) 192 doc calls asked for 4.10.0, 
4.14.0 or 4.17.0 (the example in a tool
+     * description then), and got the options of a release more than a year 
old without a word that they were.
+     */
+    static String applyVersionWithNote(ToolContext ctx, Map<String, String> 
args) {
+        String asked = args.get("camelVersion");
+        if (asked == null || asked.isBlank()) {
+            return null;
+        }
+        asked = asked.trim();
+        // the version an MCP server applied for this call is not the 
integration's: without it the answer is the CLI's
+        boolean integration = ctx.camelVersion() != null && 
!ctx.isCamelVersionOfCall();
+        String own = integration ? ctx.camelVersion() : OWN_VERSION;
+        ctx.setCamelVersion(asked);
+        if (own == null || asked.equals(own)) {
+            return null;
+        }
+        return "This answer is for Camel " + asked + ", as this call asked. 
Without camelVersion it is for Camel " + own
+               + (integration ? ", the version of the integration" : ", the 
version of the Camel CLI")
+               + ". Leave camelVersion out unless the project runs another 
Camel version.";
+    }
+
+    /** The answer with the note of {@link #applyVersionWithNote(ToolContext, 
Map)}, when there is one. */
+    private static JsonObject withVersionNote(JsonObject answer, String note) {
+        if (note != null && answer != null) {
+            answer.put("camelVersionNote", note);
+        }
+        return answer;
+    }
+
     private static void applyVersion(ToolContext ctx, Map<String, String> 
args) {
         String version = args.get("camelVersion");
         if (version != null && !version.isBlank()) {
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/CatalogDocs.java
 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/CatalogDocs.java
index aacaa924f15e..e080fdcf5f81 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/CatalogDocs.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/CatalogDocs.java
@@ -519,6 +519,9 @@ public final class CatalogDocs {
                 em = catalog.eipModel(anyCase);
             }
             if (em != null) {
+                if (page != null && !page.isEmpty()) {
+                    return eipSection(catalog, em, page, lowerFilter);
+                }
                 return eipDoc(catalog, em, lowerFilter, scope, includeDoc, 
null);
             }
             if (BEANS_ENTRY.equalsIgnoreCase(name)) {
@@ -848,6 +851,42 @@ public final class CatalogDocs {
         return result;
     }
 
+    /**
+     * A section of the doc page of an EIP, by its title (docPage), as for a 
component. The EIP answer used to leave
+     * docPage out without a word: a model that asked for a section got the 
options again, and asked for another
+     * section, and another. In the local-model benchmark (qwen4, Dec 2026), 
29 of 61 steps that ended at 25 tool calls
+     * without a write asked for sections of split, rest or onException this 
way. When there is no such section, the
+     * answer says so, with the sections there are, or that the EIP has no doc 
page with sections.
+     */
+    private static JsonObject eipSection(CamelCatalog catalog, EipModel em, 
String page, String lowerFilter) {
+        String adoc = catalog.asciiDoc(em.getName() + "-eip");
+        List<DocSection> sections = docSections(adoc);
+        DocSection section = findSection(sections, page);
+        if (section != null) {
+            JsonObject answer = eipDoc(em, lowerFilter, OptionScope.NONE, 
section.text());
+            answer.put("section", section.title());
+            return answer;
+        }
+        JsonObject err;
+        if (sections.isEmpty()) {
+            err = error("The EIP " + em.getName() + " has no doc page with 
sections in the catalog, so there is no"
+                        + " section '" + page + "'. Its options are in 
camel_catalog_doc name=" + em.getName()
+                        + " without docPage");
+        } else {
+            err = error("No section '" + page + "' in the doc page of the EIP 
" + em.getName());
+            err.put("sections", sectionTitles(sections, lowerFilter));
+        }
+        if (catalog.componentModel(em.getName()) != null) {
+            // rest is an EIP (the REST DSL) and a component: the component 
page has the sections
+            err.put("componentDoc", "camel_catalog_doc name=" + em.getName() + 
" kind=component docPage=<section title>"
+                                    + " returns a section of the " + 
em.getName() + " component page");
+        }
+        if (CatalogSamples.hasEipSample(catalog, em.getName())) {
+            err.put("sampleHint", "camel_catalog_sample name=" + em.getName() 
+ " returns a validated YAML example");
+        }
+        return err;
+    }
+
     /**
      * The top-level entries of the YAML DSL whose model is an application 
model of the catalog (models-app), not an EIP
      * model: camel_catalog_doc and camel_catalog_find did not find 
sslContextParameters (CAMEL-25735).
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/RepeatedToolCalls.java
 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/RepeatedToolCalls.java
index 2db6dd7219be..7f2b03dee99d 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/RepeatedToolCalls.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/RepeatedToolCalls.java
@@ -23,6 +23,7 @@ import java.util.Collection;
 import java.util.HashMap;
 import java.util.HexFormat;
 import java.util.Map;
+import java.util.Set;
 import java.util.TreeMap;
 
 import org.apache.camel.util.json.JsonObject;
@@ -58,8 +59,26 @@ public final class RepeatedToolCalls {
     /** Guards against unbounded growth over a very long session; the oldest 
counts are simply forgotten. */
     private static final int MAX_TRACKED = 1000;
 
+    /**
+     * The catalog tools whose answers count as reading: from the {@value 
#READS_BEFORE_WRITE_NOTE}th of them in a row,
+     * with no write in between, each answer also says to write the file.
+     */
+    static final Set<String> CATALOG_READS = Set.of("camel_catalog_doc", 
"camel_catalog_find", "camel_catalog_sample");
+
+    /**
+     * How many catalog answers in a row, without a write, before each answer 
also says to write the file. A model can
+     * read without end when each question is a little different, so the note 
for identical calls never comes: in the
+     * local-model benchmark (qwen4, Dec 2026) 54 of 72 failed steps of the 
new set ended at their 25 tool calls without
+     * a write, most of them asking for one doc section after another. In the 
steps that passed, 95% of the longest runs
+     * of reads without a write were shorter than 10 (qwen3.6: 97%).
+     */
+    static final int READS_BEFORE_WRITE_NOTE = 10;
+
     private final Map<String, Integer> counts = new HashMap<>();
 
+    /** The catalog answers since the last write, or since the session began. 
*/
+    private int readsSinceWrite;
+
     /** The calls whose answer was an error given as data, such as a name the 
catalog has not got, with that answer. */
     private final Map<String, JsonObject> misses = new HashMap<>();
 
@@ -152,10 +171,37 @@ public final class RepeatedToolCalls {
         }
     }
 
+    /**
+     * Counts a call of a tool and returns the note to add to its answer, or 
null. A catalog read counts; any other tool
+     * given here, such as validating a draft, means the model is working on 
its content and starts the count again, as
+     * {@link #recordWrite()} does. From the {@value 
#READS_BEFORE_WRITE_NOTE}th catalog read in a row, the note says
+     * how many there were and that writing is the next step.
+     */
+    public synchronized String readNote(String tool) {
+        if (!CATALOG_READS.contains(tool)) {
+            readsSinceWrite = 0;
+            return null;
+        }
+        readsSinceWrite++;
+        if (readsSinceWrite < READS_BEFORE_WRITE_NOTE) {
+            return null;
+        }
+        return "You have read " + readsSinceWrite + " catalog answers in a row 
without writing a file. Write the file"
+               + " now with camel_write_file, or change it with 
camel_edit_file: the write checks the options against"
+               + " the catalog, and its answer says what to change. Read more 
only for an option that the write says"
+               + " is wrong.";
+    }
+
+    /** A file was written or changed: the catalog reads are counted from zero 
again. */
+    public synchronized void recordWrite() {
+        readsSinceWrite = 0;
+    }
+
     /** Forgets the calls so far: a new session starts. */
     public synchronized void reset() {
         counts.clear();
         misses.clear();
+        readsSinceWrite = 0;
     }
 
     /**
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ToolContext.java
 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ToolContext.java
index d2670d694aac..bec03d705015 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ToolContext.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ToolContext.java
@@ -50,6 +50,7 @@ public class ToolContext {
     private volatile long pid = -1;
     private volatile CamelCatalog catalog;
     private volatile String camelVersion;
+    private volatile boolean versionOfCall;
     private volatile Path defaultDirectory;
     // guarded by this: the root is asked for once per context
     private Supplier<Path> rootDirectory;
@@ -128,6 +129,22 @@ public class ToolContext {
         }
     }
 
+    /**
+     * Sets the camelVersion argument of the call before the tool runs, as an 
MCP server does to hand the tool a cached
+     * catalog of that version. Unlike {@link #setCamelVersion(String)} it is 
not the version of an integration: without
+     * the argument the tools answer for the CLI's own version, and a catalog 
answer says so when the call asked for
+     * another.
+     */
+    public void setCamelVersionOfCall(String camelVersion) {
+        setCamelVersion(camelVersion);
+        this.versionOfCall = camelVersion != null;
+    }
+
+    /** Whether {@link #camelVersion()} is the camelVersion argument of the 
call, not the version of an integration. */
+    public boolean isCamelVersionOfCall() {
+        return versionOfCall;
+    }
+
     /**
      * The project directory the file tools use when a call names none: the 
TUI sets it to the source directory of the
      * selected integration, {@code camel ask} to the project directory; an 
MCP server leaves it null.
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/AuthoringToolsVersionNoteTest.java
 
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/AuthoringToolsVersionNoteTest.java
new file mode 100644
index 000000000000..4b72ad815356
--- /dev/null
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/AuthoringToolsVersionNoteTest.java
@@ -0,0 +1,70 @@
+/*
+ * 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.ai;
+
+import java.util.Map;
+
+import org.apache.camel.catalog.DefaultCamelCatalog;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The note of a catalog answer for another Camel version than the one the 
tools answer for without camelVersion: a
+ * model added versions nobody gave it (qwen4 night, Dec 2026) and got the 
options of an old release without a word.
+ */
+class AuthoringToolsVersionNoteTest {
+
+    private static final String OWN = new 
DefaultCamelCatalog().getCatalogVersion();
+
+    @Test
+    void anotherVersionThanTheClisOwnGetsANote() {
+        ToolContext ctx = new ToolContext();
+        String note = AuthoringTools.applyVersionWithNote(ctx, 
Map.of("camelVersion", "4.14.0"));
+        assertTrue(note.startsWith("This answer is for Camel 4.14.0"), note);
+        assertTrue(note.contains("Camel " + OWN + ", the version of the Camel 
CLI"), note);
+        assertTrue(note.contains("Leave camelVersion out"), note);
+        assertEquals("4.14.0", ctx.camelVersion(), "the version still 
applies");
+    }
+
+    @Test
+    void anotherVersionThanTheIntegrationsGetsANoteNamingIt() {
+        ToolContext ctx = new ToolContext();
+        ctx.setCamelVersion("4.18.0");
+        String note = AuthoringTools.applyVersionWithNote(ctx, 
Map.of("camelVersion", "4.10.0"));
+        assertTrue(note.contains("Camel 4.18.0, the version of the 
integration"), note);
+    }
+
+    @Test
+    void theVersionAnMcpServerAppliedForTheCallIsComparedWithTheClisOwn() {
+        // an MCP server applies the call's camelVersion before the tool runs, 
to hand it a cached catalog
+        ToolContext ctx = new ToolContext();
+        ctx.setCamelVersionOfCall("4.17.0");
+        String note = AuthoringTools.applyVersionWithNote(ctx, 
Map.of("camelVersion", "4.17.0"));
+        assertTrue(note.startsWith("This answer is for Camel 4.17.0"), note);
+        assertTrue(note.contains("Camel " + OWN + ", the version of the Camel 
CLI"), note);
+    }
+
+    @Test
+    void noVersionOrTheSameVersionGetsNoNote() {
+        assertNull(AuthoringTools.applyVersionWithNote(new ToolContext(), 
Map.of()));
+        assertNull(AuthoringTools.applyVersionWithNote(new ToolContext(), 
Map.of("camelVersion", " ")));
+        assertNull(AuthoringTools.applyVersionWithNote(new ToolContext(), 
Map.of("camelVersion", OWN)));
+    }
+}
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/CatalogDocsTest.java
 
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/CatalogDocsTest.java
index 30e44323f163..27dcb9391902 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/CatalogDocsTest.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/CatalogDocsTest.java
@@ -295,6 +295,29 @@ class CatalogDocsTest {
         assertNull(catalogDoc(Map.of("name", "constant", "kind", 
"language")).get("docPages"));
     }
 
+    @Test
+    void docPageReturnsASectionOfAnEipPage() throws Exception {
+        // the EIP answer left docPage out without a word, so a model asked 
for one section after another (qwen4 night)
+        JsonObject section = catalogDoc(Map.of("name", "split", "kind", "eip", 
"docPage", "Splitting with a delimiter"));
+        assertEquals("Splitting with a delimiter", 
section.getString("section"));
+        assertTrue(section.getString("doc").contains("delimiter"), 
section.toJson());
+        assertNull(section.get("options"), "the section is the answer");
+
+        JsonObject missing = catalogDoc(Map.of("name", "split", "kind", "eip", 
"docPage", "Split producer binding"));
+        assertTrue(missing.getString("error").contains("No section 'split 
producer binding'"), missing.toJson());
+        assertTrue(missing.getCollection("sections").contains("Splitting with 
a delimiter"), missing.toJson());
+        assertNotNull(missing.get("sampleHint"));
+    }
+
+    @Test
+    void docPageOfAnEipWithoutSectionsSaysSoAndNamesTheComponentPage() throws 
Exception {
+        // rest is the REST DSL (an EIP without a doc page of its own) and a 
component with one
+        JsonObject missing = catalogDoc(Map.of("name", "rest", "kind", "eip", 
"docPage", "Rest producer binding"));
+        assertTrue(missing.getString("error").contains("The EIP rest has no 
doc page with sections"), missing.toJson());
+        assertNull(missing.get("sections"));
+        
assertTrue(missing.getString("componentDoc").contains("kind=component"), 
missing.toJson());
+    }
+
     @Test
     void filterReturnsMatchingFunctionsWithParametersAndExamples() throws 
Exception {
         JsonObject result = catalogDoc(Map.of("name", "simple", "kind", 
"language", "optionsFilter", "random"));
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/RepeatedToolCallsTest.java
 
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/RepeatedToolCallsTest.java
index b28bb8475a12..e8d5e362df7c 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/RepeatedToolCallsTest.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/RepeatedToolCallsTest.java
@@ -335,4 +335,39 @@ class RepeatedToolCallsTest {
         // and the key does not hold the source itself
         assertThat(RepeatedToolCalls.key("camel_validate_source", withNewline, 
"content")).doesNotContain("<routes/>");
     }
+
+    @Test
+    void manyCatalogReadsInARowWithoutAWriteGetANoteToWrite() {
+        // qwen4 night: one doc section after another, each call a little 
different, so no identical-call note came
+        for (int i = 1; i < RepeatedToolCalls.READS_BEFORE_WRITE_NOTE; i++) {
+            assertThat(calls.readNote("camel_catalog_doc")).as("read " + 
i).isNull();
+        }
+        String note = calls.readNote("camel_catalog_find");
+        assertThat(note).isNotNull();
+        assertThat(note).startsWith("You have read " + 
RepeatedToolCalls.READS_BEFORE_WRITE_NOTE + " catalog answers");
+        assertThat(note).contains("camel_write_file");
+        assertThat(calls.readNote("camel_catalog_sample")).contains("read 11 
catalog answers");
+    }
+
+    @Test
+    void aWriteOrAnotherToolStartsTheCountOfReadsAgain() {
+        for (int i = 0; i < RepeatedToolCalls.READS_BEFORE_WRITE_NOTE; i++) {
+            calls.readNote("camel_catalog_doc");
+        }
+        calls.recordWrite();
+        assertThat(calls.readNote("camel_catalog_doc")).as("counted from zero 
after a write").isNull();
+
+        for (int i = 0; i < RepeatedToolCalls.READS_BEFORE_WRITE_NOTE; i++) {
+            calls.readNote("camel_catalog_doc");
+        }
+        // validating a draft is work on the content, as a write is
+        assertThat(calls.readNote("camel_validate_source")).isNull();
+        assertThat(calls.readNote("camel_catalog_doc")).isNull();
+
+        for (int i = 0; i < RepeatedToolCalls.READS_BEFORE_WRITE_NOTE; i++) {
+            calls.readNote("camel_catalog_doc");
+        }
+        calls.reset();
+        assertThat(calls.readNote("camel_catalog_doc")).as("a new session 
counts from zero").isNull();
+    }
 }
diff --git 
a/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/AuthoringTools.java
 
b/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/AuthoringTools.java
index dabfcbe93e25..a055443fe8bf 100644
--- 
a/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/AuthoringTools.java
+++ 
b/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/AuthoringTools.java
@@ -65,7 +65,8 @@ public class AuthoringTools {
     private static final Logger LOG = Logger.getLogger(AuthoringTools.class);
 
     private static final String NAME_DESC = "Integration name or pid (default: 
the only one running)";
-    private static final String VERSION_DESC = "Camel version to answer for 
(default: the CLI's own)";
+    private static final String VERSION_DESC
+            = "Camel version to answer for; leave it out for the CLI's own, 
unless the project runs another Camel version";
     private static final String DIRECTORY_DESC = "Project directory with the 
source files (absolute path)";
     /**
      * How long a file tool waits for the client's roots, at most: the 
server's own timeout
@@ -207,6 +208,7 @@ public class AuthoringTools {
                         + "An integration running in dev mode reloads the 
change, otherwise restart it with "
                         + "camel_control.")
     public JsonObject camel_write_file(
+            McpConnection connection,
             Roots roots,
             @ToolArg(description = DIRECTORY_DESC, required = false) String 
directory,
             @ToolArg(description = "File path relative to the directory 
(subdirectories are created)",
@@ -214,6 +216,7 @@ public class AuthoringTools {
             @ToolArg(description = "The complete new content", required = 
true) String content,
             @ToolArg(description = VERSION_DESC, required = false) String 
camelVersion) {
         refuseRedacted(content);
+        recordWrite(connection);
         return call("camel_write_file", args("directory", directory, "file", 
file, "content", content,
                 "camelVersion", camelVersion), null, clientRoot(roots));
     }
@@ -225,6 +228,7 @@ public class AuthoringTools {
                         + "camel_write_file for a new one. A change to several 
places of the file is given at once in "
                         + "edits, so the file is written and reloaded once, 
not half done.")
     public JsonObject camel_edit_file(
+            McpConnection connection,
             Roots roots,
             @ToolArg(description = DIRECTORY_DESC, required = false) String 
directory,
             @ToolArg(description = "File path relative to the directory", 
required = true) String file,
@@ -250,9 +254,20 @@ public class AuthoringTools {
             // of a YAML line) then deleted the text it was to replace 
(CAMEL-26932)
             arguments.put("replace", replace);
         }
+        recordWrite(connection);
         return call("camel_edit_file", arguments, null, clientRoot(roots));
     }
 
+    /**
+     * A write or change of a file, also one the checks refuse: the model is 
working on the content, so its catalog
+     * reads are counted from zero again.
+     */
+    private void recordWrite(McpConnection connection) {
+        if (repeatedCalls != null) {
+            repeatedCalls.recordWrite(connection);
+        }
+    }
+
     /**
      * The project directory of a file tool call that names none 
(CAMEL-26398): the client's only {@code file:} root,
      * asked for only when a call needs it, and only of a client that declares 
roots. The file stays inside it, as
@@ -537,6 +552,9 @@ public class AuthoringTools {
     /** As {@link #callDeterministic(McpConnection, String, Map)}, with what 
the tool's context gets beside the args. */
     JsonObject callDeterministic(
             McpConnection connection, String tool, Map<String, String> args, 
Consumer<ToolContext> configure) {
+        // many catalog reads in a row without a write: the answer also says 
to write the file (the note of a
+        // repeated call says so already)
+        String readNote = repeatedCalls != null ? 
repeatedCalls.readNote(connection, tool) : null;
         JsonObject repeat = repeatedCalls != null ? 
repeatedCalls.repeatOf(connection, tool, args) : null;
         if (repeat != null) {
             return repeat;
@@ -545,6 +563,9 @@ public class AuthoringTools {
         if (repeatedCalls != null) {
             repeatedCalls.recordSuccessfulAnswer(connection, tool, args, 
result);
         }
+        if (readNote != null) {
+            result.put("nextStep", readNote);
+        }
         return result;
     }
 
@@ -579,7 +600,7 @@ public class AuthoringTools {
                     // Set the version first: setCamelVersion() on a fresh 
context nulls out any previously set catalog,
                     // so the catalog must be set after (or the version set 
before, so it is a no-op when they match).
                     if (camelVersion != null && !camelVersion.isBlank()) {
-                        ctx.setCamelVersion(camelVersion.trim());
+                        ctx.setCamelVersionOfCall(camelVersion.trim());
                     }
                     CamelCatalog catalog = catalogService.loadCatalog(null, 
camelVersion, null);
                     ctx.setCatalog(catalog);
diff --git 
a/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RepeatedCallSessions.java
 
b/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RepeatedCallSessions.java
index 8807ded9e691..ae323ee0f10d 100644
--- 
a/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RepeatedCallSessions.java
+++ 
b/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RepeatedCallSessions.java
@@ -60,6 +60,35 @@ public class RepeatedCallSessions {
         return calls.repeatOf(ToolRegistry.findTool(tool), args);
     }
 
+    /**
+     * Counts a deterministic call of the connection and returns the note to 
add to its answer after many catalog reads
+     * in a row without a write, or null (see {@link 
RepeatedToolCalls#readNote(String)}).
+     */
+    String readNote(McpConnection connection, String tool) {
+        if (connection == null || connection.id() == null) {
+            return null;
+        }
+        RepeatedToolCalls calls;
+        synchronized (sessions) {
+            calls = sessions.computeIfAbsent(connection.id(), id -> new 
RepeatedToolCalls());
+        }
+        return calls.readNote(tool);
+    }
+
+    /** The connection wrote or changed a file: its catalog reads are counted 
from zero again. */
+    void recordWrite(McpConnection connection) {
+        if (connection == null || connection.id() == null) {
+            return;
+        }
+        RepeatedToolCalls calls;
+        synchronized (sessions) {
+            calls = sessions.get(connection.id());
+        }
+        if (calls != null) {
+            calls.recordWrite();
+        }
+    }
+
     /**
      * Records that the tool answered this call in full without throwing. 
Failed calls must not count against the retry
      * budget (CAMEL-25640).
diff --git 
a/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/ToolArgDocs.java
 
b/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/ToolArgDocs.java
index aeb84c3b8e9a..fc1ed072427d 100644
--- 
a/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/ToolArgDocs.java
+++ 
b/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/ToolArgDocs.java
@@ -29,7 +29,9 @@ final class ToolArgDocs {
     static final String RUNTIME_REQUIRED = "Runtime: main | spring-boot | 
quarkus";
 
     /** Camel version for catalog lookups. */
-    static final String CAMEL_VERSION = "Camel version (e.g., 4.17.0); 
defaults to catalog version.";
+    static final String CAMEL_VERSION
+            = "Camel version to answer for; leave it out for the catalog's 
own, unless the project runs another Camel"
+              + " version";
 
     /** Multi-runtime version selector; for quarkus use the Quarkus Platform 
version. */
     static final String VERSION_QUERY = "Version: main/spring-boot uses Camel 
version (e.g., 4.17.0); "
diff --git 
a/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/AuthoringToolsRootsTest.java
 
b/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/AuthoringToolsRootsTest.java
index 909b89515acd..0fc3e2cb7408 100644
--- 
a/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/AuthoringToolsRootsTest.java
+++ 
b/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/AuthoringToolsRootsTest.java
@@ -82,13 +82,13 @@ class AuthoringToolsRootsTest {
         assertThat(read.getString("content")).isEqualTo(ROUTE);
         JsonObject validated = tools.camel_validate_source(null, roots, null, 
"camel/main-route.yaml", null, null);
         
assertThat(validated.getBoolean("valid")).as(validated.toJson()).isTrue();
-        JsonObject written = tools.camel_write_file(roots, null, 
"camel/application.properties", "a=b\n", null);
+        JsonObject written = tools.camel_write_file(null, roots, null, 
"camel/application.properties", "a=b\n", null);
         
assertThat(written.getString("status")).as(written.toJson()).isEqualTo("created");
         
assertThat(Files.readString(workspace.resolve("camel/application.properties"))).isEqualTo("a=b\n");
-        JsonObject edited = tools.camel_edit_file(roots, null, 
"camel/application.properties", "a=b", "a=c", null, null);
+        JsonObject edited = tools.camel_edit_file(null, roots, null, 
"camel/application.properties", "a=b", "a=c", null, null);
         
assertThat(edited.getString("status")).as(edited.toJson()).isEqualTo("edited");
         // a directory the call names inside the root is created by the write
-        JsonObject created = tools.camel_write_file(roots, 
workspace.resolve("config").toString(),
+        JsonObject created = tools.camel_write_file(null, roots, 
workspace.resolve("config").toString(),
                 "application.properties", "a=b\n", null);
         
assertThat(created.getString("status")).as(created.toJson()).isEqualTo("created");
     }
@@ -130,7 +130,7 @@ class AuthoringToolsRootsTest {
     void aClientThatFailsToListItsRootsGivesNoDefault() {
         FakeRoots failing = new FakeRoots(true, () -> 
Uni.createFrom().failure(new IllegalStateException("no roots")));
 
-        assertThatThrownBy(() -> tools.camel_write_file(failing, null, 
"application.properties", "a=b\n", null))
+        assertThatThrownBy(() -> tools.camel_write_file(null, failing, null, 
"application.properties", "a=b\n", null))
                 
.isInstanceOf(ToolCallException.class).hasMessageStartingWith("directory is 
required");
     }
 
diff --git 
a/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/AuthoringToolsTest.java
 
b/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/AuthoringToolsTest.java
index 2f2c8acae7c3..8f409793f5ed 100644
--- 
a/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/AuthoringToolsTest.java
+++ 
b/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/AuthoringToolsTest.java
@@ -92,11 +92,11 @@ class AuthoringToolsTest {
     @Test
     void filesAreReadAndWrittenInTheGivenDirectory(@TempDir Path dir) throws 
Exception {
         String route = "- route:\n    from:\n      uri: timer:tick\n      
steps:\n        - log:\n            message: hi\n";
-        JsonObject written = tools.camel_write_file(null, dir.toString(), 
"demo.camel.yaml", route, null);
+        JsonObject written = tools.camel_write_file(null, null, 
dir.toString(), "demo.camel.yaml", route, null);
         assertThat(written.getString("status")).isEqualTo("created");
         assertThat(Files.readString(dir.resolve("demo.camel.yaml"), 
StandardCharsets.UTF_8)).isEqualTo(route);
 
-        JsonObject invalid = tools.camel_write_file(null, dir.toString(), 
"demo.camel.yaml",
+        JsonObject invalid = tools.camel_write_file(null, null, 
dir.toString(), "demo.camel.yaml",
                 route.replace("message", "mesage"), null);
         assertThat(invalid.getString("status")).isEqualTo("invalid");
         assertThat(Files.readString(dir.resolve("demo.camel.yaml"), 
StandardCharsets.UTF_8)).isEqualTo(route);
@@ -116,7 +116,7 @@ class AuthoringToolsTest {
         // a blank replace was left out of the call, and the text was deleted 
instead (CAMEL-26932)
         Files.writeString(dir.resolve("application.properties"), 
"greeting=hello TODO world\n", StandardCharsets.UTF_8);
 
-        JsonObject edited = tools.camel_edit_file(null, dir.toString(), 
"application.properties", "TODO", " ", null,
+        JsonObject edited = tools.camel_edit_file(null, null, dir.toString(), 
"application.properties", "TODO", " ", null,
                 null);
 
         
assertThat(edited.getString("status")).as(edited.toJson()).isEqualTo("edited");
@@ -131,7 +131,7 @@ class AuthoringToolsTest {
                        + "        - log:\n            message: bye\n";
         Files.writeString(dir.resolve("demo.camel.yaml"), route, 
StandardCharsets.UTF_8);
 
-        JsonObject edited = tools.camel_edit_file(null, dir.toString(), 
"demo.camel.yaml", null, null,
+        JsonObject edited = tools.camel_edit_file(null, null, dir.toString(), 
"demo.camel.yaml", null, null,
                 List.of(new AuthoringTools.FileEdit("message: hi", "message: 
hello"),
                         new AuthoringTools.FileEdit("message: bye", "message: 
goodbye")),
                 null);
@@ -269,12 +269,37 @@ class AuthoringToolsTest {
                 // a tool that is deterministic for some arguments 
(camel_validate_source with content, an evaluation)
                 // counts too
                 boolean connected = 
Arrays.stream(m.getParameterTypes()).anyMatch(t -> t == McpConnection.class);
+                // the write tools get it too: a write starts the count of 
catalog reads in a row again
+                boolean writes = m.getName().equals("camel_write_file") || 
m.getName().equals("camel_edit_file");
                 assertThat(connected).as(m.getName() + " gets the connection 
to count its repeats")
-                        .isEqualTo(td.isDeterministicForSomeCalls());
+                        .isEqualTo(td.isDeterministicForSomeCalls() || writes);
             }
         }
     }
 
+    @Test
+    void manyDifferentCatalogReadsInARowGetANoteToWriteUntilAWrite(@TempDir 
Path dir) {
+        // qwen4 night (Dec 2026): one doc section after another, each call a 
little different, never a write
+        AuthoringTools counted = new AuthoringTools();
+        counted.repeatedCalls = new RepeatedCallSessions();
+        McpConnection agent = connection("agent-1");
+        String[] names = { "timer", "log", "file", "kafka", "jms", "sql", 
"rest", "http", "direct" };
+        for (String name : names) {
+            JsonObject doc = counted.camel_catalog_doc(agent, name, null, 
null, null, null, null, null, null, null, null);
+            assertThat(doc.get("nextStep")).as(name).isNull();
+        }
+        JsonObject tenth = counted.camel_catalog_doc(agent, "seda", null, 
null, null, null, null, null, null, null, null);
+        assertThat(tenth.getString("nextStep")).startsWith("You have read 10 
catalog answers in a row")
+                .contains("camel_write_file");
+        // another connection has its own count
+        assertThat(counted.camel_catalog_doc(connection("agent-2"), "seda", 
null, null, null, null, null, null, null,
+                null, null).get("nextStep")).isNull();
+
+        counted.camel_write_file(agent, null, dir.toString(), 
"application.properties", "a=b\n", null);
+        assertThat(counted.camel_catalog_doc(agent, "timer", null, null, null, 
null, null, null, null, null, null)
+                .get("nextStep")).as("counted from zero after the 
write").isNull();
+    }
+
     @Test
     void aThirdIdenticalCatalogMissGetsTheSuggestionsNotTheWriteHint() {
         // CAMEL-26932: a miss is answered as data, so it still counts; its 
note says what to ask instead
diff --git 
a/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/McpSecurityInterceptorTest.java
 
b/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/McpSecurityInterceptorTest.java
index f59dea61bd79..a2005b103d85 100644
--- 
a/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/McpSecurityInterceptorTest.java
+++ 
b/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/McpSecurityInterceptorTest.java
@@ -28,6 +28,7 @@ import java.util.Optional;
 
 import jakarta.interceptor.InvocationContext;
 
+import io.quarkiverse.mcp.server.McpConnection;
 import io.quarkiverse.mcp.server.Roots;
 import io.quarkiverse.mcp.server.ToolCallException;
 import org.apache.camel.util.json.JsonObject;
@@ -134,10 +135,10 @@ class McpSecurityInterceptorTest {
     private static Object writeFile(McpSecurityInterceptor interceptor, Path 
dir, String content) throws Exception {
         AuthoringTools tools = new AuthoringTools();
         tools.securityConfig = interceptor.config;
-        Method method = AuthoringTools.class.getMethod("camel_write_file", 
Roots.class, String.class, String.class,
-                String.class, String.class);
+        Method method = AuthoringTools.class.getMethod("camel_write_file", 
McpConnection.class, Roots.class, String.class,
+                String.class, String.class, String.class);
         Object result = interceptor.intercept(
-                new Invocation(tools, method, null, dir.toString(), 
"notes.txt", content, null));
+                new Invocation(tools, method, null, null, dir.toString(), 
"notes.txt", content, null));
         assertThat(((JsonObject) result).getString("status")).isIn("created", 
"overwritten");
         return result;
     }

Reply via email to