You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by da...@apache.org on 2026/09/13 13:38:51 UTC
(camel) branch main updated (d089f084ce5f -> 10ac427f27ad)
This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a change to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
from d089f084ce5f CAMEL-24694: camel-yaml-dsl - validator must accept the scalar forms the runtime accepts (#26351)
new 15bce9716352 CAMEL-24695: camel-jbang - one shared set of Camel authoring MCP tools for camel mcp and camel tui --mcp
new 10ac427f27ad CAMEL-24695: Address review feedback
The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../ROOT/pages/camel-4x-upgrade-guide-4_23.adoc | 22 +
.../modules/ROOT/pages/camel-jbang-mcp.adoc | 66 +-
.../modules/ROOT/pages/camel-jbang-tui.adoc | 43 +-
dsl/camel-jbang/camel-jbang-core/pom.xml | 9 +-
.../dsl/jbang/core/commands/ai/AuthoringTools.java | 469 ++++++++++++
.../dsl/jbang/core/commands/ai/CatalogDocs.java | 739 +++++++++++++++++++
.../dsl/jbang/core/commands/ai}/DiagnoseData.java | 13 +-
.../dsl/jbang/core/commands/ai/ErrorDiagnoser.java | 143 ++++
.../core/commands/ai/ExpressionEvaluator.java | 151 ++++
.../core/commands/ai/IntegrationLauncher.java | 259 +++++++
.../dsl/jbang/core/commands/ai/LogFileReader.java | 199 +++++
.../jbang/core/commands/ai/SourceValidator.java | 546 ++++++++++++++
.../dsl/jbang/core/commands/ai/ToolContext.java | 140 +++-
.../dsl/jbang/core/commands/ai/ToolDescriptor.java | 43 ++
.../dsl/jbang/core/commands/ai/ToolRegistry.java | 9 +
.../jbang/core/commands/ai/AuthoringToolsTest.java | 229 ++++++
.../jbang/core/commands/ai/CatalogDocsTest.java} | 24 +-
.../core/commands/ai/ExpressionEvaluatorTest.java | 68 ++
.../jbang/core/commands/ai/LogFileReaderTest.java | 66 ++
.../commands/ai/SourceValidatorEndpointTest.java} | 38 +-
.../commands/ai/SourceValidatorSimpleTest.java} | 26 +-
.../jbang/core/commands/mcp/AuthoringTools.java | 198 +++++
.../dsl/jbang/core/commands/mcp/CatalogTools.java | 60 +-
.../dsl/jbang/core/commands/mcp/DiagnoseData.java | 441 +----------
.../dsl/jbang/core/commands/mcp/DiagnoseTools.java | 185 +----
.../core/commands/mcp/AuthoringToolsTest.java | 111 +++
.../jbang/core/commands/mcp/DiagnoseToolsTest.java | 130 ++--
.../camel/dsl/jbang/core/commands/tui/AiPanel.java | 26 +-
.../dsl/jbang/core/commands/tui/CamelMonitor.java | 3 +-
.../jbang/core/commands/tui/DocViewerPopup.java | 4 +-
.../dsl/jbang/core/commands/tui/McpFacade.java | 114 +--
.../jbang/core/commands/tui/SourceEditAssist.java | 342 +--------
.../core/commands/tui/SourceValidationSupport.java | 70 +-
.../core/commands/tui/TuiToolDefinitions.java | 118 +--
.../jbang/core/commands/tui/TuiToolRegistry.java | 818 +++------------------
.../core/commands/tui/AcpPermissionPopupTest.java | 4 +-
.../jbang/core/commands/tui/AiPanelAcpTest.java | 12 +-
.../commands/tui/AiPanelHistoryCompactionTest.java | 2 +-
.../core/commands/tui/AiPanelPromptBudgetTest.java | 11 +-
.../core/commands/tui/McpFacadeWriteFileTest.java | 4 +-
.../commands/tui/TuiToolRegistryCoreToolsTest.java | 4 +-
.../tui/TuiToolRegistryEvalExpressionTest.java | 44 +-
42 files changed, 3872 insertions(+), 2131 deletions(-)
create mode 100644 dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/AuthoringTools.java
create mode 100644 dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/CatalogDocs.java
copy dsl/camel-jbang/{camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp => camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai}/DiagnoseData.java (98%)
create mode 100644 dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ErrorDiagnoser.java
create mode 100644 dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ExpressionEvaluator.java
create mode 100644 dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/IntegrationLauncher.java
create mode 100644 dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/LogFileReader.java
create mode 100644 dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/SourceValidator.java
create mode 100644 dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/AuthoringToolsTest.java
rename dsl/camel-jbang/{camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistryCatalogDocTest.java => camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/CatalogDocsTest.java} (88%)
create mode 100644 dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/ExpressionEvaluatorTest.java
create mode 100644 dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/LogFileReaderTest.java
rename dsl/camel-jbang/{camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/YamlEndpointValidationTest.java => camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/SourceValidatorEndpointTest.java} (83%)
rename dsl/camel-jbang/{camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/YamlSimpleValidationTest.java => camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/SourceValidatorSimpleTest.java} (84%)
create mode 100644 dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/AuthoringTools.java
create mode 100644 dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/AuthoringToolsTest.java
(camel) 01/02: CAMEL-24695: camel-jbang - one shared set of Camel authoring MCP tools for camel mcp and camel tui --mcp
Posted by da...@apache.org.
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
commit 15bce971635266d47a3aba295585f79a8d8fecd5
Author: Claus Ibsen <cl...@gmail.com>
AuthorDate: Sat Sep 12 12:46:54 2026 +0200
CAMEL-24695: camel-jbang - one shared set of Camel authoring MCP tools for camel mcp and camel tui --mcp
The authoring tools an AI agent needs to build and edit an integration are
defined once in the shared ToolRegistry in camel-jbang-core and exposed
under the same camel_ names by both MCP servers: catalog doc with the URI
rules and the simple syntax, catalog find, validate source, get/write
files, run, control, get log, get errors, eval expression (locally when no
integration runs) and error diagnose.
camel-jbang-mcp gets thin @Tool wrappers (the security interceptor and
access filter keep working); camel_catalog_doc replaces the AsciiDoc-only
tool of that name and camel_error_diagnose delegates to the shared
diagnoser. The TUI drops its tui_ copies of the eight tools, exposes the
shared definitions with its extras on top (selection as default directory,
confirm dialog and live replay for writes, infra logs, stop-all/close),
and the editor's source validation moves to the shared SourceValidator.
camel-jbang-core now depends on camel-yaml-dsl-validator.
Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
Signed-off-by: Claus Ibsen <cl...@gmail.com>
---
.../ROOT/pages/camel-4x-upgrade-guide-4_23.adoc | 22 +
.../modules/ROOT/pages/camel-jbang-mcp.adoc | 66 +-
.../modules/ROOT/pages/camel-jbang-tui.adoc | 43 +-
dsl/camel-jbang/camel-jbang-core/pom.xml | 9 +-
.../dsl/jbang/core/commands/ai/AuthoringTools.java | 469 ++++++++++++
.../dsl/jbang/core/commands/ai/CatalogDocs.java | 739 +++++++++++++++++++
.../dsl/jbang/core/commands/ai}/DiagnoseData.java | 13 +-
.../dsl/jbang/core/commands/ai/ErrorDiagnoser.java | 143 ++++
.../core/commands/ai/ExpressionEvaluator.java | 151 ++++
.../core/commands/ai/IntegrationLauncher.java | 259 +++++++
.../dsl/jbang/core/commands/ai/LogFileReader.java | 199 +++++
.../jbang/core/commands/ai/SourceValidator.java | 546 ++++++++++++++
.../dsl/jbang/core/commands/ai/ToolContext.java | 136 +++-
.../dsl/jbang/core/commands/ai/ToolDescriptor.java | 43 ++
.../dsl/jbang/core/commands/ai/ToolRegistry.java | 9 +
.../jbang/core/commands/ai/AuthoringToolsTest.java | 229 ++++++
.../jbang/core/commands/ai/CatalogDocsTest.java} | 24 +-
.../core/commands/ai/ExpressionEvaluatorTest.java | 68 ++
.../jbang/core/commands/ai/LogFileReaderTest.java | 66 ++
.../commands/ai/SourceValidatorEndpointTest.java} | 38 +-
.../commands/ai/SourceValidatorSimpleTest.java} | 26 +-
.../jbang/core/commands/mcp/AuthoringTools.java | 198 +++++
.../dsl/jbang/core/commands/mcp/CatalogTools.java | 60 +-
.../dsl/jbang/core/commands/mcp/DiagnoseData.java | 441 +----------
.../dsl/jbang/core/commands/mcp/DiagnoseTools.java | 185 +----
.../core/commands/mcp/AuthoringToolsTest.java | 111 +++
.../jbang/core/commands/mcp/DiagnoseToolsTest.java | 130 ++--
.../camel/dsl/jbang/core/commands/tui/AiPanel.java | 26 +-
.../dsl/jbang/core/commands/tui/CamelMonitor.java | 3 +-
.../jbang/core/commands/tui/DocViewerPopup.java | 4 +-
.../dsl/jbang/core/commands/tui/McpFacade.java | 114 +--
.../jbang/core/commands/tui/SourceEditAssist.java | 342 +--------
.../core/commands/tui/SourceValidationSupport.java | 70 +-
.../core/commands/tui/TuiToolDefinitions.java | 118 +--
.../jbang/core/commands/tui/TuiToolRegistry.java | 818 +++------------------
.../core/commands/tui/AcpPermissionPopupTest.java | 4 +-
.../jbang/core/commands/tui/AiPanelAcpTest.java | 12 +-
.../commands/tui/AiPanelHistoryCompactionTest.java | 2 +-
.../core/commands/tui/AiPanelPromptBudgetTest.java | 11 +-
.../core/commands/tui/McpFacadeWriteFileTest.java | 4 +-
.../commands/tui/TuiToolRegistryCoreToolsTest.java | 4 +-
.../tui/TuiToolRegistryEvalExpressionTest.java | 44 +-
42 files changed, 3868 insertions(+), 2131 deletions(-)
diff --git a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_23.adoc b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_23.adoc
index 21a6fd92ea74..9a58332b789a 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_23.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_23.adoc
@@ -655,6 +655,28 @@ Running an existing Maven project (`camel run pom.xml`) is unchanged, and still
from the `pom.xml`. The other commands that take `--runtime` (such as `camel export`,
`camel dependency list` and `camel version list`) accept `jbang` as an alias for `main`.
+=== camel-jbang (MCP servers)
+
+The Camel authoring tools for AI agents are now defined once, in `camel-jbang-core`, and exposed under the
+same `camel_` names by both MCP servers, `camel mcp` and `camel tui --mcp`: `camel_catalog_doc`,
+`camel_catalog_find`, `camel_validate_source`, `camel_get_files`, `camel_write_file`, `camel_run`,
+`camel_control`, `camel_get_log`, `camel_get_errors`, `camel_eval_expression` and `camel_error_diagnose`.
+
+In the TUI MCP server the tools `tui_catalog_doc`, `tui_validate_source`, `tui_write_file`, `tui_get_files`,
+`tui_control`, `tui_get_log`, `tui_get_errors` and `tui_eval_expression` were renamed to the `camel_` names
+above; the `tui_` prefix is now reserved for the tools that only make sense in front of the screen. Update
+MCP clients, prompts and ACP permission lists that name them. `camel_eval_expression` no longer fails when
+no integration is selected but evaluates the expression in a local scratch context, and `camel_get_errors`
+reads the integration's error file rather than the Errors tab.
+
+In `camel mcp` the `camel_catalog_doc` tool changed: it now takes the artifact `name` and `kind` (not a page
+name such as `kafka-component`) and returns the structured documentation with options and URI rules;
+`includeDoc=true` adds the AsciiDoc page the tool used to return on its own. `camel_error_diagnose` returns
+the same JSON fields as before. The new file, run and control tools are hidden by the `read-only` access
+level of the security layer; the server does not ask before writing a file, that is the MCP client's job.
+
+`camel-jbang-core` now depends on `camel-yaml-dsl-validator` for the source validation behind these tools.
+
=== camel-jbang (TUI)
The F8 AI panel now sends only a core subset of its `tui_*` tools to local providers (Ollama, or any
diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-mcp.adoc b/docs/user-manual/modules/ROOT/pages/camel-jbang-mcp.adoc
index 0695b686d787..7d7547aa00e6 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-mcp.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-mcp.adoc
@@ -251,6 +251,69 @@ The server exposes catalog tools for exploring components, validating routes, an
runtime introspection tools for inspecting and interacting with live Camel processes,
plus prompts that provide structured multi-step workflows.
+=== Authoring (shared with the Camel TUI)
+
+The tools an agent needs to build and edit an integration are defined once, in the Camel CLI, and exposed
+under the same `camel_` names by this server and by `camel tui --mcp` (see xref:camel-jbang-tui.adoc[]),
+so an agent gets the same Camel through either door. The tools are self-contained: the file tools take the
+project `directory` as an argument, the runtime tools take the integration `name` (or use the only one running).
+
+[cols="1,3",options="header"]
+|===
+| Tool | Description
+
+| `camel_catalog_doc`
+| Catalog documentation of a component, data format, language or EIP: description, options (with a keyword
+ filter), Maven coordinates, and for a component the rules of its endpoint URI spelled out (which options
+ are path parts, the YAML `uri` plus `parameters` form, placeholders, `RAW()`). For the `simple` language the
+ syntax rules, functions and operators (their count and names by group, or with `optionsFilter` the matching
+ ones with parameters and examples), and `docPage` serves the functions, operators, OGNL and advanced pages.
+ With `endpoint` it checks a URI against the catalog: unknown options with the closest real names, invalid
+ values, missing path parts, consumer options on a producer endpoint. `includeDoc=true` adds the AsciiDoc page.
+
+| `camel_catalog_find`
+| Finds components, data formats and languages by a protocol, product or other term that is not the exact
+ name (`mqtt`, `s3`, `snowflake`, `csv`), best match first with title and description.
+
+| `camel_validate_source`
+| Validates Camel YAML DSL or `.properties` source without writing: the YAML DSL schema (a misspelled option
+ such as `logLevel` instead of `loggingLevel`), endpoint URIs, simple expressions, and `camel.*` options.
+ Takes the content, or reads the file from the project directory.
+
+| `camel_get_files`
+| The source files of a project directory (name, size, type), or the content of one of them.
+
+| `camel_write_file`
+| Writes the complete content of a file in the project directory. YAML and `.properties` content is validated
+ first; invalid content is not written and the errors are returned (`validate=false` writes anyway). Only a
+ plain file name in the directory is accepted. Nobody is asked before the write: the MCP client (Claude Code,
+ Cursor and the others ask before a tool that is not read-only runs) is where the human sits, and the
+ `read-only` access level of the security layer hides the tool altogether.
+
+| `camel_run`
+| Starts an integration from a project directory with `camel run` in a separate process, in dev mode by
+ default so route files reload when written. Returns the pid, name and log file once the integration is up.
+
+| `camel_control`
+| Controls a running integration: `stop`, `kill`, `restart` (picks up edited files without dev mode),
+ `stop-routes`, `start-routes`, `reset-stats`.
+
+| `camel_get_log`
+| Recent log records of a running integration, newest first, filtered by level or text; a stack trace comes
+ as one record with a `detail` block.
+
+| `camel_get_errors`
+| The failed exchanges of a running integration: route, exchange, exception with stack trace, body and headers.
+
+| `camel_eval_expression`
+| Evaluates an expression (simple by default) in the running integration, or locally when none is named,
+ and returns the value (true/false for a predicate) or the syntax error, so an agent can check a simple
+ expression before writing it into a route.
+
+| `camel_error_diagnose`
+| See <<_error_diagnosis,Error Diagnosis>>; the same shared tool.
+|===
+
=== Catalog Exploration
[cols="1,3",options="header"]
@@ -427,7 +490,8 @@ The advisories are also browseable as MCP resources: `camel://security/advisorie
| `camel_validate_yaml_dsl`
| Validates a YAML DSL route definition against the Camel YAML DSL JSON schema. Checks for valid DSL elements,
correct route structure, and returns detailed schema validation errors including instance path, error type,
- and schema path.
+ and schema path. `camel_validate_source` (above) runs the same schema check plus the endpoint URI and simple
+ expression checks in one call, with the messages by line.
| `camel_transform_route`
| Assists with route DSL format transformation between YAML and XML.
diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
index c1726f578883..730c49973b5c 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-tui.adoc
@@ -951,7 +951,7 @@ cycles backward.
| Show the current model, or switch the session model.
| `/write [confirm\|auto\|live]` (`/w`)
-| Show or switch how file writes by the model (`tui_write_file`) are handled. `confirm` (default) shows the confirm dialog for every write, whatever the model passes; `auto` lets the model skip the dialog with `confirm=false`; `live` replays the edit in the Source editor so you watch it happen (see below). The mode lasts for the session.
+| Show or switch how file writes by the model (`camel_write_file`) are handled. `confirm` (default) shows the confirm dialog for every write, whatever the model passes; `auto` lets the model skip the dialog with `confirm=false`; `live` replays the edit in the Source editor so you watch it happen (see below). The mode lasts for the session.
| `/tools [auto\|core\|full]` (`/t`)
| Show which tool set is sent to the model, or switch it. `auto` (default) sends the core set to local providers and every tool to hosted ones; the choice is saved as `camel.tui.ai.tools`.
@@ -1053,16 +1053,16 @@ required. *F2* -> _MCP Info_ shows the port and the tool calls the agent makes.
header (so a web page cannot reach it) or that are not JSON.
Permissions: calls to the TUI's read-only tools (the `tui_get_*` tools, catalog documentation, expression
-evaluation, locate, validate) are approved without asking. So is `tui_write_file` while the write mode is
+evaluation, locate, validate) are approved without asking. So is `camel_write_file` while the write mode is
`confirm` or `live`, because the TUI itself asks before the file is touched (the diff dialog or the live replay
in the Source editor); with `/write auto` the permission popup is the only question and stays. A tool that
-changes anything else, such as `tui_control`, `tui_send_message` or `tui_execute_sql`, opens the same popup as
+changes anything else, such as `camel_control`, `tui_send_message` or `tui_execute_sql`, opens the same popup as
any other request; answering "Always allow" makes it a one-time question per tool. For anything else the agent
wants to do, such as editing a file with its own tools or running a command, a popup shows the agent's options;
*Enter* selects, *Esc* rejects that one call and lets the turn continue, and *Ctrl+C* cancels the whole turn.
-The preamble tells the agent to edit route sources through `tui_write_file` rather than its own file tools, so
+The preamble tells the agent to edit route sources through `camel_write_file` rather than its own file tools, so
that you see the diff or watch the edit; when it still asks to edit a file directly, the popup says so and *Esc*
-sends it back to `tui_write_file`.
+sends it back to `camel_write_file`.
"Always allow" choices are remembered by the agent for the session. The model, reasoning settings and any
"always allow" rules are configured in the agent, not in the TUI; `/model` only reports the agent in use.
@@ -1103,7 +1103,16 @@ To connect Claude Code to the TUI, add the MCP server to your project configurat
=== What AI Agents Can Do
-The MCP server exposes tools organized by purpose:
+The MCP server exposes two kinds of tools. The `camel_` tools are the Camel authoring set shared with the
+`camel mcp` server (see xref:camel-jbang-mcp.adoc[]): catalog documentation with the endpoint URI rules and the
+simple syntax (`camel_catalog_doc`, `camel_catalog_find`), source validation (`camel_validate_source`), reading
+and writing the source files (`camel_get_files`, `camel_write_file`), running an integration in dev mode and
+controlling it (`camel_run`, `camel_control`), its log and failed exchanges (`camel_get_log`, `camel_get_errors`),
+expression evaluation (`camel_eval_expression`) and error diagnosis (`camel_error_diagnose`). They are defined
+once in the Camel CLI, so an agent gets the same tools, names and answers through either server; in the TUI
+they work on the selected integration unless a `directory` or `name` argument says otherwise, and a write goes
+through the TUI's confirm dialog or live replay. The `tui_` tools are the ones only the TUI can offer, organized
+by purpose:
* *Observe* -- read the screen, get structured state, query tables/logs/errors/traces/topology/diagram/files,
list the running infra services (brokers, databases) and read their logs
@@ -1111,7 +1120,7 @@ The MCP server exposes tools organized by purpose:
* *Act* -- send test messages to endpoints, start/stop/restart routes, change log levels,
list and launch the bundled examples, start/stop/restart infra services, run any entry of
the *F2* actions menu by its label
-* *Edit* -- write a source file in the integration's source directory (`tui_write_file`), see below
+* *Edit* -- write a source file in the integration's source directory (`camel_write_file`), see below
* *Annotate* -- locate text and diagram nodes by coordinates, draw shapes (boxes, highlights,
arrows, underlines, text labels), show captions with typewriter animation
* *Present* -- take screenshots, record tape sessions, control demo pacing
@@ -1119,11 +1128,11 @@ The MCP server exposes tools organized by purpose:
=== Editing source files from an AI agent
The TUI is for prototyping, human and AI together, so an agent (the built-in *F8* panel or an
-external MCP client) can change the routes it is looking at. `tui_get_files` tells the agent where
+external MCP client) can change the routes it is looking at. `camel_get_files` tells the agent where
the sources are, which differs with how the integration was started (plain files, `--source-dir`,
an example extracted to a temporary folder, or an exported project), and whether editing makes
sense: `devMode` (changes are reloaded automatically), `temporary` (a copy that is lost when the
-integration stops) and an `editing` hint. `tui_write_file` then writes the complete new content of
+integration stops) and an `editing` hint. `camel_write_file` then writes the complete new content of
a file in that directory.
Every write is confirmed in the TUI first: a dialog names the file, the directory and the size of the
@@ -1136,22 +1145,22 @@ its own: `confirm=false` is honoured only after you switched to `/write auto` in
directory are accepted; the tool cannot write elsewhere, and there is no git integration, so the
worst case is a wrong route file in a folder you are watching.
-Before writing, an agent can check its content with `tui_validate_source`, which runs the same checks as
+Before writing, an agent can check its content with `camel_validate_source`, which runs the same checks as
the Source tab's save: YAML routes against the Camel YAML DSL schema (a misspelled option such as `logLevel`
instead of `loggingLevel` is reported) plus endpoint URIs and simple expressions, and `.properties` files
-against the catalog of `camel.*` and Spring Boot options. `tui_write_file` runs that validation itself and
+against the catalog of `camel.*` and Spring Boot options. `camel_write_file` runs that validation itself and
refuses to write an invalid file, returning the errors instead, so a model fixes them rather than the user
finding them in the log after the reload (`validate=false` writes anyway). Both tools are part of the core
tool set, so local models (Ollama) get them as well.
Simple expressions get two more helpers, because they are what a small model gets wrong most often
(functions belong inside the `${...}` placeholder, operators between placeholders: `${header.user} ?: 'Guest'`,
-not `${header.user ?: 'Guest'}`). `tui_catalog_doc` for the `simple` language returns those syntax rules
+not `${header.user ?: 'Guest'}`). `camel_catalog_doc` for the `simple` language returns those syntax rules
together with the catalog's functions and operators (their count and names by group, or with `optionsFilter`
the matching ones with parameters and examples), and `docPage` serves the operators, functions, OGNL and
-advanced documentation pages. `tui_eval_expression` evaluates an expression inside the running integration,
-like `camel cmd eval`, and returns the value or the parser error, so the agent can try an expression before
-it answers or writes it. Component lookups get the same treatment for endpoint URIs: every endpoint option
+advanced documentation pages. `camel_eval_expression` evaluates an expression inside the running integration,
+like `camel cmd eval`, or locally when no integration is selected, and returns the value or the parser error,
+so the agent can try an expression before it answers or writes it. Component lookups get the same treatment for endpoint URIs: every endpoint option
says whether it is part of the URI path or a query parameter, and the result spells out the URI rules for
that component (its path options, the `?option=value&option=value` form, the YAML `uri` plus `parameters`
form, placeholders, `RAW()`, and that component options belong in `application.properties`). With
@@ -1177,10 +1186,10 @@ and is told what was applied, what was skipped, and the content of the saved fil
While the replay pauses you can also ask the agent about the change it just made: *F8* opens the AI panel
with the question prefilled (`About edit 2 of 3:`), you complete it and press *Enter*. The waiting
-`tui_write_file` call returns to the agent with the question, the edits applied so far and the editor's
+`camel_write_file` call returns to the agent with the question, the edits applied so far and the editor's
content, and the agent answers in the same turn -- nothing is written meanwhile. Close the panel with *F8*
(or *Esc* to leave without asking) and the pause continues where it was. If your question makes the agent
-revise the change, its next `tui_write_file` of the same file continues in the editor from the current
+revise the change, its next `camel_write_file` of the same file continues in the editor from the current
content instead of starting over. If you save or discard without the agent being involved again, it is
told what became of the edit with your next question.
diff --git a/dsl/camel-jbang/camel-jbang-core/pom.xml b/dsl/camel-jbang/camel-jbang-core/pom.xml
index d080e201dc18..7c83c8ac3436 100644
--- a/dsl/camel-jbang/camel-jbang-core/pom.xml
+++ b/dsl/camel-jbang/camel-jbang-core/pom.xml
@@ -73,6 +73,11 @@
<groupId>org.apache.camel</groupId>
<artifactId>camel-xml-io-util</artifactId>
</dependency>
+ <!-- source validation for the shared AI authoring tools (CAMEL-24695) -->
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-yaml-dsl-validator</artifactId>
+ </dependency>
<!-- yaml -->
<dependency>
@@ -218,12 +223,12 @@
<version>${mcp-java-sdk-version}</version>
<scope>test</scope>
</dependency>
- <!-- MCP SDK schema validation needs networknt 2.0.1 (Dialects); wiremock transitively pulls 1.5.x -->
+ <!-- the YAML DSL validator (source validation for the AI authoring tools) and the MCP SDK schema validation
+ in the tests need networknt 2.0.1 (Dialects); wiremock transitively pulls 1.5.x -->
<dependency>
<groupId>com.networknt</groupId>
<artifactId>json-schema-validator</artifactId>
<version>${networknt-json-schema-validator-version}</version>
- <scope>test</scope>
</dependency>
</dependencies>
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
new file mode 100644
index 000000000000..e7d124590f1d
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/AuthoringTools.java
@@ -0,0 +1,469 @@
+/*
+ * 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.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+
+import org.apache.camel.dsl.jbang.core.common.RuntimeHelper;
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
+
+import static org.apache.camel.dsl.jbang.core.commands.ai.ToolDescriptor.tool;
+
+/**
+ * The neutral set of Camel authoring tools for AI agents, defined once and exposed by every Camel MCP server
+ * ({@code camel mcp} and {@code camel tui --mcp}) under the same {@code camel_} names, so an agent gets the same Camel
+ * through either door: catalog documentation with the URI rules and the simple syntax, source validation, reading and
+ * writing the source files of a project, running an integration in dev mode and reading its log and errors, evaluating
+ * an expression and diagnosing an error.
+ * <p>
+ * The tools are self-contained: a file tool takes the project {@code directory} as an argument (a server that has a
+ * selected integration fills it in through {@link ToolContext#setDefaultDirectory}), and a runtime tool takes the
+ * integration {@code name} (or uses the selected or the only running one). Writing a file is validated first and
+ * refused when the content is invalid; confirming a write with a human is the job of the client or of the TUI, not of
+ * these tools.
+ */
+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 DIRECTORY_DESC = "Project directory with the source files (default: the selected integration's)";
+
+ /** Files listed and read by the file tools; more than that and a directory is not an integration's sources. */
+ private static final int MAX_FILES = 99;
+
+ private AuthoringTools() {
+ }
+
+ /** Registers the authoring tools; called once by the {@link ToolRegistry}. */
+ static void register(Consumer<ToolDescriptor> registry) {
+ registry.accept(tool("camel_catalog_doc",
+ "Camel catalog documentation of a component, data format, language or EIP (description, options, "
+ + "Maven coordinates), with the URI rules of a component. For simple also its "
+ + "syntax rules, functions and operators: count and names by group, or with "
+ + "optionsFilter the matching ones with parameters and examples. endpoint "
+ + "validates a URI: unknown or invalid options, missing path.")
+ .param("name", "string", "Name, e.g. kafka, json-jackson, simple, timer, choice, split", false)
+ .param("endpoint", "string", "Endpoint URI to check, e.g. kafka:orders?brokers=host:9092", false)
+ .param("kind", "string", "component, dataformat, language or eip (auto-detected)", false)
+ .param("includeOptions", "boolean", "Include the options (default true)", false)
+ .param("includeDoc", "boolean", "Include the full AsciiDoc page (default false)", false)
+ .param("docPage", "string", "A language doc sub-page (simple: functions, operators, ognl, advanced)"
+ + " to return as text",
+ false)
+ .param("optionsFilter", "string", "Keyword to match in option names or descriptions", false)
+ .param("camelVersion", "string", VERSION_DESC, false)
+ .core(true)
+ .executor((ctx, args) -> {
+ applyVersion(ctx, args);
+ return CatalogDocs.catalogDoc(ctx.catalog(), args.get("name"), args.get("endpoint"),
+ args.get("kind"), args.get("optionsFilter"), bool(args, "includeOptions", true),
+ bool(args, "includeDoc", false), args.get("docPage")).toJson();
+ }));
+
+ registry.accept(tool("camel_catalog_find",
+ "Finds Camel components, data formats and languages by a protocol, product or other term that is not "
+ + "the exact name (mqtt, s3, snowflake, csv): best match first with title and "
+ + "description. camel_catalog_doc then gives the options of one.")
+ .param("term", "string", "What to look for, e.g. mqtt, s3, database, csv", true)
+ .param("kind", "string", "component, dataformat or language (default: all)", false)
+ .param("limit", "integer", "Maximum matches per kind (default 10)", false)
+ .param("camelVersion", "string", VERSION_DESC, false)
+ .executor((ctx, args) -> {
+ applyVersion(ctx, args);
+ return CatalogDocs.find(ctx.catalog(), args.get("term"), args.get("kind"),
+ integer(args, "limit", 10)).toJson();
+ }));
+
+ registry.accept(tool("camel_validate_source",
+ "Validates Camel YAML DSL or .properties source without writing: schema (misspelled options such as "
+ + "logLevel instead of loggingLevel), endpoint URIs, simple expressions, "
+ + "camel.* options. Use on content before writing it, or on an existing "
+ + "file (no content) to explain a reload error.")
+ .param("directory", "string", DIRECTORY_DESC, false)
+ .param("file", "string", "File name; picks the checks by extension, read when no content", true)
+ .param("content", "string", "The source to validate", false)
+ .param("camelVersion", "string", VERSION_DESC, false)
+ .core(true)
+ .executor((ctx, args) -> {
+ applyVersion(ctx, args);
+ String file = required(args, "file");
+ String content = args.get("content");
+ if (content == null) {
+ Path path = resolveFile(ctx.resolveDirectory(args.get("directory")), file);
+ if (!Files.isRegularFile(path)) {
+ throw new ToolExecutionException("No such file in the directory: " + file);
+ }
+ content = read(path);
+ }
+ return validate(ctx, file, content).toJson();
+ }));
+
+ registry.accept(tool("camel_get_files",
+ "The source files of a project directory: without file the list (name, size, type), with file its "
+ + "content. Use before editing to see the routes, configuration and other "
+ + "files of the integration.")
+ .param("directory", "string", DIRECTORY_DESC, false)
+ .param("file", "string", "File name to read; omitted lists the files", false)
+ .core(true)
+ .executor((ctx, args) -> {
+ Path dir = ctx.resolveDirectory(args.get("directory"));
+ String file = args.get("file");
+ if (file != null && !file.isBlank()) {
+ return readFile(dir, file).toJson();
+ }
+ return listFiles(dir).toJson();
+ }));
+
+ registry.accept(tool("camel_write_file",
+ "Writes the complete content of a file in the project directory. YAML and .properties content is "
+ + "validated first; invalid content is not written and the errors are returned. "
+ + "An integration running in dev mode reloads the change, otherwise restart it "
+ + "with camel_control.")
+ .param("directory", "string", DIRECTORY_DESC, false)
+ .param("file", "string", "File name, no path", true)
+ .param("content", "string", "The complete new content", true)
+ .param("validate", "boolean", "Validate before writing (default true)", false)
+ .param("camelVersion", "string", VERSION_DESC, false)
+ .readOnly(false)
+ .core(true)
+ .executor((ctx, args) -> {
+ applyVersion(ctx, args);
+ Path dir = ctx.resolveDirectory(args.get("directory"));
+ return writeFile(ctx, dir, required(args, "file"), required(args, "content"),
+ bool(args, "validate", true)).toJson();
+ }));
+
+ registry.accept(tool("camel_run",
+ "Starts an integration from a project directory with camel run in a separate process, in dev mode by "
+ + "default (route files reload when written). Returns the pid and log file once it is "
+ + "up; camel_get_log and camel_get_errors then tell how it does, camel_control stops it.")
+ .param("directory", "string", "Project directory to run in", true)
+ .param("files", "string", "Source files to run, comma-separated (default: every route file in the"
+ + " directory)",
+ false)
+ .param("name", "string", "Integration name (default: from the first file)", false)
+ .param("dev", "boolean", "Dev mode with reload on file change (default true)", false)
+ .readOnly(false)
+ .executor((ctx, args) -> {
+ Path dir = ctx.resolveDirectory(args.get("directory"));
+ List<String> files = new ArrayList<>();
+ String list = args.get("files");
+ if (list != null && !list.isBlank()) {
+ for (String f : list.split(",")) {
+ if (!f.isBlank()) {
+ files.add(f.trim());
+ }
+ }
+ }
+ JsonObject result = IntegrationLauncher.run(dir, files, args.get("name"), bool(args, "dev", true),
+ List.of());
+ if (result.get("pid") instanceof Long pid) {
+ ctx.selectProcess(pid);
+ }
+ return result.toJson();
+ }));
+
+ registry.accept(tool("camel_control",
+ "Controls a running integration: stop (graceful), kill, restart (picks up edited files without dev "
+ + "mode), stop-routes, start-routes, reset-stats (clears statistics, routes "
+ + "untouched). Never stop, kill or restart unless the user asked for it.")
+ .param("action", "string", "stop, kill, restart, stop-routes, start-routes or reset-stats", true)
+ .param("name", "string", NAME_DESC, false)
+ .readOnly(false)
+ .destructive(true)
+ .core(true)
+ .executor((ctx, args) -> {
+ selectProcess(ctx, args);
+ return IntegrationLauncher.control(ctx, required(args, "action"));
+ }));
+
+ registry.accept(tool("camel_get_log",
+ "Recent log records of a running integration, newest first, with optional filtering; a stack trace "
+ + "comes as one record with a detail block.")
+ .param("name", "string", NAME_DESC, false)
+ .param("limit", "integer", "Maximum records to return (default 50)", false)
+ .param("filter", "string", "Case-insensitive substring filter on the message", false)
+ .param("level", "string", "Only this log level (INFO, WARN, ERROR, DEBUG, TRACE)", false)
+ .core(true)
+ .executor((ctx, args) -> {
+ RuntimeHelper.ProcessInfo p = selectProcess(ctx, args);
+ return LogFileReader.read(ctx.pid(), p != null ? p.name() : null, integer(args, "limit", 50),
+ args.get("filter"), args.get("level")).toJson();
+ }));
+
+ registry.accept(tool("camel_get_errors",
+ "The failed exchanges of a running integration: routeId, exchangeId, exception with stack trace, "
+ + "body and headers.")
+ .param("name", "string", NAME_DESC, false)
+ .core(true)
+ .executor((ctx, args) -> {
+ selectProcess(ctx, args);
+ JsonObject errors = ctx.readErrorFile();
+ return errors != null ? errors.toJson() : "No errors captured.";
+ }));
+
+ registry.accept(tool("camel_eval_expression",
+ "Evaluates an expression: in the running integration when there is one, else locally. Returns the "
+ + "value (true/false for a predicate) or the syntax error, so check simple "
+ + "before answering or writing it.")
+ .param("expression", "string", "e.g. ${random(1,10)} or ${body} ?: 'none'", true)
+ .param("language", "string", "simple (default), jsonpath, xpath, jq", false)
+ .param("body", "string", "Message body", false)
+ .param("name", "string", NAME_DESC, false)
+ .core(true)
+ .executor((ctx, args) -> {
+ String name = args.get("name");
+ if (name != null && !name.isBlank()) {
+ ctx.selectProcess(name);
+ } else {
+ ctx.selectSingleProcessIfNone();
+ }
+ return ExpressionEvaluator.evaluate(ctx, args.get("language"), required(args, "expression"),
+ args.get("body")).toJson();
+ }));
+
+ registry.accept(tool("camel_error_diagnose",
+ "Diagnoses a Camel error from a stack trace or error message: the known exceptions in it with common "
+ + "causes and suggested fixes, the components and EIPs it mentions with "
+ + "documentation links, and the route id.")
+ .param("error", "string", "The stack trace or error message", true)
+ .param("camelVersion", "string", VERSION_DESC, false)
+ .core(true)
+ .executor((ctx, args) -> {
+ applyVersion(ctx, args);
+ return ErrorDiagnoser.diagnose(required(args, "error"), ctx.catalog()).toJson();
+ }));
+ }
+
+ // ---- shared logic, also used by the TUI over its own selection ----
+
+ /** Validates source content for the context's Camel version, as {@code camel_validate_source} answers it. */
+ public static JsonObject validate(ToolContext ctx, String file, String content) {
+ if (!SourceValidator.isValidatableFile(file)) {
+ throw new ToolExecutionException(
+ "No validation for " + file + ": only YAML routes and .properties files are validated");
+ }
+ List<String> errors = SourceValidator.validate(file, content, ctx.catalog(), ctx.propertyLineValidator());
+ JsonObject result = new JsonObject();
+ result.put("valid", errors.isEmpty());
+ result.put("file", file);
+ result.put("errors", new JsonArray(errors));
+ result.put("message", errors.isEmpty()
+ ? "The source is valid"
+ : errors.size() + " problem(s) found; fix them before writing the file");
+ return result;
+ }
+
+ /** Writes a file after validating it, as {@code camel_write_file} does; no confirmation is asked here. */
+ public static JsonObject writeFile(ToolContext ctx, Path dir, String file, String content, boolean validate) {
+ Path path = resolveFile(dir, file);
+ boolean exists = Files.exists(path);
+ if (exists && !Files.isRegularFile(path)) {
+ throw new ToolExecutionException(file + " is not a regular file");
+ }
+ if (validate && SourceValidator.isValidatableFile(file)) {
+ List<String> errors = SourceValidator.validate(file, content, ctx.catalog(), ctx.propertyLineValidator());
+ if (!errors.isEmpty()) {
+ JsonObject result = new JsonObject();
+ result.put("status", "invalid");
+ result.put("file", file);
+ result.put("errors", new JsonArray(errors));
+ result.put("message", "The file was not written: the content has validation errors. Fix them and"
+ + " call camel_write_file again (validate=false writes it anyway).");
+ return result;
+ }
+ }
+ try {
+ Files.writeString(path, content, StandardCharsets.UTF_8);
+ } catch (IOException e) {
+ throw new ToolExecutionException("Failed to write " + path + ": " + e.getMessage());
+ }
+ JsonObject result = new JsonObject();
+ result.put("status", exists ? "overwritten" : "created");
+ result.put("file", file);
+ result.put("directory", dir.toString());
+ result.put("lines", content.isEmpty() ? 0 : (int) content.lines().count());
+ result.put("bytes", content.getBytes(StandardCharsets.UTF_8).length);
+ result.put("message", "An integration running the file in dev mode reloads it now; otherwise restart the"
+ + " integration for the change to take effect.");
+ return result;
+ }
+
+ /** The files of a project directory, as {@code camel_get_files} lists them. */
+ public static JsonObject listFiles(Path dir) {
+ JsonArray files = new JsonArray();
+ try (Stream<Path> stream = Files.list(dir)) {
+ stream.filter(Files::isRegularFile)
+ .sorted((a, b) -> a.getFileName().toString().compareToIgnoreCase(b.getFileName().toString()))
+ .limit(MAX_FILES)
+ .forEach(p -> {
+ JsonObject entry = new JsonObject();
+ entry.put("name", p.getFileName().toString());
+ entry.put("size", formatSize(size(p)));
+ entry.put("type", fileType(p.getFileName().toString()));
+ files.add(entry);
+ });
+ } catch (IOException e) {
+ throw new ToolExecutionException("Cannot list " + dir + ": " + e.getMessage());
+ }
+ JsonObject result = new JsonObject();
+ result.put("directory", dir.toString());
+ result.put("files", files);
+ result.put("totalFiles", files.size());
+ if (files.isEmpty()) {
+ result.put("message", "The directory has no files");
+ }
+ return result;
+ }
+
+ /** One file of a project directory with its content, as {@code camel_get_files} reads it. */
+ public static JsonObject readFile(Path dir, String file) {
+ Path path = resolveFile(dir, file);
+ if (!Files.isRegularFile(path)) {
+ throw new ToolExecutionException("No such file in the directory: " + file);
+ }
+ JsonObject result = new JsonObject();
+ result.put("file", file);
+ result.put("directory", dir.toString());
+ result.put("size", formatSize(size(path)));
+ result.put("type", fileType(file));
+ result.put("content", read(path));
+ return result;
+ }
+
+ /** A plain file name inside the directory; anything else (a path, a parent reference) is refused. */
+ static Path resolveFile(Path dir, String file) {
+ if (file == null || file.isBlank()) {
+ throw new ToolExecutionException("file is required");
+ }
+ Path path = dir.resolve(file).normalize();
+ if (!path.startsWith(dir) || !dir.equals(path.getParent())) {
+ throw new ToolExecutionException("file must be a plain file name in the directory " + dir);
+ }
+ return path;
+ }
+
+ private static String read(Path path) {
+ try {
+ return Files.readString(path, StandardCharsets.UTF_8);
+ } catch (IOException e) {
+ throw new ToolExecutionException("Cannot read " + path + ": " + e.getMessage());
+ }
+ }
+
+ private static long size(Path p) {
+ try {
+ return Files.size(p);
+ } catch (IOException e) {
+ return 0;
+ }
+ }
+
+ static String formatSize(long bytes) {
+ if (bytes < 1024) {
+ return bytes + " B";
+ }
+ if (bytes < 1024 * 1024) {
+ return String.format(Locale.ROOT, "%.1f KB", bytes / 1024.0);
+ }
+ return String.format(Locale.ROOT, "%.1f MB", bytes / (1024.0 * 1024));
+ }
+
+ static String fileType(String name) {
+ String lower = name.toLowerCase(Locale.ROOT);
+ int dot = lower.lastIndexOf('.');
+ if (dot < 0) {
+ return "other";
+ }
+ return switch (lower.substring(dot + 1)) {
+ case "yaml", "yml" -> "yaml";
+ case "xml" -> "xml";
+ case "java" -> "java";
+ case "properties" -> "properties";
+ case "groovy", "js", "kts", "py" -> "script";
+ case "json" -> "json";
+ case "md", "adoc", "txt" -> "text";
+ default -> "other";
+ };
+ }
+
+ // ---- argument helpers ----
+
+ private static void applyVersion(ToolContext ctx, Map<String, String> args) {
+ String version = args.get("camelVersion");
+ if (version != null && !version.isBlank()) {
+ ctx.setCamelVersion(version.trim());
+ }
+ }
+
+ /**
+ * Selects the process the call names, else keeps the selected one, else the only one running.
+ *
+ * @throws ToolExecutionException when no process can be selected
+ */
+ private static RuntimeHelper.ProcessInfo selectProcess(ToolContext ctx, Map<String, String> args) {
+ String name = args.get("name");
+ if (name != null && !name.isBlank()) {
+ ctx.selectProcess(name);
+ } else if (!ctx.selectSingleProcessIfNone()) {
+ throw new ToolExecutionException(
+ "No integration selected: pass name (an integration name or pid); list_processes shows"
+ + " what runs, camel_run starts one");
+ }
+ for (RuntimeHelper.ProcessInfo p : RuntimeHelper.discoverProcesses()) {
+ if (p.pid() == ctx.pid()) {
+ return p;
+ }
+ }
+ return null;
+ }
+
+ private static String required(Map<String, String> args, String key) {
+ String value = args.get(key);
+ if (value == null || value.isBlank()) {
+ throw new ToolExecutionException(key + " is required");
+ }
+ return value;
+ }
+
+ static boolean bool(Map<String, String> args, String key, boolean defaultValue) {
+ String value = args.get(key);
+ return value == null || value.isBlank() ? defaultValue : Boolean.parseBoolean(value.trim());
+ }
+
+ static int integer(Map<String, String> args, String key, int defaultValue) {
+ String value = args.get(key);
+ if (value == null || value.isBlank()) {
+ return defaultValue;
+ }
+ try {
+ return Integer.parseInt(value.trim());
+ } catch (NumberFormatException e) {
+ return defaultValue;
+ }
+ }
+}
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
new file mode 100644
index 000000000000..097b91c6e491
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/CatalogDocs.java
@@ -0,0 +1,739 @@
+/*
+ * 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.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.apache.camel.catalog.CamelCatalog;
+import org.apache.camel.catalog.EndpointValidationResult;
+import org.apache.camel.tooling.model.BaseModel;
+import org.apache.camel.tooling.model.BaseOptionModel;
+import org.apache.camel.tooling.model.ComponentModel;
+import org.apache.camel.tooling.model.DataFormatModel;
+import org.apache.camel.tooling.model.EipModel;
+import org.apache.camel.tooling.model.LanguageModel;
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
+
+/**
+ * The catalog documentation an AI agent authoring an integration asks for: a component, data format, language or EIP
+ * with its options, the rules of an endpoint URI spelled out, the simple language's syntax, functions and operators,
+ * and an endpoint URI checked against the catalog. Written for what a small model gets wrong most (a path option as a
+ * query parameter, an operator inside a placeholder), and shared by the {@code camel_catalog_doc} tool of every Camel
+ * MCP server.
+ */
+public final class CatalogDocs {
+
+ /** The sub-pages of a language's documentation (simple has functions, operators, ognl and advanced). */
+ private static final List<String> LANGUAGE_DOC_PAGES = List.of("functions", "operators", "ognl", "advanced");
+
+ /**
+ * The rules a small model gets wrong most: functions live inside the placeholder, operators between placeholders.
+ * Sent with the simple language result so an answer's examples follow the same shape as the catalog's.
+ */
+ public static final String SIMPLE_SYNTAX = "Values and functions go inside ${...}: ${body}, ${header.name},"
+ + " ${exchangeProperty.name}, ${variable.name}, ${random(1,10)},"
+ + " ${date:now:yyyy-MM-dd}. Operators go BETWEEN placeholders, with spaces,"
+ + " never inside one: ${header.foo} == 'bar', ${header.user} ?: 'Guest',"
+ + " ${header.n} > 5 && ${body} != null, ${header.a} == 'x' ? 'yes' : 'no'."
+ + " Text literals are in single quotes; text outside ${...} is kept as is:"
+ + " Hello ${header.name}. Nesting works: ${header.${header.key}}.";
+
+ private CatalogDocs() {
+ }
+
+ /**
+ * The documentation of a catalog artifact, or the check of an endpoint URI when {@code endpoint} is given.
+ *
+ * @param catalog the catalog of the Camel version to answer for
+ * @param name the artifact name (kafka, json-jackson, simple, choice); ignored when endpoint is given
+ * @param endpoint an endpoint URI to validate instead of documenting an artifact
+ * @param kind component, dataformat, language or eip; null to detect
+ * @param optionsFilter keyword to match in option names, descriptions and groups; also picks the simple functions
+ * and operators to list in full
+ * @param includeOptions whether to list the options
+ * @param includeDoc whether to add the full AsciiDoc page
+ * @param docPage a language doc sub-page (simple: functions, operators, ognl, advanced) to return as text
+ * @return the JSON result, an {@code error} object when nothing matches
+ */
+ public static JsonObject catalogDoc(
+ CamelCatalog catalog, String name, String endpoint, String kind, String optionsFilter,
+ boolean includeOptions, boolean includeDoc, String docPage) {
+ if (endpoint != null && !endpoint.isBlank()) {
+ return validateEndpoint(catalog, endpoint.trim());
+ }
+ if (name == null || name.isBlank()) {
+ return error("'name' or 'endpoint' parameter is required");
+ }
+ String page = docPage != null ? docPage.trim().toLowerCase(Locale.ROOT) : null;
+ String lowerFilter = optionsFilter != null && !optionsFilter.isBlank() ? optionsFilter.toLowerCase() : null;
+
+ if (kind == null || "component".equals(kind)) {
+ ComponentModel cm = catalog.componentModel(name);
+ if (cm != null) {
+ String doc = includeDoc ? catalog.asciiDoc(name + "-component") : null;
+ return componentDoc(cm, lowerFilter, includeOptions, doc);
+ }
+ if (kind != null) {
+ return notFound("Component", name, catalog.suggestComponentNames(name, 5));
+ }
+ }
+ if (kind == null || "dataformat".equals(kind)) {
+ DataFormatModel dm = catalog.dataFormatModel(name);
+ if (dm != null) {
+ String doc = includeDoc ? catalog.asciiDoc(name + "-dataformat") : null;
+ return dataFormatDoc(dm, lowerFilter, includeOptions, doc);
+ }
+ if (kind != null) {
+ return notFound("Data format", name, catalog.suggestDataFormatNames(name, 5));
+ }
+ }
+ if (kind == null || "language".equals(kind)) {
+ LanguageModel lm = catalog.languageModel(name);
+ if (lm != null) {
+ String doc = null;
+ if (page != null && !page.isEmpty()) {
+ doc = catalog.asciiDoc(name + "-" + page);
+ if (doc == null) {
+ JsonObject err = error("No doc page '" + page + "' for language " + name);
+ err.put("docPages", new JsonArray(languageDocPages(catalog, name)));
+ return err;
+ }
+ } else if (includeDoc) {
+ doc = catalog.asciiDoc(name + "-language");
+ }
+ boolean docPageOnly = page != null && !page.isEmpty();
+ return languageDoc(lm, lowerFilter, includeOptions, doc, languageDocPages(catalog, name), docPageOnly);
+ }
+ if (kind != null) {
+ return notFound("Language", name, catalog.suggestLanguageNames(name, 5));
+ }
+ }
+ if (kind == null || "eip".equals(kind)) {
+ EipModel em = catalog.eipModel(name);
+ if (em != null) {
+ String doc = includeDoc ? catalog.asciiDoc(name + "-eip") : null;
+ return eipDoc(em, lowerFilter, includeOptions, doc);
+ }
+ if (kind != null) {
+ return error("EIP not found: " + name);
+ }
+ }
+ List<String> suggestions = new ArrayList<>(catalog.suggestComponentNames(name, 5));
+ suggestions.addAll(catalog.suggestDataFormatNames(name, 3));
+ suggestions.addAll(catalog.suggestLanguageNames(name, 3));
+ return notFound("Artifact", name, suggestions);
+ }
+
+ /**
+ * Finds the catalog artifacts matching a term that need not be a name: a protocol (mqtt, amqp), a product (s3,
+ * snowflake) or a word of the title. Best match first, with the title and description so the caller can pick.
+ *
+ * @param catalog the catalog
+ * @param term what to look for
+ * @param kind component, dataformat or language; null for all three
+ * @param limit maximum matches per kind
+ */
+ public static JsonObject find(CamelCatalog catalog, String term, String kind, int limit) {
+ if (term == null || term.isBlank()) {
+ return error("'term' parameter is required");
+ }
+ int max = limit > 0 ? limit : 10;
+ JsonObject result = new JsonObject();
+ result.put("term", term);
+ JsonArray matches = new JsonArray();
+ if (kind == null || "component".equals(kind)) {
+ for (String name : catalog.suggestComponentNames(term, max)) {
+ ComponentModel m = catalog.componentModel(name);
+ if (m != null) {
+ JsonObject o = summary("component", m.getScheme(), m.getTitle(), m.getDescription(), m.getLabel());
+ o.put("syntax", m.getSyntax());
+ matches.add(o);
+ }
+ }
+ }
+ if (kind == null || "dataformat".equals(kind)) {
+ for (String name : catalog.suggestDataFormatNames(term, max)) {
+ DataFormatModel m = catalog.dataFormatModel(name);
+ if (m != null) {
+ matches.add(summary("dataformat", m.getName(), m.getTitle(), m.getDescription(), m.getLabel()));
+ }
+ }
+ }
+ if (kind == null || "language".equals(kind)) {
+ for (String name : catalog.suggestLanguageNames(term, max)) {
+ LanguageModel m = catalog.languageModel(name);
+ if (m != null) {
+ matches.add(summary("language", m.getName(), m.getTitle(), m.getDescription(), m.getLabel()));
+ }
+ }
+ }
+ result.put("matches", matches);
+ result.put("count", matches.size());
+ if (matches.isEmpty()) {
+ result.put("message", "Nothing in the catalog matches '" + term + "'");
+ } else {
+ result.put("message", "Best match first; camel_catalog_doc gives the options of one");
+ }
+ return result;
+ }
+
+ private static JsonObject summary(String kind, String name, String title, String description, String label) {
+ JsonObject o = new JsonObject();
+ o.put("kind", kind);
+ o.put("name", name);
+ o.put("title", title);
+ if (description != null) {
+ o.put("description", description);
+ }
+ if (label != null) {
+ o.put("label", label);
+ }
+ return o;
+ }
+
+ /**
+ * Checks an endpoint URI against the catalog the way the YAML validator does on a write: the component is taken
+ * from the scheme, the path is parsed against the component's syntax and every option is checked. The problems come
+ * back in words, with the closest real option name or the allowed values, and the options the URI uses come with
+ * their documentation so a follow-up needs no second call.
+ */
+ public static JsonObject validateEndpoint(CamelCatalog catalog, String endpoint) {
+ int colon = endpoint.indexOf(':');
+ if (colon <= 0) {
+ return error("Not an endpoint URI (scheme:path?options expected): " + endpoint);
+ }
+ String scheme = endpoint.substring(0, colon).toLowerCase(Locale.ROOT);
+ ComponentModel cm = catalog.componentModel(scheme);
+ if (cm == null) {
+ JsonObject err = error("Camel has no component named '" + scheme + "'");
+ List<String> similar = catalog.suggestComponentNames(scheme, 5);
+ if (!similar.isEmpty()) {
+ err.put("suggestions", new JsonArray(similar));
+ err.put("hint", "Check again with one of those schemes, e.g. '" + similar.get(0)
+ + endpoint.substring(colon) + "'.");
+ }
+ return err;
+ }
+ JsonObject result = new JsonObject();
+ result.put("kind", "component");
+ result.put("name", scheme);
+ result.put("title", cm.getTitle());
+ result.put("endpoint", endpoint);
+ if (cm.getSyntax() != null) {
+ result.put("syntax", cm.getSyntax());
+ result.put("uriSyntax", uriSyntax(cm));
+ }
+ EndpointValidationResult validation;
+ try {
+ validation = catalog.validateEndpointProperties(endpoint, false, false, false);
+ } catch (Exception e) {
+ result.put("valid", false);
+ result.put("problems", new JsonArray(List.of("Cannot parse the URI: " + e.getMessage())));
+ return result;
+ }
+ List<String> problems = endpointProblems(validation);
+ List<String> warnings = new ArrayList<>();
+ if (validation.getDeprecated() != null) {
+ for (String name : validation.getDeprecated()) {
+ warnings.add("Option '" + name + "' is deprecated");
+ }
+ }
+ if (validation.getDefaultValues() != null) {
+ for (Map.Entry<String, String> entry : validation.getDefaultValues().entrySet()) {
+ warnings.add("Option '" + entry.getKey() + "' is set to its default value " + entry.getValue());
+ }
+ }
+ result.put("valid", problems.isEmpty());
+ result.put("problems", new JsonArray(problems));
+ if (!warnings.isEmpty()) {
+ result.put("warnings", new JsonArray(warnings));
+ }
+ // the options the URI uses (path parts included), with their catalog documentation
+ Map<String, String> used;
+ try {
+ used = catalog.endpointProperties(endpoint);
+ } catch (Exception e) {
+ used = Map.of();
+ }
+ JsonArray options = new JsonArray();
+ if (cm.getEndpointOptions() != null) {
+ for (BaseOptionModel opt : cm.getEndpointOptions()) {
+ if (used.containsKey(opt.getName())) {
+ JsonObject o = optionToJson(opt, "endpoint");
+ o.put("value", used.get(opt.getName()));
+ options.add(o);
+ }
+ }
+ }
+ result.put("usedOptions", options);
+ result.put("message", problems.isEmpty()
+ ? "The URI is valid for the " + scheme + " component"
+ : problems.size() + " problem(s); fix them before using the URI");
+ return result;
+ }
+
+ /** The problems of an endpoint validation in words, one per entry, with suggestions and allowed values. */
+ public static List<String> endpointProblems(EndpointValidationResult r) {
+ List<String> problems = new ArrayList<>();
+ if (r.getSyntaxError() != null) {
+ problems.add("Syntax error: " + r.getSyntaxError());
+ }
+ if (r.getUnknownComponent() != null) {
+ problems.add("Unknown component: " + r.getUnknownComponent());
+ }
+ if (r.getIncapable() != null) {
+ problems.add("Cannot validate: " + r.getIncapable());
+ }
+ if (r.getUnknown() != null) {
+ for (String name : r.getUnknown()) {
+ StringBuilder sb = new StringBuilder("Unknown option '").append(name).append("'");
+ // the catalog suggests the closest names itself (edit distance, CAMEL-24666)
+ String[] suggestions = r.getUnknownSuggestions() != null ? r.getUnknownSuggestions().get(name) : null;
+ if (suggestions != null && suggestions.length > 0) {
+ sb.append(". Did you mean: ").append(Arrays.asList(suggestions));
+ }
+ problems.add(sb.toString());
+ }
+ }
+ if (r.getRequired() != null) {
+ for (String name : r.getRequired()) {
+ problems.add("Missing required option '" + name + "'");
+ }
+ }
+ if (r.getInvalidEnum() != null) {
+ for (Map.Entry<String, String> entry : r.getInvalidEnum().entrySet()) {
+ StringBuilder sb = new StringBuilder("Invalid value '").append(entry.getValue())
+ .append("' for option '").append(entry.getKey()).append("'");
+ String[] choices = r.getInvalidEnumChoices() != null ? r.getInvalidEnumChoices().get(entry.getKey()) : null;
+ if (choices != null) {
+ sb.append(". Possible values: ").append(Arrays.asList(choices));
+ }
+ problems.add(sb.toString());
+ }
+ }
+ addInvalid(problems, r.getInvalidBoolean(), "boolean");
+ addInvalid(problems, r.getInvalidInteger(), "integer");
+ addInvalid(problems, r.getInvalidNumber(), "number");
+ addInvalid(problems, r.getInvalidDuration(), "duration");
+ addInvalid(problems, r.getInvalidReference(), "reference (#bean)");
+ addInvalid(problems, r.getInvalidMap(), "map");
+ addInvalid(problems, r.getInvalidArray(), "array");
+ if (r.getNotConsumerOnly() != null) {
+ for (String name : r.getNotConsumerOnly()) {
+ problems.add("Option '" + name + "' is a producer option; not for a from (consumer) endpoint");
+ }
+ }
+ if (r.getNotProducerOnly() != null) {
+ for (String name : r.getNotProducerOnly()) {
+ problems.add("Option '" + name + "' is a consumer option; not for a to (producer) endpoint");
+ }
+ }
+ return problems;
+ }
+
+ private static void addInvalid(List<String> problems, Map<String, String> invalid, String type) {
+ if (invalid != null) {
+ for (Map.Entry<String, String> entry : invalid.entrySet()) {
+ problems.add("Invalid " + type + " value '" + entry.getValue() + "' for option '" + entry.getKey() + "'");
+ }
+ }
+ }
+
+ private static JsonObject error(String message) {
+ JsonObject err = new JsonObject();
+ err.put("error", message);
+ return err;
+ }
+
+ /**
+ * Error for a catalog lookup that found nothing, with the names the catalog suggests for the term (a protocol or
+ * product name such as mqtt or s3) so the next call can use one of them.
+ */
+ private static JsonObject notFound(String kind, String name, List<String> suggestions) {
+ JsonObject err = error(kind + " not found: " + name);
+ if (!suggestions.isEmpty()) {
+ err.put("suggestions", new JsonArray(suggestions));
+ }
+ return err;
+ }
+
+ private static void addCommonModelFields(JsonObject result, BaseModel<?> model) {
+ if (model.getFirstVersion() != null) {
+ result.put("since", model.getFirstVersion());
+ }
+ if (model.getSupportLevel() != null) {
+ result.put("supportLevel", model.getSupportLevel().name());
+ }
+ if (model.isNativeSupported()) {
+ result.put("nativeSupported", true);
+ }
+ if (model.isDeprecated()) {
+ result.put("deprecated", true);
+ if (model.getDeprecatedSince() != null) {
+ result.put("deprecatedSince", model.getDeprecatedSince());
+ }
+ if (model.getDeprecationNote() != null) {
+ result.put("deprecationNote", model.getDeprecationNote());
+ }
+ }
+ }
+
+ /**
+ * The rules of an endpoint URI for this component, spelled out with its own path parts: what a small model gets
+ * wrong most is a path option written as a query parameter or the other way round, and the YAML form.
+ */
+ public static String uriSyntax(ComponentModel model) {
+ List<String> path = new ArrayList<>();
+ if (model.getEndpointOptions() != null) {
+ for (BaseOptionModel opt : model.getEndpointOptions()) {
+ if ("path".equals(opt.getKind())) {
+ path.add(opt.getName());
+ }
+ }
+ }
+ StringBuilder sb = new StringBuilder();
+ sb.append("URI: ").append(model.getSyntax()).append("?option=value&option=value. ");
+ if (path.isEmpty()) {
+ sb.append("The path has no options; ");
+ } else {
+ sb.append("The path options (").append(String.join(", ", path))
+ .append(") go in the path, never as ?name=value; ");
+ }
+ sb.append("every other endpoint option is a query parameter after ?, separated by &.")
+ .append(" In YAML DSL: uri: ").append(model.getScheme()).append(":<path> plus a parameters: map of the")
+ .append(" query options (or the full URI in uri). Values may use {{property.placeholders}};")
+ .append(" wrap a value containing & or + in RAW(value). Component options (scope component) are")
+ .append(" set in application.properties as camel.component.").append(model.getScheme())
+ .append(".<option>=value, not on the URI.");
+ return sb.toString();
+ }
+
+ private static JsonObject componentDoc(ComponentModel model, String filter, boolean includeOptions, String doc) {
+ JsonObject result = new JsonObject();
+ result.put("kind", "component");
+ result.put("name", model.getScheme());
+ result.put("title", model.getTitle());
+ result.put("description", model.getDescription());
+ if (model.getLabel() != null) {
+ result.put("label", model.getLabel());
+ }
+ if (model.getSyntax() != null) {
+ result.put("syntax", model.getSyntax());
+ result.put("uriSyntax", uriSyntax(model));
+ }
+ result.put("consumerOnly", model.isConsumerOnly());
+ result.put("producerOnly", model.isProducerOnly());
+ result.put("remote", model.isRemote());
+ result.put("groupId", model.getGroupId());
+ result.put("artifactId", model.getArtifactId());
+ addCommonModelFields(result, model);
+
+ if (includeOptions) {
+ JsonArray options = new JsonArray();
+ if (model.getComponentOptions() != null) {
+ for (BaseOptionModel opt : model.getComponentOptions()) {
+ if (matchesOptionFilter(opt, filter)) {
+ options.add(optionToJson(opt, "component"));
+ }
+ }
+ }
+ if (model.getEndpointOptions() != null) {
+ for (BaseOptionModel opt : model.getEndpointOptions()) {
+ if (matchesOptionFilter(opt, filter)) {
+ options.add(optionToJson(opt, "endpoint"));
+ }
+ }
+ }
+ result.put("options", options);
+ result.put("matchedOptions", options.size());
+ }
+ if (doc != null) {
+ result.put("doc", doc);
+ }
+ return result;
+ }
+
+ private static JsonObject dataFormatDoc(DataFormatModel model, String filter, boolean includeOptions, String doc) {
+ JsonObject result = new JsonObject();
+ result.put("kind", "dataformat");
+ result.put("name", model.getName());
+ result.put("title", model.getTitle());
+ result.put("description", model.getDescription());
+ if (model.getLabel() != null) {
+ result.put("label", model.getLabel());
+ }
+ result.put("groupId", model.getGroupId());
+ result.put("artifactId", model.getArtifactId());
+ addCommonModelFields(result, model);
+ if (includeOptions) {
+ result.put("options", filteredOptions(model.getOptions(), filter));
+ result.put("matchedOptions", ((JsonArray) result.get("options")).size());
+ }
+ if (doc != null) {
+ result.put("doc", doc);
+ }
+ return result;
+ }
+
+ private static List<String> languageDocPages(CamelCatalog catalog, String name) {
+ List<String> pages = new ArrayList<>();
+ for (String page : LANGUAGE_DOC_PAGES) {
+ if (catalog.asciiDoc(name + "-" + page) != null) {
+ pages.add(page);
+ }
+ }
+ return pages;
+ }
+
+ private static JsonObject languageDoc(
+ LanguageModel model, String filter, boolean includeOptions, String doc, List<String> docPages,
+ boolean docPageOnly) {
+ JsonObject result = new JsonObject();
+ result.put("kind", "language");
+ result.put("name", model.getName());
+ result.put("title", model.getTitle());
+ result.put("description", model.getDescription());
+ if (model.getLabel() != null) {
+ result.put("label", model.getLabel());
+ }
+ result.put("groupId", model.getGroupId());
+ result.put("artifactId", model.getArtifactId());
+ addCommonModelFields(result, model);
+
+ // a requested doc page is the answer; the options, functions and operators would only add tokens around it
+ if (includeOptions && !docPageOnly) {
+ result.put("options", filteredOptions(model.getOptions(), filter));
+ result.put("matchedOptions", ((JsonArray) result.get("options")).size());
+ }
+ if (!docPageOnly) {
+ addLanguageFunctions(result, model, filter);
+ }
+ if ("simple".equals(model.getName()) || "csimple".equals(model.getName())) {
+ result.put("syntax", SIMPLE_SYNTAX);
+ }
+ if (!docPages.isEmpty()) {
+ result.put("docPages", new JsonArray(docPages));
+ result.put("docPagesHint", "docPage=<name> returns that documentation page as text");
+ }
+ if (doc != null) {
+ result.put("doc", doc);
+ }
+ return result;
+ }
+
+ /**
+ * The functions and operators of a language that has them (simple): without a filter their count and names by
+ * group, which answers "what is there" in a few hundred tokens; with a filter the matching ones in full, with
+ * parameters and examples, the way the options are filtered.
+ */
+ private static void addLanguageFunctions(JsonObject result, LanguageModel model, String filter) {
+ List<LanguageModel.LanguageFunctionModel> functions = model.getFunctions();
+ if (functions != null && !functions.isEmpty()) {
+ result.put("functionCount", functions.size());
+ if (filter != null) {
+ JsonArray arr = new JsonArray();
+ for (LanguageModel.LanguageFunctionModel fn : functions) {
+ if (matchesOptionFilter(fn, filter)
+ || (fn.getDisplayName() != null && fn.getDisplayName().toLowerCase().contains(filter))) {
+ arr.add(functionToJson(fn));
+ }
+ }
+ result.put("functions", arr);
+ result.put("matchedFunctions", arr.size());
+ } else {
+ Map<String, JsonArray> groups = new TreeMap<>();
+ for (LanguageModel.LanguageFunctionModel fn : functions) {
+ String group = fn.getGroup() != null ? fn.getGroup() : "other";
+ groups.computeIfAbsent(group, g -> new JsonArray()).add(fn.getName());
+ }
+ result.put("functionGroups", new JsonObject(groups));
+ result.put("functionsHint", "optionsFilter with a function name, a group above or a word from its"
+ + " description returns the matching functions with their parameters"
+ + " and examples");
+ }
+ }
+ List<LanguageModel.LanguageOperatorModel> operators = model.getOperators();
+ if (operators != null && !operators.isEmpty()) {
+ result.put("operatorCount", operators.size());
+ if (filter != null) {
+ JsonArray arr = new JsonArray();
+ for (LanguageModel.LanguageOperatorModel op : operators) {
+ if (matchesOptionFilter(op, filter)
+ || (op.getOperatorKind() != null && op.getOperatorKind().toLowerCase().contains(filter))) {
+ arr.add(operatorToJson(op));
+ }
+ }
+ result.put("operators", arr);
+ result.put("matchedOperators", arr.size());
+ } else {
+ JsonArray syntaxes = new JsonArray();
+ for (LanguageModel.LanguageOperatorModel op : operators) {
+ syntaxes.add(op.getOperatorSyntax() != null ? op.getOperatorSyntax() : op.getName());
+ }
+ result.put("operatorSyntax", syntaxes);
+ }
+ }
+ }
+
+ private static JsonObject functionToJson(LanguageModel.LanguageFunctionModel fn) {
+ JsonObject o = new JsonObject();
+ o.put("name", fn.getName());
+ if (fn.getDisplayName() != null) {
+ o.put("displayName", fn.getDisplayName());
+ }
+ if (fn.getGroup() != null) {
+ o.put("group", fn.getGroup());
+ }
+ if (fn.getJavaType() != null) {
+ o.put("javaType", fn.getJavaType());
+ }
+ if (fn.getDescription() != null) {
+ o.put("description", fn.getDescription());
+ }
+ if (fn.getParams() != null && !fn.getParams().isEmpty()) {
+ JsonArray params = new JsonArray();
+ for (LanguageModel.FunctionParamModel param : fn.getParams()) {
+ JsonObject p = new JsonObject();
+ p.put("name", param.getName());
+ if (param.getJavaType() != null) {
+ p.put("javaType", param.getJavaType());
+ }
+ p.put("required", param.isRequired());
+ if (param.getDescription() != null) {
+ p.put("description", param.getDescription());
+ }
+ params.add(p);
+ }
+ o.put("params", params);
+ }
+ if (fn.getExamples() != null && !fn.getExamples().isEmpty()) {
+ o.put("examples", new JsonArray(fn.getExamples()));
+ }
+ if (fn.isOgnl()) {
+ o.put("ognl", true);
+ }
+ if (fn.isDeprecated()) {
+ o.put("deprecated", true);
+ }
+ return o;
+ }
+
+ private static JsonObject operatorToJson(LanguageModel.LanguageOperatorModel op) {
+ JsonObject o = new JsonObject();
+ o.put("name", op.getName());
+ if (op.getDisplayName() != null) {
+ o.put("displayName", op.getDisplayName());
+ }
+ if (op.getOperatorKind() != null) {
+ o.put("kind", op.getOperatorKind());
+ }
+ if (op.getOperatorSyntax() != null) {
+ o.put("syntax", op.getOperatorSyntax());
+ }
+ if (op.getDescription() != null) {
+ o.put("description", op.getDescription());
+ }
+ if (op.getExamples() != null && !op.getExamples().isEmpty()) {
+ o.put("examples", new JsonArray(op.getExamples()));
+ }
+ return o;
+ }
+
+ private static JsonObject eipDoc(EipModel model, String filter, boolean includeOptions, String doc) {
+ JsonObject result = new JsonObject();
+ result.put("kind", "eip");
+ result.put("name", model.getName());
+ result.put("title", model.getTitle());
+ result.put("description", model.getDescription());
+ if (model.getLabel() != null) {
+ result.put("label", model.getLabel());
+ }
+ result.put("input", model.isInput());
+ result.put("output", model.isOutput());
+ addCommonModelFields(result, model);
+ if (includeOptions) {
+ result.put("options", filteredOptions(model.getOptions(), filter));
+ result.put("matchedOptions", ((JsonArray) result.get("options")).size());
+ }
+ if (doc != null) {
+ result.put("doc", doc);
+ }
+ return result;
+ }
+
+ private static JsonArray filteredOptions(List<? extends BaseOptionModel> options, String filter) {
+ JsonArray arr = new JsonArray();
+ if (options != null) {
+ for (BaseOptionModel opt : options) {
+ if (matchesOptionFilter(opt, filter)) {
+ arr.add(optionToJson(opt, null));
+ }
+ }
+ }
+ return arr;
+ }
+
+ private static boolean matchesOptionFilter(BaseOptionModel opt, String filter) {
+ if (filter == null) {
+ return true;
+ }
+ return (opt.getName() != null && opt.getName().toLowerCase().contains(filter))
+ || (opt.getDescription() != null && opt.getDescription().toLowerCase().contains(filter))
+ || (opt.getGroup() != null && opt.getGroup().toLowerCase().contains(filter))
+ || (opt.getLabel() != null && opt.getLabel().toLowerCase().contains(filter));
+ }
+
+ /** One option as the tools return it; {@code scope} is component or endpoint for a component's options. */
+ public static JsonObject optionToJson(BaseOptionModel opt, String scope) {
+ JsonObject o = new JsonObject();
+ o.put("name", opt.getName());
+ o.put("description", opt.getDescription());
+ o.put("type", opt.getType());
+ o.put("required", opt.isRequired());
+ if ("path".equals(opt.getKind()) || "parameter".equals(opt.getKind())) {
+ // an endpoint option is either part of the URI path or a query parameter; a model must not mix them up
+ o.put("kind", opt.getKind());
+ }
+ if (opt.getDefaultValue() != null) {
+ o.put("defaultValue", opt.getDefaultValue().toString());
+ }
+ if (opt.getGroup() != null) {
+ o.put("group", opt.getGroup());
+ }
+ if (scope != null) {
+ o.put("scope", scope);
+ }
+ if (opt.isDeprecated()) {
+ o.put("deprecated", true);
+ }
+ if (opt.isSecret()) {
+ o.put("secret", true);
+ }
+ if (opt.getEnums() != null && !opt.getEnums().isEmpty()) {
+ JsonArray enums = new JsonArray();
+ enums.addAll(opt.getEnums());
+ o.put("enumValues", enums);
+ }
+ return o;
+ }
+}
diff --git a/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/DiagnoseData.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/DiagnoseData.java
similarity index 98%
copy from dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/DiagnoseData.java
copy to dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/DiagnoseData.java
index f65da48865db..9206844d7e9a 100644
--- a/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/DiagnoseData.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/DiagnoseData.java
@@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.camel.dsl.jbang.core.commands.mcp;
+package org.apache.camel.dsl.jbang.core.commands.ai;
import java.util.ArrayList;
import java.util.Collections;
@@ -22,19 +22,14 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
-import jakarta.enterprise.context.ApplicationScoped;
-
import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
/**
- * Shared holder for Camel exception diagnostic reference data used by both {@link DiagnoseTools} (MCP Tool) and
- * {@link DiagnoseResources} (MCP Resources).
- * <p>
- * Contains the registry of known Camel exceptions with their descriptions, common causes, suggested fixes, and
- * documentation links.
+ * Reference data for diagnosing Camel errors: the known Camel exceptions with their descriptions, common causes,
+ * suggested fixes and documentation links. Used by the shared {@code camel_error_diagnose} tool in the
+ * {@link ToolRegistry} and by the camel-jbang-mcp diagnose resources.
*/
-@ApplicationScoped
public class DiagnoseData {
public static final String CAMEL_DOC_BASE = "https://camel.apache.org/";
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ErrorDiagnoser.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ErrorDiagnoser.java
new file mode 100644
index 000000000000..8993efbd9de2
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ErrorDiagnoser.java
@@ -0,0 +1,143 @@
+/*
+ * 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.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.camel.catalog.CamelCatalog;
+import org.apache.camel.tooling.model.ComponentModel;
+import org.apache.camel.tooling.model.EipModel;
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
+
+/**
+ * Diagnoses a Camel error from a stack trace or error message: the known exceptions it contains with their common
+ * causes and suggested fixes ({@link DiagnoseData}), the components and EIPs it mentions, and the route id if any.
+ * Shared by the {@code camel_error_diagnose} tool of every Camel MCP server.
+ */
+public final class ErrorDiagnoser {
+
+ private static final Pattern ENDPOINT_URI_PATTERN = Pattern
+ .compile("(?:endpoint|uri)[:\\s]+['\"]?([a-zA-Z][a-zA-Z0-9+.-]*):(?://)?[^\\s'\"]*", Pattern.CASE_INSENSITIVE);
+ private static final Pattern COMPONENT_SCHEME_PATTERN
+ = Pattern.compile("(?:component|scheme)[:\\s]+['\"]?([a-zA-Z][a-zA-Z0-9+.-]*)['\"]?", Pattern.CASE_INSENSITIVE);
+ private static final Pattern ROUTE_ID_PATTERN
+ = Pattern.compile("route[:\\s]+['\"]?([a-zA-Z0-9_-]+)['\"]?", Pattern.CASE_INSENSITIVE);
+
+ private static final DiagnoseData DATA = new DiagnoseData();
+
+ private ErrorDiagnoser() {
+ }
+
+ /**
+ * @param error the stack trace or error message
+ * @param catalog the catalog to resolve component and EIP names with
+ * @return identifiedExceptions, identifiedComponents, identifiedEips, routeId and a summary
+ */
+ public static JsonObject diagnose(String error, CamelCatalog catalog) {
+ JsonArray exceptions = new JsonArray();
+ for (Map.Entry<String, DiagnoseData.ExceptionInfo> entry : DATA.getKnownExceptions().entrySet()) {
+ if (error.contains(entry.getKey())) {
+ JsonObject e = new JsonObject();
+ e.put("exception", entry.getKey());
+ DiagnoseData.ExceptionInfo info = entry.getValue();
+ e.put("description", info.description());
+ e.put("commonCauses", new JsonArray(info.commonCauses()));
+ e.put("suggestedFixes", new JsonArray(info.suggestedFixes()));
+ e.put("documentationLinks", new JsonArray(info.documentationLinks()));
+ exceptions.add(e);
+ }
+ }
+
+ JsonArray components = new JsonArray();
+ for (String comp : extractComponentNames(error, catalog)) {
+ ComponentModel model = catalog.componentModel(comp);
+ if (model != null) {
+ JsonObject c = new JsonObject();
+ c.put("name", comp);
+ c.put("title", model.getTitle());
+ c.put("description", model.getDescription());
+ c.put("documentationUrl", DiagnoseData.CAMEL_COMPONENT_DOC + comp + "-component.html");
+ components.add(c);
+ }
+ }
+
+ JsonArray eips = new JsonArray();
+ String lowerError = error.toLowerCase();
+ for (String eip : catalog.findModelNames()) {
+ EipModel model = catalog.eipModel(eip);
+ if (model != null && lowerError.contains(eip.toLowerCase())) {
+ JsonObject e = new JsonObject();
+ e.put("name", eip);
+ e.put("title", model.getTitle());
+ e.put("description", model.getDescription());
+ e.put("documentationUrl", DiagnoseData.CAMEL_EIP_DOC + eip + "-eip.html");
+ eips.add(e);
+ }
+ }
+
+ JsonObject result = new JsonObject();
+ result.put("identifiedExceptions", exceptions);
+ result.put("identifiedComponents", components);
+ result.put("identifiedEips", eips);
+ Matcher routeMatcher = ROUTE_ID_PATTERN.matcher(error);
+ if (routeMatcher.find()) {
+ result.put("routeId", routeMatcher.group(1));
+ }
+ JsonObject summary = new JsonObject();
+ summary.put("exceptionCount", exceptions.size());
+ summary.put("componentCount", components.size());
+ summary.put("eipCount", eips.size());
+ summary.put("diagnosed", !exceptions.isEmpty());
+ result.put("summary", summary);
+ if (exceptions.isEmpty()) {
+ result.put("message", "No known Camel exception in the text; the components and EIPs it mentions are"
+ + " listed, and camel_catalog_doc has their options");
+ }
+ return result;
+ }
+
+ private static List<String> extractComponentNames(String error, CamelCatalog catalog) {
+ List<String> found = new ArrayList<>();
+ Matcher uriMatcher = ENDPOINT_URI_PATTERN.matcher(error);
+ while (uriMatcher.find()) {
+ String scheme = uriMatcher.group(1).toLowerCase();
+ if (catalog.componentModel(scheme) != null && !found.contains(scheme)) {
+ found.add(scheme);
+ }
+ }
+ Matcher schemeMatcher = COMPONENT_SCHEME_PATTERN.matcher(error);
+ while (schemeMatcher.find()) {
+ String scheme = schemeMatcher.group(1).toLowerCase();
+ if (catalog.componentModel(scheme) != null && !found.contains(scheme)) {
+ found.add(scheme);
+ }
+ }
+ String lowerError = error.toLowerCase();
+ for (String comp : catalog.findComponentNames()) {
+ if (!found.contains(comp) && (lowerError.contains(comp + ":")
+ || lowerError.contains("\"" + comp + "\"") || lowerError.contains("'" + comp + "'"))) {
+ found.add(comp);
+ }
+ }
+ return found;
+ }
+}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ExpressionEvaluator.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ExpressionEvaluator.java
new file mode 100644
index 000000000000..3a532da5be1c
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ExpressionEvaluator.java
@@ -0,0 +1,151 @@
+/*
+ * 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.regex.Pattern;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.Expression;
+import org.apache.camel.Predicate;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.spi.Language;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.util.json.JsonObject;
+import org.apache.camel.util.json.Jsoner;
+
+/**
+ * Evaluates an expression for an AI agent: inside the running integration when one is selected (the way
+ * {@code camel cmd eval} does, so the expression sees the real context), otherwise locally in a scratch CamelContext
+ * with the languages on the CLI's classpath, so a simple expression can be checked before it is written into a route
+ * that is not running yet. The result is the value, or the parser or evaluation error, so the tool doubles as a
+ * validator.
+ */
+public final class ExpressionEvaluator {
+
+ private static final Pattern PREDICATE_OPERATOR = Pattern.compile(
+ "\\s(==|=~|!=|!=~|>|>=|<|<=|~~|!~~|contains|!contains|regex|!regex|in|!in|is|!is|range|!range"
+ + "|startsWith|!startsWith|endsWith|!endsWith|equals|!equals|&&|\\|\\|)\\s");
+
+ private ExpressionEvaluator() {
+ }
+
+ /** Whether a simple expression is a predicate: it has a comparison or logical operator and no ternary or elvis. */
+ public static boolean looksLikePredicate(String expression) {
+ if (expression == null || expression.contains(" ? ") || expression.contains(" ?: ")) {
+ return false;
+ }
+ return PREDICATE_OPERATOR.matcher(expression).find();
+ }
+
+ /**
+ * @param ctx the context; its selected process evaluates the expression when it has one
+ * @param language the language, simple by default
+ * @param expression the expression
+ * @param body the message body, or null for an empty one
+ * @return language, expression, predicate, status (ok or error) and the result or error
+ */
+ public static JsonObject evaluate(ToolContext ctx, String language, String expression, String body) {
+ String lang = language == null || language.isBlank() ? "simple" : language;
+ boolean predicate = "simple".equals(lang) && looksLikePredicate(expression);
+ JsonObject result = new JsonObject();
+ result.put("language", lang);
+ result.put("expression", expression);
+ if (predicate) {
+ result.put("predicate", true);
+ }
+ if (body == null && expression.contains("${body")) {
+ result.put("note", "evaluated with an empty body; pass body to evaluate against a value");
+ }
+ if (ctx.hasProcess()) {
+ result.put("evaluatedIn", "the running integration (pid " + ctx.pid() + ")");
+ evaluateInProcess(ctx, lang, expression, body, predicate, result);
+ } else {
+ result.put("evaluatedIn", "a local scratch context (no integration selected)");
+ evaluateLocally(lang, expression, body, predicate, result);
+ }
+ return result;
+ }
+
+ private static void evaluateInProcess(
+ ToolContext ctx, String lang, String expression, String body, boolean predicate, JsonObject result) {
+ String raw = ctx.executeAction("eval", root -> {
+ root.put("language", lang);
+ root.put("predicate", String.valueOf(predicate));
+ root.put("template", Jsoner.escape(expression));
+ if (body != null) {
+ root.put("body", Jsoner.escape(body));
+ }
+ });
+ JsonObject out = null;
+ try {
+ out = (JsonObject) Jsoner.deserialize(raw);
+ } catch (Exception e) {
+ // not JSON: a timeout message
+ }
+ if (out == null) {
+ result.put("status", "error");
+ result.put("error", raw);
+ return;
+ }
+ if ("success".equals(out.getString("status"))) {
+ result.put("status", "ok");
+ result.put("result", out.get("result"));
+ return;
+ }
+ result.put("status", "error");
+ JsonObject cause = out.getMap("exception");
+ String message = cause != null ? cause.getString("message") : null;
+ result.put("error", message != null ? Jsoner.unescape(message) : "evaluation failed");
+ }
+
+ private static void evaluateLocally(
+ String lang, String expression, String body, boolean predicate, JsonObject result) {
+ try (DefaultCamelContext context = new DefaultCamelContext(false)) {
+ context.start();
+ Language language;
+ try {
+ language = context.resolveLanguage(lang);
+ } catch (Exception e) {
+ result.put("status", "error");
+ result.put("error", "Unknown language '" + lang + "': " + e.getMessage());
+ return;
+ }
+ Exchange exchange = new DefaultExchange(context);
+ exchange.getMessage().setBody(body != null ? body : "");
+ Object value;
+ if (predicate) {
+ Predicate p = language.createPredicate(expression);
+ p.init(context);
+ value = p.matches(exchange);
+ } else {
+ Expression e = language.createExpression(expression);
+ e.init(context);
+ value = e.evaluate(exchange, Object.class);
+ }
+ result.put("status", "ok");
+ result.put("result", value != null ? value.toString() : null);
+ } catch (Exception e) {
+ result.put("status", "error");
+ Throwable cause = e;
+ while (cause.getCause() != null && cause.getCause() != cause) {
+ cause = cause.getCause();
+ }
+ String message = cause.getMessage();
+ result.put("error", message != null ? message : cause.toString());
+ }
+ }
+}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/IntegrationLauncher.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/IntegrationLauncher.java
new file mode 100644
index 000000000000..908623b16404
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/IntegrationLauncher.java
@@ -0,0 +1,259 @@
+/*
+ * 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.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
+import org.apache.camel.dsl.jbang.core.common.LauncherHelper;
+import org.apache.camel.dsl.jbang.core.common.RuntimeHelper;
+import org.apache.camel.util.json.JsonObject;
+
+/**
+ * Starts, stops and restarts an integration for an AI agent that is building one: {@code camel run --dev} in a separate
+ * JVM (through the same launcher the CLI itself uses), watched until its status file appears so the caller gets the pid
+ * and the log file back, and a restart that relaunches the process with its own command line.
+ */
+public final class IntegrationLauncher {
+
+ /** How long a started integration is given to publish its status file before the call returns without a pid. */
+ static final long STARTUP_TIMEOUT_MS = 30_000;
+
+ private IntegrationLauncher() {
+ }
+
+ /**
+ * Starts {@code camel run} detached in the given directory.
+ *
+ * @param directory the project directory (the working directory of the process)
+ * @param files the source files to run, relative to the directory; empty runs every route file in it
+ * @param name the integration name (the {@code --name} option); null keeps the default
+ * @param dev dev mode (reload on file changes)
+ * @param extraArgs further {@code camel run} arguments
+ * @return status started (with pid, name, log), failed (with the output) or starting
+ */
+ public static JsonObject run(Path directory, List<String> files, String name, boolean dev, List<String> extraArgs) {
+ List<String> cmd = new ArrayList<>(LauncherHelper.getCamelCommand());
+ cmd.add("run");
+ cmd.addAll(files);
+ if (dev) {
+ cmd.add("--dev");
+ }
+ if (name != null && !name.isBlank()) {
+ cmd.add("--name=" + name);
+ }
+ cmd.add("--logging-color=false");
+ if (extraArgs != null) {
+ cmd.addAll(extraArgs);
+ }
+ JsonObject result = new JsonObject();
+ result.put("directory", directory.toString());
+ result.put("command", String.join(" ", cmd));
+ Path output;
+ Process process;
+ try {
+ Files.createDirectories(CommandLineHelper.getCamelDir());
+ output = Files.createTempFile(CommandLineHelper.getCamelDir(), "camel-launch-", ".log");
+ output.toFile().deleteOnExit();
+ ProcessBuilder pb = new ProcessBuilder(cmd);
+ pb.directory(directory.toFile());
+ pb.redirectErrorStream(true);
+ pb.redirectOutput(output.toFile());
+ process = pb.start();
+ } catch (IOException e) {
+ result.put("status", "failed");
+ result.put("error", "Cannot start camel run: " + e.getMessage());
+ return result;
+ }
+ long pid = process.pid();
+ long deadline = System.currentTimeMillis() + STARTUP_TIMEOUT_MS;
+ while (System.currentTimeMillis() < deadline) {
+ if (!process.isAlive()) {
+ result.put("status", "failed");
+ result.put("exitCode", process.exitValue());
+ result.put("output", readTail(output));
+ result.put("message", "camel run exited before the integration started; the output has the reason");
+ return result;
+ }
+ RuntimeHelper.ProcessInfo info = findByPid(pid);
+ if (info != null) {
+ result.put("status", "started");
+ result.put("pid", pid);
+ result.put("name", info.name());
+ result.put("log", LogFileReader.logFile(pid, info.name()).toString());
+ result.put("devMode", dev);
+ result.put("message", "Started " + info.name() + " (pid " + pid + ")"
+ + (dev
+ ? "; dev mode reloads the routes when a source file changes"
+ : "; restart it after changing a source file")
+ + ". camel_get_log reads its log, camel_get_errors its failed exchanges.");
+ return result;
+ }
+ try {
+ Thread.sleep(250);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ break;
+ }
+ }
+ result.put("status", "starting");
+ result.put("pid", pid);
+ result.put("output", readTail(output));
+ result.put("message", "camel run is still starting after " + STARTUP_TIMEOUT_MS / 1000
+ + "s (dependencies may be downloading); list_processes shows it once it is up");
+ return result;
+ }
+
+ private static RuntimeHelper.ProcessInfo findByPid(long pid) {
+ for (RuntimeHelper.ProcessInfo p : RuntimeHelper.discoverProcesses()) {
+ if (p.pid() == pid) {
+ return p;
+ }
+ }
+ return null;
+ }
+
+ private static String readTail(Path output) {
+ try {
+ String text = Files.readString(output, StandardCharsets.UTF_8);
+ return text.length() > 4000 ? "..." + text.substring(text.length() - 4000) : text;
+ } catch (IOException e) {
+ return "";
+ }
+ }
+
+ /**
+ * Controls a running integration.
+ *
+ * @param ctx the context with the selected process
+ * @param action stop (graceful), kill, restart, stop-routes, start-routes or reset-stats
+ * @return what was done
+ */
+ public static String control(ToolContext ctx, String action) {
+ ctx.requireProcess();
+ long pid = ctx.pid();
+ return switch (action) {
+ case "stop" -> ctx.stopApplication();
+ case "kill" -> {
+ Optional<ProcessHandle> ph = ProcessHandle.of(pid);
+ if (ph.isEmpty()) {
+ yield "No process with pid " + pid;
+ }
+ ph.get().destroyForcibly();
+ yield "Killed pid " + pid;
+ }
+ case "restart" -> restart(pid);
+ case "stop-routes", "pause" -> ctx.executeAction("route", root -> {
+ root.put("id", "*");
+ root.put("command", "stop");
+ });
+ case "start-routes", "resume" -> ctx.executeAction("route", root -> {
+ root.put("id", "*");
+ root.put("command", "start");
+ });
+ case "reset-stats" -> {
+ ctx.executeAction("reset-stats", null);
+ yield "Statistics reset for pid " + pid;
+ }
+ default -> throw new ToolExecutionException(
+ "Unknown action: " + action + ". Use stop, kill, restart, stop-routes, start-routes or reset-stats");
+ };
+ }
+
+ /**
+ * Stops the process and starts it again with its own command line and working directory, so a route file edited
+ * without dev mode is picked up. Returns the new pid once its status file appears.
+ */
+ static String restart(long pid) {
+ Optional<ProcessHandle> handle = ProcessHandle.of(pid);
+ if (handle.isEmpty()) {
+ return "No process with pid " + pid;
+ }
+ ProcessHandle ph = handle.get();
+ ProcessHandle.Info info = ph.info();
+ List<String> cmd = new ArrayList<>();
+ if (info.command().isPresent() && info.arguments().isPresent()) {
+ cmd.add(info.command().get());
+ Collections.addAll(cmd, info.arguments().get());
+ }
+ if (cmd.isEmpty()) {
+ return "Cannot restart pid " + pid + ": its command line is not available; stop it and run it again";
+ }
+ RuntimeHelper.ProcessInfo pi = findByPid(pid);
+ String name = pi != null ? pi.name() : null;
+ Path directory = workingDirectory(pid);
+ RuntimeHelper.stopApplication(pid);
+ try {
+ ph.onExit().get(10, TimeUnit.SECONDS);
+ } catch (Exception e) {
+ ph.destroyForcibly();
+ try {
+ ph.onExit().get(5, TimeUnit.SECONDS);
+ } catch (Exception ignored) {
+ // the relaunch below is attempted anyway
+ }
+ }
+ try {
+ Path output = Files.createTempFile(CommandLineHelper.getCamelDir(), "camel-restart-", ".log");
+ output.toFile().deleteOnExit();
+ ProcessBuilder pb = new ProcessBuilder(cmd);
+ if (directory != null) {
+ pb.directory(directory.toFile());
+ }
+ pb.redirectErrorStream(true);
+ pb.redirectOutput(output.toFile());
+ Process p = pb.start();
+ long deadline = System.currentTimeMillis() + STARTUP_TIMEOUT_MS;
+ while (System.currentTimeMillis() < deadline && p.isAlive()) {
+ if (findByPid(p.pid()) != null) {
+ return "Restarted " + (name != null ? name : "pid " + pid) + " as pid " + p.pid();
+ }
+ Thread.sleep(250);
+ }
+ if (!p.isAlive()) {
+ return "Restart of " + (name != null ? name : "pid " + pid) + " failed with exit code "
+ + p.exitValue() + ":\n" + readTail(output);
+ }
+ return "Restarting " + (name != null ? name : "pid " + pid) + " as pid " + p.pid()
+ + " (still starting)";
+ } catch (IOException e) {
+ return "Restart failed: " + e.getMessage();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return "Restart interrupted";
+ }
+ }
+
+ /** The working directory of a camel run process, which it reports in the runtime section of its status file. */
+ private static Path workingDirectory(long pid) {
+ JsonObject status = RuntimeHelper.readStatus(pid);
+ if (status == null) {
+ return null;
+ }
+ JsonObject runtime = (JsonObject) status.get("runtime");
+ String dir = runtime != null ? runtime.getString("directory") : null;
+ return dir != null && Files.isDirectory(Path.of(dir)) ? Path.of(dir) : null;
+ }
+}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/LogFileReader.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/LogFileReader.java
new file mode 100644
index 000000000000..c57fb7c9d378
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/LogFileReader.java
@@ -0,0 +1,199 @@
+/*
+ * 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.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
+
+/**
+ * Reads the tail of an integration's log file ({@code ~/.camel/<pid>.log}, which {@code camel run} writes) as
+ * structured records, newest first, the way the Camel TUI's Log tab hands it to an AI agent: a stack trace or wrapped
+ * text is one record with a {@code detail} block, not fifty lines that all claim to be INFO.
+ */
+public final class LogFileReader {
+
+ /** Continuation lines kept per log record before the rest is summarised as a count. */
+ static final int MAX_DETAIL_LINES = 20;
+
+ /** How much of the end of the file is read; a limit of a few hundred records fits with room to spare. */
+ private static final int TAIL_BYTES = 512 * 1024;
+
+ private static final Pattern LOG_PATTERN = Pattern.compile(
+ "^(\\d{4}-\\d{2}-\\d{2})[T ](\\d{2}:\\d{2}:\\d{2}\\.\\d+)\\S*\\s+"
+ + "(TRACE|DEBUG|INFO|WARN|ERROR|FATAL)\\s+"
+ + "\\d+\\s+---\\s+"
+ + "\\[([^]]*)]\\s+"
+ + "(\\S+)\\s*:\\s*(.*)$");
+
+ private static final Pattern ANSI = Pattern.compile("\\u001b\\[[;\\d]*[ -/]*[@-~]");
+
+ private LogFileReader() {
+ }
+
+ /** The log file of a process: {@code <pid>.log}, or {@code <name>.log} when the pid file does not exist. */
+ public static Path logFile(long pid, String name) {
+ Path dir = CommandLineHelper.getCamelDir();
+ Path pidLog = dir.resolve(pid + ".log");
+ if (!Files.exists(pidLog) && name != null && !name.isBlank()) {
+ Path nameLog = dir.resolve(name + ".log");
+ if (Files.exists(nameLog)) {
+ return nameLog;
+ }
+ }
+ return pidLog;
+ }
+
+ /**
+ * @param pid the process
+ * @param name the integration name, for the log file fallback
+ * @param limit maximum records to return
+ * @param filter case-insensitive substring the message or detail must contain; null for all
+ * @param level only records of this level (INFO, WARN, ERROR, DEBUG, TRACE); null for all
+ * @return lines (newest first), totalLines and returnedLines, or an error when there is no log file
+ */
+ public static JsonObject read(long pid, String name, int limit, String filter, String level) {
+ Path file = logFile(pid, name);
+ JsonObject result = new JsonObject();
+ result.put("file", file.toString());
+ if (!Files.isRegularFile(file)) {
+ result.put("error", "No log file " + file + " (an integration started with camel run writes one;"
+ + " Spring Boot and Quarkus applications log to their own console)");
+ return result;
+ }
+ List<String> lines;
+ try {
+ lines = tail(file);
+ } catch (IOException e) {
+ result.put("error", "Cannot read " + file + ": " + e.getMessage());
+ return result;
+ }
+ return build(lines, limit, filter, level, result);
+ }
+
+ /** Groups raw lines into records and filters them, newest first; visible for tests. */
+ static JsonObject build(List<String> lines, int limit, String filter, String level, JsonObject result) {
+ List<JsonObject> records = toRecords(lines);
+ String needle = filter == null || filter.isBlank() ? null : filter.toLowerCase();
+ JsonArray rows = new JsonArray();
+ for (int i = records.size() - 1; i >= 0 && rows.size() < limit; i--) {
+ JsonObject r = records.get(i);
+ if (level != null && !level.isBlank() && !level.equalsIgnoreCase(r.getString("level"))) {
+ continue;
+ }
+ if (needle != null) {
+ String message = r.getStringOrDefault("message", "").toLowerCase();
+ String detail = r.getStringOrDefault("detail", "").toLowerCase();
+ if (!message.contains(needle) && !detail.contains(needle)) {
+ continue;
+ }
+ }
+ rows.add(r);
+ }
+ result.put("lines", rows);
+ result.put("totalLines", lines.size());
+ result.put("returnedLines", rows.size());
+ return result;
+ }
+
+ private static List<String> tail(Path file) throws IOException {
+ try (RandomAccessFile raf = new RandomAccessFile(file.toFile(), "r")) {
+ long length = raf.length();
+ long start = Math.max(0, length - TAIL_BYTES);
+ raf.seek(start);
+ byte[] buf = new byte[(int) (length - start)];
+ raf.readFully(buf);
+ String text = new String(buf, StandardCharsets.UTF_8);
+ List<String> lines = new ArrayList<>();
+ int from = 0;
+ if (start > 0) {
+ // the first line is most likely cut in the middle
+ from = text.indexOf('\n') + 1;
+ }
+ for (String line : text.substring(from).split("\n")) {
+ if (!line.isEmpty()) {
+ lines.add(line);
+ }
+ }
+ return lines;
+ }
+ }
+
+ private static List<JsonObject> toRecords(List<String> lines) {
+ List<JsonObject> records = new ArrayList<>();
+ JsonObject head = null;
+ List<String> detail = null;
+ int hidden = 0;
+ for (String raw : lines) {
+ String line = ANSI.matcher(raw).replaceAll("");
+ Matcher m = LOG_PATTERN.matcher(line);
+ boolean matches = m.matches();
+ if (!matches && head != null) {
+ if (detail.size() < MAX_DETAIL_LINES) {
+ detail.add(line);
+ } else {
+ hidden++;
+ }
+ continue;
+ }
+ if (head != null) {
+ records.add(finish(head, detail, hidden));
+ }
+ head = new JsonObject();
+ if (matches) {
+ String time = m.group(2);
+ head.put("time", time.length() > 12 ? time.substring(0, 12) : time);
+ head.put("level", m.group(3));
+ String logger = m.group(5);
+ int lastDot = logger.lastIndexOf('.');
+ head.put("logger", lastDot > 0 ? logger.substring(lastDot + 1) : logger);
+ head.put("message", m.group(6));
+ } else {
+ head.put("time", "");
+ head.put("level", "INFO");
+ head.put("message", line);
+ }
+ detail = new ArrayList<>();
+ hidden = 0;
+ }
+ if (head != null) {
+ records.add(finish(head, detail, hidden));
+ }
+ return records;
+ }
+
+ private static JsonObject finish(JsonObject head, List<String> detail, int hidden) {
+ if (!detail.isEmpty()) {
+ String text = String.join("\n", detail);
+ if (hidden > 0) {
+ text += "\n... " + hidden + " more lines";
+ }
+ head.put("detail", text);
+ }
+ return head;
+ }
+}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/SourceValidator.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/SourceValidator.java
new file mode 100644
index 000000000000..5e2750cb396d
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/SourceValidator.java
@@ -0,0 +1,546 @@
+/*
+ * 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.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import com.networknt.schema.Error;
+import org.apache.camel.catalog.CamelCatalog;
+import org.apache.camel.catalog.ConfigurationPropertiesValidationResult;
+import org.apache.camel.catalog.EndpointValidationResult;
+import org.apache.camel.catalog.LanguageValidationResult;
+import org.apache.camel.dsl.yaml.validator.YamlValidator;
+
+/**
+ * Validates integration source files the way the Camel TUI's editor does on save, before an AI agent writes them: Camel
+ * YAML DSL against the YAML DSL schema (unknown or misspelled options, wrong structure), then the endpoint URIs and
+ * simple expressions in it against the catalog; a .properties file line by line against the catalog of {@code camel.*}
+ * options. Every message names the line so the agent can fix the file.
+ */
+public final class SourceValidator {
+
+ private static final Set<String> PREDICATE_EIPS = Set.of(
+ "filter", "when", "validate", "onWhen", "on-when",
+ "handled", "continued", "retryWhile", "retry-while",
+ "completionPredicate", "completion-predicate",
+ "completion", "loopDoWhile", "loop-do-while");
+
+ private static final Set<String> CONSUMER_EIPS
+ = Set.of("from", "pollEnrich", "poll-enrich", "poll", "interceptFrom", "intercept-from");
+ private static final Set<String> PRODUCER_EIPS
+ = Set.of("to", "toD", "to-d", "wireTap", "wire-tap", "enrich",
+ "interceptSendToEndpoint", "intercept-send-to-endpoint");
+
+ private static final Pattern YAML_URI_PATTERN = Pattern.compile(
+ "^\\s*-?\\s*(?:uri|from|to|toD|wireTap|enrich|pollEnrich|deadLetterChannel):\\s*\"?([a-zA-Z][a-zA-Z0-9+.-]*(?::[^\"\\s]*)?)");
+
+ private static volatile YamlValidator yamlValidator;
+
+ private SourceValidator() {
+ }
+
+ /** Whether the file has a validator: YAML routes and .properties files do, other files have none. */
+ public static boolean isValidatableFile(String fileName) {
+ String name = fileName == null ? "" : fileName.toLowerCase(Locale.ROOT);
+ return name.endsWith(".yaml") || name.endsWith(".yml") || name.endsWith(".properties");
+ }
+
+ /**
+ * Validates source by file type: Camel YAML DSL for .yaml/.yml files, Camel options for .properties files. Other
+ * file types have no validation and yield no messages.
+ *
+ * @param fileName the file name; its extension picks the checks
+ * @param content the source
+ * @param catalog the catalog of the Camel version the source is for
+ * @param extraPropertyLine an extra check for a properties line the catalog does not know (Spring Boot
+ * properties), returning the message or null; may be null
+ * @return the messages, empty when the source is valid
+ */
+ public static List<String> validate(
+ String fileName, String content, CamelCatalog catalog, Function<String, String> extraPropertyLine) {
+ String name = fileName == null ? "" : fileName.toLowerCase(Locale.ROOT);
+ if (name.endsWith(".yaml") || name.endsWith(".yml")) {
+ return validateCamelYaml(content, catalog);
+ }
+ if (name.endsWith(".properties")) {
+ return validateProperties(content, catalog, extraPropertyLine);
+ }
+ return List.of();
+ }
+
+ /**
+ * Validates Camel YAML DSL source: the YAML DSL schema first, then endpoint URIs and simple expressions against the
+ * catalog. Returns the messages, empty when the source is valid.
+ */
+ public static List<String> validateCamelYaml(String content, CamelCatalog catalog) {
+ List<String> msgs = new ArrayList<>();
+ if (content == null || content.isBlank()) {
+ return msgs;
+ }
+ try {
+ msgs.addAll(formatSchemaErrors(yamlValidator().validate(content)));
+ } catch (Exception e) {
+ msgs.add("Invalid YAML: " + e.getMessage());
+ return msgs;
+ }
+ if (catalog != null) {
+ msgs.addAll(validateYamlEndpoints(content, catalog));
+ msgs.addAll(validateYamlSimple(content, catalog));
+ }
+ return msgs;
+ }
+
+ private static YamlValidator yamlValidator() throws Exception {
+ YamlValidator v = yamlValidator;
+ if (v == null) {
+ synchronized (SourceValidator.class) {
+ v = yamlValidator;
+ if (v == null) {
+ v = new YamlValidator();
+ v.init();
+ yamlValidator = v;
+ }
+ }
+ }
+ return v;
+ }
+
+ /**
+ * Validates a properties file line by line: {@code camel.*} keys against the catalog, the rest with the extra
+ * check.
+ */
+ public static List<String> validateProperties(
+ String content, CamelCatalog catalog, Function<String, String> extraPropertyLine) {
+ return validatePropertiesLines(content, line -> validatePropertyLine(line, catalog, extraPropertyLine));
+ }
+
+ /** Validates one properties line: a {@code camel.*} key against the catalog, any other with the extra check. */
+ public static String validatePropertyLine(String line, CamelCatalog catalog, Function<String, String> extra) {
+ if (catalog != null) {
+ try {
+ ConfigurationPropertiesValidationResult result = catalog.validateConfigurationProperty(line);
+ if (result.isAccepted()) {
+ if (!result.isSuccess()) {
+ String msg = result.summaryErrorMessage(false);
+ if (msg != null) {
+ return msg.trim();
+ }
+ }
+ return null;
+ }
+ } catch (Exception e) {
+ // ignore validation errors
+ }
+ }
+ return extra != null ? extra.apply(line) : null;
+ }
+
+ /** Runs a line validator over the key=value lines of a properties file, prefixing each message with its line. */
+ public static List<String> validatePropertiesLines(String content, Function<String, String> lineValidator) {
+ List<String> msgs = new ArrayList<>();
+ if (content == null) {
+ return msgs;
+ }
+ String[] lines = content.split("\n", -1);
+ for (int i = 0; i < lines.length; i++) {
+ String line = lines[i].trim();
+ if (line.isEmpty() || line.startsWith("#") || line.startsWith("!") || !line.contains("=")) {
+ continue;
+ }
+ String error = lineValidator.apply(lines[i]);
+ if (error != null) {
+ msgs.add("Line " + (i + 1) + ": " + error);
+ }
+ }
+ return msgs;
+ }
+
+ /** The YAML DSL schema errors in words: the node they are about and the message without parser noise. */
+ public static List<String> formatSchemaErrors(List<Error> errors) {
+ List<String> msgs = new ArrayList<>();
+ if (errors == null) {
+ return msgs;
+ }
+ for (Error error : errors) {
+ String msg = error.getMessage();
+ if (msg == null) {
+ continue;
+ }
+ String loc = error.getInstanceLocation() != null ? error.getInstanceLocation().toString() : null;
+ String node = extractNodeName(loc);
+ String clean = cleanValidationMessage(msg);
+ msgs.add(node != null ? node + ": " + clean : clean);
+ }
+ return msgs;
+ }
+
+ public static String cleanValidationMessage(String msg) {
+ // strip FQCN prefix like "com.fasterxml...MarkedYAMLException: "
+ int colonSpace = msg.indexOf(": ");
+ if (colonSpace > 0) {
+ String prefix = msg.substring(0, colonSpace);
+ if (prefix.contains(".") && !prefix.contains(" ")) {
+ msg = msg.substring(colonSpace + 2);
+ }
+ }
+ // strip "at [Source: (StringReader); line: N, column: N]"
+ int atSource = msg.indexOf("at [Source:");
+ if (atSource > 0) {
+ msg = msg.substring(0, atSource).stripTrailing();
+ }
+ // strip "in 'reader', " prefix from snakeyaml messages
+ msg = msg.replace("in 'reader', ", "");
+ return msg;
+ }
+
+ public static String extractNodeName(String instanceLocation) {
+ if (instanceLocation == null || instanceLocation.isEmpty()) {
+ return null;
+ }
+ int slash = instanceLocation.lastIndexOf('/');
+ String last = slash >= 0 ? instanceLocation.substring(slash + 1) : instanceLocation;
+ if (last.isEmpty()) {
+ return null;
+ }
+ // skip pure numeric segments (array indices)
+ try {
+ Integer.parseInt(last);
+ return null;
+ } catch (NumberFormatException e) {
+ return last;
+ }
+ }
+
+ /** The simple expressions of a YAML route checked against the catalog, as predicate where the EIP expects one. */
+ public static List<String> validateYamlSimple(String content, CamelCatalog catalog) {
+ List<String> errors = new ArrayList<>();
+ String[] lines = content.split("\n", -1);
+
+ for (int i = 0; i < lines.length; i++) {
+ String line = lines[i];
+ if (line.isBlank()) {
+ continue;
+ }
+ String trimmed = line.trim();
+ if (trimmed.startsWith("#")) {
+ continue;
+ }
+
+ String simpleText = null;
+ int lineNum = i + 1;
+ int lineIndent = countLeadingSpaces(line);
+ boolean isLogMessage = false;
+
+ // Strip YAML list prefix for matching
+ String key = trimmed.startsWith("- ") ? trimmed.substring(2) : trimmed;
+
+ // Match "simple: <value>" (inline shorthand)
+ if (key.startsWith("simple:") && !key.equals("simple:")) {
+ simpleText = extractYamlValue(key, "simple");
+ }
+ // Match "simple:" followed by "expression: <value>" on next line
+ else if (key.equals("simple:")) {
+ for (int j = i + 1; j < lines.length; j++) {
+ String next = lines[j].trim();
+ if (next.isBlank()) {
+ continue;
+ }
+ if (next.startsWith("expression:")) {
+ simpleText = extractYamlValue(next, "expression");
+ lineNum = j + 1;
+ }
+ break;
+ }
+ }
+ // Match "message: <value>" under log: EIP
+ else if (key.startsWith("message:") && !key.equals("message:")) {
+ String parentEip = findParentEip(lines, i, lineIndent);
+ if ("log".equals(parentEip)) {
+ simpleText = extractYamlValue(key, "message");
+ isLogMessage = true;
+ }
+ }
+
+ if (simpleText == null || simpleText.isEmpty()) {
+ continue;
+ }
+ // Skip placeholder-only expressions
+ if (simpleText.startsWith("{{") && simpleText.endsWith("}}")) {
+ continue;
+ }
+
+ // Determine predicate vs expression context
+ boolean predicate = false;
+ if (!isLogMessage) {
+ String parentEip = findParentEip(lines, i, lineIndent);
+ predicate = parentEip != null && PREDICATE_EIPS.contains(parentEip);
+ }
+
+ try {
+ LanguageValidationResult result = predicate
+ ? catalog.validateLanguagePredicate(null, "simple", simpleText)
+ : catalog.validateLanguageExpression(null, "simple", simpleText);
+ if (!result.isSuccess()) {
+ String error = result.getShortError() != null ? result.getShortError() : result.getError();
+ if (error != null) {
+ errors.add("Line " + lineNum + ": Simple syntax error: " + error);
+ }
+ }
+ } catch (Exception e) {
+ // best effort
+ }
+ }
+ return errors;
+ }
+
+ /** The endpoint URIs of a YAML route (uri plus a parameters: map) checked against the catalog. */
+ public static List<String> validateYamlEndpoints(String content, CamelCatalog catalog) {
+ List<String> errors = new ArrayList<>();
+ String[] lines = content.split("\n", -1);
+
+ for (int i = 0; i < lines.length; i++) {
+ String line = lines[i];
+ if (line.isBlank()) {
+ continue;
+ }
+ String trimmed = line.trim();
+ if (trimmed.startsWith("#")) {
+ continue;
+ }
+
+ Matcher m = YAML_URI_PATTERN.matcher(line);
+ if (!m.find()) {
+ continue;
+ }
+
+ String uri = m.group(1);
+ if (uri.endsWith("\"")) {
+ uri = uri.substring(0, uri.length() - 1);
+ }
+ if (uri.startsWith("{{")) {
+ continue;
+ }
+ // scheme-only URI (e.g., "uri: timer") needs a colon for catalog parsing
+ if (!uri.contains(":")) {
+ uri = uri + ":";
+ }
+
+ String eipName = extractEipFromLine(trimmed);
+ int lineIndent = countLeadingSpaces(line);
+
+ // for "uri:" lines, walk backwards to find the parent EIP (from, to, etc.)
+ if ("uri".equals(eipName)) {
+ for (int j = i - 1; j >= 0; j--) {
+ String prev = lines[j];
+ if (prev.isBlank()) {
+ continue;
+ }
+ int prevIndent = countLeadingSpaces(prev);
+ if (prevIndent < lineIndent) {
+ eipName = extractEipFromLine(prev.trim());
+ break;
+ }
+ }
+ }
+
+ boolean consumerOnly = eipName != null && CONSUMER_EIPS.contains(eipName);
+ boolean producerOnly = eipName != null && PRODUCER_EIPS.contains(eipName);
+
+ // look ahead for a parameters: block at the same indent level as uri
+ StringBuilder uriBuilder = new StringBuilder(uri);
+ boolean hasParams = uri.contains("?");
+ Map<String, Integer> optionLineMap = new LinkedHashMap<>();
+ for (int j = i + 1; j < lines.length; j++) {
+ String next = lines[j];
+ if (next.isBlank()) {
+ continue;
+ }
+ int nextIndent = countLeadingSpaces(next);
+ if (nextIndent < lineIndent) {
+ break;
+ }
+ String nextTrimmed = next.trim();
+ if (nextIndent == lineIndent && nextTrimmed.startsWith("parameters:")) {
+ int paramBlockIndent = nextIndent;
+ for (int k = j + 1; k < lines.length; k++) {
+ String paramLine = lines[k];
+ if (paramLine.isBlank()) {
+ continue;
+ }
+ int paramIndent = countLeadingSpaces(paramLine);
+ if (paramIndent <= paramBlockIndent) {
+ break;
+ }
+ String paramTrimmed = paramLine.trim();
+ int colonPos = paramTrimmed.indexOf(':');
+ if (colonPos > 0) {
+ String key = paramTrimmed.substring(0, colonPos).trim();
+ String val = unquote(paramTrimmed.substring(colonPos + 1).trim());
+ char sep = hasParams ? '&' : '?';
+ uriBuilder.append(sep).append(key).append('=').append(val);
+ hasParams = true;
+ optionLineMap.put(key, k);
+ }
+ }
+ break;
+ }
+ if (nextIndent == lineIndent) {
+ break;
+ }
+ }
+
+ String fullUri = uriBuilder.toString();
+ try {
+ EndpointValidationResult result
+ = catalog.validateEndpointProperties(fullUri, false, consumerOnly, producerOnly);
+ if (!result.isSuccess()) {
+ String scheme = fullUri.contains(":") ? fullUri.substring(0, fullUri.indexOf(':')) : fullUri;
+ collectEndpointErrors(errors, result, scheme, i, optionLineMap);
+ }
+ } catch (Exception e) {
+ // ignore validation errors
+ }
+ }
+ return errors;
+ }
+
+ static void collectEndpointErrors(
+ List<String> errors, EndpointValidationResult result, String scheme,
+ int uriLineIdx, Map<String, Integer> optionLineMap) {
+ if (result.getUnknown() != null) {
+ for (String name : result.getUnknown()) {
+ StringBuilder sb = new StringBuilder(scheme).append(": Unknown option '").append(name).append("'");
+ if (result.getUnknownSuggestions() != null) {
+ String[] suggestions = result.getUnknownSuggestions().get(name);
+ if (suggestions != null && suggestions.length > 0) {
+ sb.append(". Did you mean: ").append(Arrays.asList(suggestions));
+ }
+ }
+ errors.add(linePrefix(optionLineMap.getOrDefault(name, uriLineIdx)) + sb);
+ }
+ }
+ addInvalid(errors, result.getInvalidBoolean(), "boolean", scheme, uriLineIdx, optionLineMap);
+ addInvalid(errors, result.getInvalidInteger(), "integer", scheme, uriLineIdx, optionLineMap);
+ addInvalid(errors, result.getInvalidNumber(), "number", scheme, uriLineIdx, optionLineMap);
+ if (result.getInvalidEnum() != null) {
+ for (Map.Entry<String, String> entry : result.getInvalidEnum().entrySet()) {
+ StringBuilder sb = new StringBuilder(scheme)
+ .append(": Invalid enum value '").append(entry.getValue())
+ .append("' for option '").append(entry.getKey()).append("'");
+ if (result.getInvalidEnumChoices() != null) {
+ String[] choices = result.getInvalidEnumChoices().get(entry.getKey());
+ if (choices != null) {
+ sb.append(". Possible values: ").append(Arrays.asList(choices));
+ }
+ }
+ errors.add(linePrefix(optionLineMap.getOrDefault(entry.getKey(), uriLineIdx)) + sb);
+ }
+ }
+ if (result.getNotConsumerOnly() != null) {
+ for (String name : result.getNotConsumerOnly()) {
+ errors.add(linePrefix(optionLineMap.getOrDefault(name, uriLineIdx))
+ + scheme + ": Option '" + name + "' is not applicable in consumer only mode");
+ }
+ }
+ if (result.getNotProducerOnly() != null) {
+ for (String name : result.getNotProducerOnly()) {
+ errors.add(linePrefix(optionLineMap.getOrDefault(name, uriLineIdx))
+ + scheme + ": Option '" + name + "' is not applicable in producer only mode");
+ }
+ }
+ }
+
+ private static void addInvalid(
+ List<String> errors, Map<String, String> invalid, String type, String scheme, int uriLineIdx,
+ Map<String, Integer> optionLineMap) {
+ if (invalid != null) {
+ for (Map.Entry<String, String> entry : invalid.entrySet()) {
+ errors.add(linePrefix(optionLineMap.getOrDefault(entry.getKey(), uriLineIdx))
+ + scheme + ": Invalid " + type + " value '" + entry.getValue() + "' for option '"
+ + entry.getKey() + "'");
+ }
+ }
+ }
+
+ static String linePrefix(int lineIdx) {
+ return "Line " + (lineIdx + 1) + ": ";
+ }
+
+ static String findParentEip(String[] lines, int lineIdx, int lineIndent) {
+ for (int j = lineIdx - 1; j >= 0; j--) {
+ String prev = lines[j];
+ if (prev.isBlank()) {
+ continue;
+ }
+ int prevIndent = countLeadingSpaces(prev);
+ if (prevIndent < lineIndent) {
+ return extractEipFromLine(prev.trim());
+ }
+ }
+ return null;
+ }
+
+ static String extractEipFromLine(String trimmed) {
+ if (trimmed.startsWith("- ")) {
+ trimmed = trimmed.substring(2).trim();
+ }
+ int colon = trimmed.indexOf(':');
+ if (colon > 0) {
+ return trimmed.substring(0, colon).trim();
+ }
+ return null;
+ }
+
+ static String extractYamlValue(String trimmed, String key) {
+ String prefix = key + ":";
+ if (!trimmed.startsWith(prefix)) {
+ return null;
+ }
+ return unquote(trimmed.substring(prefix.length()).trim());
+ }
+
+ static String unquote(String val) {
+ if (val.length() >= 2 && val.startsWith("\"") && val.endsWith("\"")) {
+ return val.substring(1, val.length() - 1);
+ }
+ if (val.length() >= 2 && val.startsWith("'") && val.endsWith("'")) {
+ return val.substring(1, val.length() - 1);
+ }
+ return val;
+ }
+
+ static int countLeadingSpaces(String line) {
+ int count = 0;
+ for (int i = 0; i < line.length(); i++) {
+ if (line.charAt(i) == ' ') {
+ count++;
+ } else {
+ break;
+ }
+ }
+ return count;
+ }
+}
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 85105260eb75..92bd550c6dd9 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
@@ -16,11 +16,16 @@
*/
package org.apache.camel.dsl.jbang.core.commands.ai;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.List;
+import java.util.Objects;
import java.util.function.Consumer;
+import java.util.function.Function;
import org.apache.camel.catalog.CamelCatalog;
import org.apache.camel.catalog.DefaultCamelCatalog;
+import org.apache.camel.dsl.jbang.core.common.CatalogLoader;
import org.apache.camel.dsl.jbang.core.common.RuntimeHelper;
import org.apache.camel.util.json.JsonObject;
@@ -33,6 +38,10 @@ public class ToolContext {
private volatile long pid = -1;
private volatile CamelCatalog catalog;
+ private volatile String camelVersion;
+ private volatile Path defaultDirectory;
+ private volatile Function<String, String> propertyLineValidator;
+ private volatile boolean autoSelectSingleProcess = true;
public long pid() {
return pid;
@@ -46,6 +55,100 @@ public class ToolContext {
return pid >= 0;
}
+ /** Forgets the selected process, so tools fall back to what needs no running integration. */
+ public void clearProcess() {
+ this.pid = -1;
+ }
+
+ /**
+ * Whether a runtime tool called without a name may pick the only running Camel process when none is selected: the
+ * default for a server without a selection of its own; the TUI turns it off, since there what the user selected is
+ * the integration.
+ */
+ public boolean isAutoSelectSingleProcess() {
+ return autoSelectSingleProcess;
+ }
+
+ public void setAutoSelectSingleProcess(boolean autoSelectSingleProcess) {
+ this.autoSelectSingleProcess = autoSelectSingleProcess;
+ }
+
+ /**
+ * Selects the only running Camel process when nothing is selected yet and auto-selection is on.
+ *
+ * @return whether a process is selected afterwards
+ */
+ public boolean selectSingleProcessIfNone() {
+ if (hasProcess()) {
+ return true;
+ }
+ if (!autoSelectSingleProcess) {
+ return false;
+ }
+ RuntimeHelper.ProcessInfo only = RuntimeHelper.findProcess(null);
+ if (only == null) {
+ return false;
+ }
+ selectProcess(only.pid());
+ return true;
+ }
+
+ /**
+ * The Camel version the catalog tools answer for: null for the version of the running CLI, otherwise the version of
+ * the integration being worked on (the TUI passes the selected integration's version), downloaded on demand.
+ */
+ public String camelVersion() {
+ return camelVersion;
+ }
+
+ public void setCamelVersion(String camelVersion) {
+ if (!Objects.equals(this.camelVersion, camelVersion)) {
+ this.camelVersion = camelVersion;
+ this.catalog = null;
+ }
+ }
+
+ /**
+ * The project directory the file tools use when a call names none: the TUI sets it to the source directory of the
+ * selected integration, an MCP server without a selection leaves it null and requires the argument.
+ */
+ public Path defaultDirectory() {
+ return defaultDirectory;
+ }
+
+ public void setDefaultDirectory(Path defaultDirectory) {
+ this.defaultDirectory = defaultDirectory;
+ }
+
+ /**
+ * Resolves the directory of a file tool call: the {@code directory} argument, else the default directory.
+ *
+ * @throws ToolExecutionException when neither is given or the directory does not exist
+ */
+ public Path resolveDirectory(String directory) {
+ Path dir = directory != null && !directory.isBlank() ? Path.of(directory) : defaultDirectory;
+ if (dir == null) {
+ throw new ToolExecutionException("directory is required: the project directory with the source files");
+ }
+ dir = dir.toAbsolutePath().normalize();
+ if (!Files.isDirectory(dir)) {
+ throw new ToolExecutionException("No such directory: " + dir);
+ }
+ return dir;
+ }
+
+ /**
+ * An extra check for a line of a .properties file that the catalog does not know (the TUI validates Spring Boot
+ * properties from the project's metadata); returns the message, or null when the line is fine.
+ */
+ public Function<String, String> propertyLineValidator() {
+ return propertyLineValidator;
+ }
+
+ public void setPropertyLineValidator(Function<String, String> propertyLineValidator) {
+ this.propertyLineValidator = propertyLineValidator;
+ }
+
/**
* Returns the shared {@link CamelCatalog} instance, creating it lazily on first access. Thread-safe: concurrent
* callers may race but will all see a fully constructed catalog.
@@ -56,7 +159,7 @@ public class ToolContext {
synchronized (this) {
result = catalog;
if (result == null) {
- result = new DefaultCamelCatalog();
+ result = loadCatalog();
catalog = result;
}
}
@@ -64,6 +167,37 @@ public class ToolContext {
return result;
}
+ private CamelCatalog loadCatalog() {
+ String version = camelVersion;
+ if (version == null || version.isBlank()) {
+ return new DefaultCamelCatalog();
+ }
+ try {
+ return CatalogLoader.loadCatalog(null, version, true);
+ } catch (Exception e) {
+ throw new ToolExecutionException("Cannot load the Camel catalog for version " + version + ": " + e.getMessage());
+ }
+ }
+
+ /**
+ * Selects the process a tool call names ({@code name} is an integration name or pid), or keeps the current
+ * selection when the call names none.
+ *
+ * @throws ToolExecutionException when the name matches no running process
+ */
+ public void selectProcess(String nameOrPid) {
+ if (nameOrPid == null || nameOrPid.isBlank()) {
+ return;
+ }
+ RuntimeHelper.ProcessInfo p = RuntimeHelper.findProcess(nameOrPid);
+ if (p == null) {
+ throw new ToolExecutionException(
+ "No running Camel process matches '" + nameOrPid
+ + "'; list_processes shows what runs");
+ }
+ selectProcess(p.pid());
+ }
+
public String readStatus(String section) {
requireProcess();
return RuntimeHelper.readStatusSection(pid, section);
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ToolDescriptor.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ToolDescriptor.java
index 6f24714f4a21..6dfed5d00581 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ToolDescriptor.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ToolDescriptor.java
@@ -21,6 +21,9 @@ import java.util.Collections;
import java.util.List;
import java.util.Map;
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
+
/**
* Describes a single AI tool: its name, description, parameters, and execution logic. Used by both the Agent REPL and
* the MCP server to avoid duplicating tool definitions.
@@ -33,6 +36,7 @@ public class ToolDescriptor {
private ToolExecutor executor;
private boolean readOnly = true;
private boolean destructive = false;
+ private boolean core = false;
public record Param(String name, String type, String description, boolean required) {
}
@@ -69,6 +73,15 @@ public class ToolDescriptor {
return this;
}
+ /**
+ * Marks the tool as part of the core subset: the tools a small local model gets when every tool schema counts
+ * against its prompt budget. Tools outside the subset are still available to hosted models and MCP clients.
+ */
+ public ToolDescriptor core(boolean v) {
+ core = v;
+ return this;
+ }
+
public ToolDescriptor executor(ToolExecutor exec) {
this.executor = exec;
return this;
@@ -96,6 +109,36 @@ public class ToolDescriptor {
return destructive;
}
+ public boolean isCore() {
+ return core;
+ }
+
+ /**
+ * The JSON schema of the tool's arguments, the way an MCP server lists it under {@code inputSchema} and an LLM
+ * client sends it as the function parameters: an object with one property per parameter (its type and description)
+ * and the names of the required ones.
+ */
+ public JsonObject inputSchema() {
+ JsonObject properties = new JsonObject();
+ JsonArray required = new JsonArray();
+ for (Param p : params) {
+ JsonObject prop = new JsonObject();
+ prop.put("type", p.type() != null ? p.type() : "string");
+ prop.put("description", p.description());
+ properties.put(p.name(), prop);
+ if (p.required()) {
+ required.add(p.name());
+ }
+ }
+ JsonObject schema = new JsonObject();
+ schema.put("type", "object");
+ schema.put("properties", properties);
+ if (!required.isEmpty()) {
+ schema.put("required", required);
+ }
+ return schema;
+ }
+
public ToolExecutor executor() {
return executor;
}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ToolRegistry.java b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ToolRegistry.java
index 99e17e0a19ce..ca4b617cc884 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ToolRegistry.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/ai/ToolRegistry.java
@@ -60,6 +60,7 @@ public final class ToolRegistry {
registerAnalysisTools();
registerCatalogTools();
registerExampleTools();
+ AuthoringTools.register(ToolRegistry::register);
}
private ToolRegistry() {
@@ -73,6 +74,14 @@ public final class ToolRegistry {
return BY_NAME.get(name);
}
+ /**
+ * The neutral authoring tools ({@code camel_*}, see {@link AuthoringTools}) that every Camel MCP server exposes
+ * under the same names, in registration order.
+ */
+ public static List<ToolDescriptor> authoringTools() {
+ return TOOLS.stream().filter(t -> t.name().startsWith("camel_")).toList();
+ }
+
public static Object execute(String name, ToolContext ctx, Map<String, String> args) {
ToolDescriptor desc = BY_NAME.get(name);
if (desc == null) {
diff --git a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/AuthoringToolsTest.java b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/AuthoringToolsTest.java
new file mode 100644
index 000000000000..109abfd2dbe2
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/AuthoringToolsTest.java
@@ -0,0 +1,229 @@
+/*
+ * 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.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.camel.util.json.JsonObject;
+import org.apache.camel.util.json.Jsoner;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The neutral authoring tools (CAMEL-24695): defined once, exposed by camel-jbang-mcp and the TUI under the same camel_
+ * names, self-contained over a project directory argument.
+ */
+class AuthoringToolsTest {
+
+ private static final String VALID_ROUTE = """
+ - route:
+ id: timer-log
+ from:
+ uri: timer:tick
+ parameters:
+ period: 1000
+ steps:
+ - log:
+ message: "${body}"
+ loggingLevel: WARN
+ """;
+
+ private static final String INVALID_ROUTE = VALID_ROUTE.replace("loggingLevel", "logLevel");
+
+ private static JsonObject call(String tool, ToolContext ctx, Map<String, Object> args) {
+ Map<String, String> stringArgs = new HashMap<>();
+ args.forEach((k, v) -> stringArgs.put(k, String.valueOf(v)));
+ Object result = ToolRegistry.execute(tool, ctx, stringArgs);
+ try {
+ return (JsonObject) Jsoner.deserialize(String.valueOf(result));
+ } catch (Exception e) {
+ throw new IllegalStateException("Not JSON: " + result, e);
+ }
+ }
+
+ @Test
+ void theSharedSetHasNeutralNamesAndFlags() {
+ List<ToolDescriptor> shared = ToolRegistry.authoringTools();
+ List<String> names = shared.stream().map(ToolDescriptor::name).toList();
+ assertEquals(List.of("camel_catalog_doc", "camel_catalog_find", "camel_validate_source", "camel_get_files",
+ "camel_write_file", "camel_run", "camel_control", "camel_get_log", "camel_get_errors",
+ "camel_eval_expression", "camel_error_diagnose"), names);
+ for (ToolDescriptor td : shared) {
+ assertTrue(td.name().startsWith("camel_"), td.name());
+ assertFalse(td.description().isBlank(), td.name());
+ assertNotNull(td.executor(), td.name());
+ }
+ // what changes something is not read-only, so an access filter or a permission handler can tell
+ for (String mutating : List.of("camel_write_file", "camel_run", "camel_control")) {
+ assertFalse(ToolRegistry.findTool(mutating).isReadOnly(), mutating);
+ }
+ for (String reading : List.of("camel_catalog_doc", "camel_get_files", "camel_get_log", "camel_get_errors",
+ "camel_eval_expression", "camel_error_diagnose", "camel_validate_source")) {
+ assertTrue(ToolRegistry.findTool(reading).isReadOnly(), reading);
+ }
+ assertTrue(ToolRegistry.findTool("camel_control").isDestructive());
+ assertFalse(ToolRegistry.findTool("camel_catalog_find").isCore(), "not needed by a small model");
+ assertTrue(ToolRegistry.findTool("camel_write_file").isCore());
+ }
+
+ @Test
+ void inputSchemaListsTheParametersWithTypesAndTheRequiredOnes() {
+ JsonObject schema = ToolRegistry.findTool("camel_write_file").inputSchema();
+ assertEquals("object", schema.getString("type"));
+ JsonObject properties = schema.getMap("properties");
+ JsonObject file = properties.getMap("file");
+ JsonObject validate = properties.getMap("validate");
+ assertEquals("string", file.getString("type"));
+ assertEquals("boolean", validate.getString("type"));
+ assertEquals(List.of("file", "content"), List.copyOf(schema.getCollection("required")));
+ JsonObject logProperties = ToolRegistry.findTool("camel_get_log").inputSchema().getMap("properties");
+ JsonObject limit = logProperties.getMap("limit");
+ assertEquals("integer", limit.getString("type"));
+ }
+
+ @Test
+ void filesAreListedAndReadFromTheDirectoryArgument(@TempDir Path dir) throws IOException {
+ Files.writeString(dir.resolve("demo.camel.yaml"), VALID_ROUTE);
+ Files.writeString(dir.resolve("application.properties"), "camel.main.name=demo\n");
+ Files.createDirectory(dir.resolve("sub"));
+ JsonObject list = call("camel_get_files", new ToolContext(), Map.of("directory", dir.toString()));
+ assertEquals(2, list.getInteger("totalFiles"), "directories are not listed");
+ JsonObject first = (JsonObject) list.getCollection("files").iterator().next();
+ assertEquals("application.properties", first.getString("name"));
+ assertEquals("properties", first.getString("type"));
+ JsonObject file = call("camel_get_files", new ToolContext(),
+ Map.of("directory", dir.toString(), "file", "demo.camel.yaml"));
+ assertEquals(VALID_ROUTE, file.getString("content"));
+ assertEquals("yaml", file.getString("type"));
+ // the TUI fills the directory in from its selection; a server without one requires it
+ ToolContext selected = new ToolContext();
+ selected.setDefaultDirectory(dir);
+ assertEquals(2, call("camel_get_files", selected, Map.of()).getInteger("totalFiles"));
+ ToolExecutionException e = assertThrows(ToolExecutionException.class,
+ () -> ToolRegistry.execute("camel_get_files", new ToolContext(), Map.of()));
+ assertTrue(e.getMessage().contains("directory is required"), e.getMessage());
+ assertThrows(ToolExecutionException.class, () -> ToolRegistry.execute("camel_get_files", new ToolContext(),
+ Map.of("directory", dir.toString(), "file", "missing.yaml")));
+ }
+
+ @Test
+ void writeValidatesFirstAndRefusesInvalidContent(@TempDir Path dir) throws IOException {
+ Files.writeString(dir.resolve("demo.camel.yaml"), "- route: {}\n");
+ JsonObject invalid = call("camel_write_file", new ToolContext(),
+ Map.of("directory", dir.toString(), "file", "demo.camel.yaml", "content", INVALID_ROUTE));
+ assertEquals("invalid", invalid.getString("status"));
+ assertTrue(invalid.getCollection("errors").stream().anyMatch(m -> m.toString().contains("logLevel")),
+ invalid.toJson());
+ assertEquals("- route: {}\n", Files.readString(dir.resolve("demo.camel.yaml"), StandardCharsets.UTF_8));
+
+ JsonObject written = call("camel_write_file", new ToolContext(),
+ Map.of("directory", dir.toString(), "file", "demo.camel.yaml", "content", VALID_ROUTE));
+ assertEquals("overwritten", written.getString("status"));
+ assertEquals(VALID_ROUTE, Files.readString(dir.resolve("demo.camel.yaml"), StandardCharsets.UTF_8));
+ assertEquals(10, written.getInteger("lines"));
+
+ JsonObject created = call("camel_write_file", new ToolContext(),
+ Map.of("directory", dir.toString(), "file", "notes.txt", "content", "logLevel"));
+ assertEquals("created", created.getString("status"), "other file types are not validated");
+ // validation can be switched off, and a properties file is validated too
+ assertEquals("invalid", call("camel_write_file", new ToolContext(), Map.of("directory", dir.toString(),
+ "file", "application.properties", "content", "camel.main.nme=x")).getString("status"));
+ assertEquals("created", call("camel_write_file", new ToolContext(), Map.of("directory", dir.toString(),
+ "file", "application.properties", "content", "camel.main.nme=x", "validate", false))
+ .getString("status"));
+ }
+
+ @Test
+ void fileNamesStayInsideTheDirectory(@TempDir Path dir) {
+ for (String bad : List.of("../etc/passwd", "sub/x.yaml", "/tmp/x.yaml")) {
+ ToolExecutionException e = assertThrows(ToolExecutionException.class,
+ () -> ToolRegistry.execute("camel_write_file", new ToolContext(),
+ Map.of("directory", dir.toString(), "file", bad, "content", "x")));
+ assertTrue(e.getMessage().contains("plain file name"), bad + ": " + e.getMessage());
+ }
+ }
+
+ @Test
+ void validateSourceChecksContentOrAnExistingFile(@TempDir Path dir) throws IOException {
+ JsonObject content = call("camel_validate_source", new ToolContext(),
+ Map.of("file", "new.camel.yaml", "content", INVALID_ROUTE));
+ assertFalse(content.getBoolean("valid"));
+ assertEquals(1, content.getCollection("errors").size());
+ assertTrue(call("camel_validate_source", new ToolContext(),
+ Map.of("file", "new.camel.yaml", "content", VALID_ROUTE)).getBoolean("valid"));
+
+ Files.writeString(dir.resolve("demo.camel.yaml"), INVALID_ROUTE);
+ JsonObject file = call("camel_validate_source", new ToolContext(),
+ Map.of("directory", dir.toString(), "file", "demo.camel.yaml"));
+ assertFalse(file.getBoolean("valid"), "the file is read when no content is given");
+
+ ToolExecutionException e = assertThrows(ToolExecutionException.class,
+ () -> ToolRegistry.execute("camel_validate_source", new ToolContext(),
+ Map.of("file", "notes.txt", "content", "x")));
+ assertTrue(e.getMessage().contains("No validation for notes.txt"), e.getMessage());
+ }
+
+ @Test
+ void catalogFindAnswersAProtocolOrProductName() {
+ JsonObject result = call("camel_catalog_find", new ToolContext(), Map.of("term", "mqtt", "kind", "component"));
+ assertTrue(result.getInteger("count") > 0);
+ JsonObject first = (JsonObject) result.getCollection("matches").iterator().next();
+ assertEquals("component", first.getString("kind"));
+ assertTrue(first.getString("name").contains("mqtt"), first.toJson());
+ assertNotNull(first.get("syntax"));
+ }
+
+ @Test
+ void errorDiagnoseNamesTheExceptionAndTheComponent() {
+ String error = "org.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint:"
+ + " timer://tick?periodd=1000 due to: There are 1 parameters that couldn't be set on the endpoint";
+ JsonObject result = call("camel_error_diagnose", new ToolContext(), Map.of("error", error));
+ JsonObject summary = result.getMap("summary");
+ assertTrue(summary.getBoolean("diagnosed"));
+ JsonObject ex = (JsonObject) result.getCollection("identifiedExceptions").iterator().next();
+ assertEquals("ResolveEndpointFailedException", ex.getString("exception"));
+ assertFalse(ex.getCollection("suggestedFixes").isEmpty());
+ assertTrue(result.getCollection("identifiedComponents").stream()
+ .anyMatch(c -> "timer".equals(((JsonObject) c).getString("name"))), result.toJson());
+ JsonObject none = call("camel_error_diagnose", new ToolContext(), Map.of("error", "nothing camel here"))
+ .getMap("summary");
+ assertFalse(none.getBoolean("diagnosed"));
+ }
+
+ @Test
+ void runtimeToolsSayWhatToDoWithoutAnIntegration() {
+ ToolExecutionException e = assertThrows(ToolExecutionException.class,
+ () -> ToolRegistry.execute("camel_get_errors", new ToolContext(), Map.of("name", "no-such-app-xyz")));
+ assertTrue(e.getMessage().contains("no-such-app-xyz"), e.getMessage());
+ e = assertThrows(ToolExecutionException.class,
+ () -> ToolRegistry.execute("camel_control", new ToolContext(), Map.of("action", "stop", "name",
+ "no-such-app-xyz")));
+ assertTrue(e.getMessage().contains("no-such-app-xyz"), e.getMessage());
+ }
+}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistryCatalogDocTest.java b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/CatalogDocsTest.java
similarity index 88%
rename from dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistryCatalogDocTest.java
rename to dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/CatalogDocsTest.java
index 1d8d3de1ebe4..bd0b9cfb7f52 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistryCatalogDocTest.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/CatalogDocsTest.java
@@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.camel.dsl.jbang.core.commands.tui;
+package org.apache.camel.dsl.jbang.core.commands.ai;
import java.util.Collection;
import java.util.HashMap;
@@ -30,13 +30,31 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
-class TuiToolRegistryCatalogDocTest {
+/**
+ * The shared camel_catalog_doc tool, as the TUI's AI panel and every Camel MCP server expose it: written for what a
+ * small model gets wrong most (a path option as a query parameter, an operator inside a simple placeholder).
+ */
+class CatalogDocsTest {
private static JsonObject catalogDoc(Map<String, Object> args) throws Exception {
- String json = new TuiToolRegistry(null).execute("tui_catalog_doc", new JsonObject(args));
+ Map<String, String> stringArgs = new HashMap<>();
+ args.forEach((k, v) -> stringArgs.put(k, String.valueOf(v)));
+ String json = String.valueOf(ToolRegistry.execute("camel_catalog_doc", new ToolContext(), stringArgs));
return (JsonObject) Jsoner.deserialize(json);
}
+ @Test
+ void theToolIsSharedAndInTheCoreSubset() {
+ ToolDescriptor td = ToolRegistry.findTool("camel_catalog_doc");
+ assertTrue(td.isCore(), "local models get it too");
+ assertTrue(td.isReadOnly());
+ assertTrue(ToolRegistry.authoringTools().contains(td));
+ JsonObject schema = td.inputSchema();
+ assertEquals("object", schema.getString("type"));
+ assertTrue(schema.getMap("properties").containsKey("endpoint"));
+ assertNull(schema.get("required"), "name or endpoint, neither alone is required");
+ }
+
@Test
void simpleLanguageListsItsFunctionsAndOperatorsCompactly() throws Exception {
JsonObject result = catalogDoc(Map.of("name", "simple", "kind", "language"));
diff --git a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/ExpressionEvaluatorTest.java b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/ExpressionEvaluatorTest.java
new file mode 100644
index 000000000000..a314d398405f
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/ExpressionEvaluatorTest.java
@@ -0,0 +1,68 @@
+/*
+ * 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 org.apache.camel.util.json.JsonObject;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ExpressionEvaluatorTest {
+
+ @Test
+ void predicatesAreRecognisedByTheirOperators() {
+ assertTrue(ExpressionEvaluator.looksLikePredicate("${body} > 200 && ${body} < 300"));
+ assertTrue(ExpressionEvaluator.looksLikePredicate("${header.type} in 'gold,silver'"));
+ assertTrue(ExpressionEvaluator.looksLikePredicate("${header.foo} == 'bar' || ${header.bar} != null"));
+ assertTrue(ExpressionEvaluator.looksLikePredicate("${header.title} contains 'Camel'"));
+ assertFalse(ExpressionEvaluator.looksLikePredicate("${random(1,10)}"));
+ assertFalse(ExpressionEvaluator.looksLikePredicate("${header.user} ?: 'Guest'"), "elvis gives a value");
+ assertFalse(ExpressionEvaluator.looksLikePredicate("${header.a} == 'x' ? 'yes' : 'no'"),
+ "ternary gives a value");
+ assertFalse(ExpressionEvaluator.looksLikePredicate("Hello ${body}, price>100"),
+ "operators need spaces around them");
+ assertFalse(ExpressionEvaluator.looksLikePredicate(null));
+ }
+
+ @Test
+ void evaluatesLocallyWithoutARunningIntegration() {
+ ToolContext ctx = new ToolContext();
+ JsonObject value = ExpressionEvaluator.evaluate(ctx, null, "Hello ${body}", "Camel");
+ assertEquals("ok", value.getString("status"));
+ assertEquals("Hello Camel", value.getString("result"));
+ assertEquals("simple", value.getString("language"));
+ assertNull(value.get("predicate"));
+
+ JsonObject predicate = ExpressionEvaluator.evaluate(ctx, "simple", "${body} == 'Camel'", "Camel");
+ assertTrue(predicate.getBoolean("predicate"));
+ assertEquals("true", predicate.getString("result"));
+
+ JsonObject note = ExpressionEvaluator.evaluate(ctx, "simple", "${body.length()}", null);
+ assertTrue(note.getString("note").contains("empty body"));
+
+ JsonObject error = ExpressionEvaluator.evaluate(ctx, "simple", "${header.foo ?: 'x'}", null);
+ assertEquals("error", error.getString("status"), "the operator is inside the placeholder");
+ assertFalse(error.getString("error").isBlank());
+
+ JsonObject unknown = ExpressionEvaluator.evaluate(ctx, "no-such-language", "x", null);
+ assertEquals("error", unknown.getString("status"));
+ assertTrue(unknown.getString("error").contains("no-such-language"));
+ }
+}
diff --git a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/LogFileReaderTest.java b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/LogFileReaderTest.java
new file mode 100644
index 000000000000..253a614ae02d
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/LogFileReaderTest.java
@@ -0,0 +1,66 @@
+/*
+ * 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.List;
+
+import org.apache.camel.util.json.JsonObject;
+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;
+
+class LogFileReaderTest {
+
+ private static final List<String> LINES = List.of(
+ "2026-09-12 10:00:00.001 INFO 42 --- [ main] org.apache.camel.main.MainSupport : Apache Camel 4.23.0 is starting",
+ "2026-09-12 10:00:01.002 WARN 42 --- [ main] o.a.c.impl.engine.AbstractCamelContext : Routes startup (started:1)",
+ "2026-09-12 10:00:02.003 ERROR 42 --- [ timer://tick] org.apache.camel.processor.errorhandler.DefaultErrorHandler : Failed delivery",
+ "java.lang.IllegalStateException: boom",
+ "\tat org.example.Foo.bar(Foo.java:12)",
+ "\tat org.example.Foo.baz(Foo.java:34)",
+ "2026-09-12 10:00:03.004 INFO 42 --- [ timer://tick] route1 : Hello Camel");
+
+ @Test
+ void groupsContinuationLinesIntoTheRecordBeforeThemNewestFirst() {
+ JsonObject result = LogFileReader.build(LINES, 50, null, null, new JsonObject());
+ assertEquals(7, result.getInteger("totalLines"));
+ assertEquals(4, result.getInteger("returnedLines"));
+ List<JsonObject> rows = List.copyOf(result.getCollection("lines"));
+ assertEquals("Hello Camel", rows.get(0).getString("message"));
+ assertEquals("route1", rows.get(0).getString("logger"));
+ assertEquals("10:00:03.004", rows.get(0).getString("time"));
+ JsonObject error = rows.get(1);
+ assertEquals("ERROR", error.getString("level"));
+ assertEquals("DefaultErrorHandler", error.getString("logger"), "the logger is shortened to its class");
+ assertTrue(error.getString("detail").startsWith("java.lang.IllegalStateException: boom\n\tat"));
+ assertNull(rows.get(0).get("detail"));
+ }
+
+ @Test
+ void filtersByLevelAndTextAndHonoursTheLimit() {
+ JsonObject errors = LogFileReader.build(LINES, 50, null, "error", new JsonObject());
+ assertEquals(1, errors.getInteger("returnedLines"));
+ JsonObject boom = LogFileReader.build(LINES, 50, "BOOM", null, new JsonObject());
+ assertEquals(1, boom.getInteger("returnedLines"), "the filter also matches the detail block");
+ assertEquals("Failed delivery", ((JsonObject) boom.getCollection("lines").iterator().next())
+ .getString("message"));
+ assertEquals(2, LogFileReader.build(LINES, 2, null, null, new JsonObject()).getInteger("returnedLines"));
+ assertEquals(0, LogFileReader.build(List.of(), 2, null, null, new JsonObject()).getInteger("returnedLines"));
+ }
+}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/YamlEndpointValidationTest.java b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/SourceValidatorEndpointTest.java
similarity index 83%
rename from dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/YamlEndpointValidationTest.java
rename to dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/SourceValidatorEndpointTest.java
index 4ecba01df6b6..4e0702c55a95 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/YamlEndpointValidationTest.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/SourceValidatorEndpointTest.java
@@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.camel.dsl.jbang.core.commands.tui;
+package org.apache.camel.dsl.jbang.core.commands.ai;
import java.util.List;
@@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
-class YamlEndpointValidationTest {
+class SourceValidatorEndpointTest {
private static CamelCatalog catalog;
@@ -45,7 +45,7 @@ class YamlEndpointValidationTest {
steps:
- log: "${body}"
""";
- List<String> errors = SourceEditAssist.doValidateYamlEndpoints(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlEndpoints(yaml, catalog);
assertThat(errors).isEmpty();
}
@@ -60,7 +60,7 @@ class YamlEndpointValidationTest {
steps:
- log: "${body}"
""";
- List<String> errors = SourceEditAssist.doValidateYamlEndpoints(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlEndpoints(yaml, catalog);
assertThat(errors).isNotEmpty();
assertThat(errors.get(0)).contains("timer:");
assertThat(errors.get(0)).containsIgnoringCase("unknown");
@@ -76,7 +76,7 @@ class YamlEndpointValidationTest {
steps:
- log: "${body}"
""";
- List<String> errors = SourceEditAssist.doValidateYamlEndpoints(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlEndpoints(yaml, catalog);
assertThat(errors).isNotEmpty();
assertThat(errors.get(0)).contains("timer:");
}
@@ -88,7 +88,7 @@ class YamlEndpointValidationTest {
steps:
- to: log:myLogger
""";
- List<String> errors = SourceEditAssist.doValidateYamlEndpoints(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlEndpoints(yaml, catalog);
assertThat(errors).isEmpty();
}
@@ -99,7 +99,7 @@ class YamlEndpointValidationTest {
steps:
- log: "${body}"
""";
- List<String> errors = SourceEditAssist.doValidateYamlEndpoints(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlEndpoints(yaml, catalog);
assertThat(errors).isNotEmpty();
assertThat(errors.get(0)).contains("timer:");
assertThat(errors.get(0)).containsIgnoringCase("unknown");
@@ -113,7 +113,7 @@ class YamlEndpointValidationTest {
steps:
- log: "${body}"
""";
- List<String> errors = SourceEditAssist.doValidateYamlEndpoints(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlEndpoints(yaml, catalog);
assertThat(errors).isEmpty();
}
@@ -127,7 +127,7 @@ class YamlEndpointValidationTest {
steps:
- log: "${body}"
""";
- List<String> errors = SourceEditAssist.doValidateYamlEndpoints(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlEndpoints(yaml, catalog);
assertThat(errors).isEmpty();
}
@@ -141,7 +141,7 @@ class YamlEndpointValidationTest {
steps:
- log: "${body}"
""";
- List<String> errors = SourceEditAssist.doValidateYamlEndpoints(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlEndpoints(yaml, catalog);
assertThat(errors).isNotEmpty();
assertThat(errors.get(0)).contains("timer:");
}
@@ -159,7 +159,7 @@ class YamlEndpointValidationTest {
parameters:
badOption: xyz
""";
- List<String> errors = SourceEditAssist.doValidateYamlEndpoints(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlEndpoints(yaml, catalog);
assertThat(errors).isNotEmpty();
assertThat(errors).allSatisfy(e -> assertThat(e).contains("log:"));
assertThat(errors).noneSatisfy(e -> assertThat(e).contains("timer:"));
@@ -172,7 +172,7 @@ class YamlEndpointValidationTest {
steps:
- log: "${body}"
""";
- List<String> errors = SourceEditAssist.doValidateYamlEndpoints(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlEndpoints(yaml, catalog);
assertThat(errors).isEmpty();
}
@@ -186,7 +186,7 @@ class YamlEndpointValidationTest {
steps:
- log: "${body}"
""";
- List<String> errors = SourceEditAssist.doValidateYamlEndpoints(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlEndpoints(yaml, catalog);
assertThat(errors).isEmpty();
}
@@ -201,7 +201,7 @@ class YamlEndpointValidationTest {
steps:
- log: "${body}"
""";
- List<String> errors = SourceEditAssist.doValidateYamlEndpoints(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlEndpoints(yaml, catalog);
assertThat(errors).isEmpty();
}
@@ -212,7 +212,7 @@ class YamlEndpointValidationTest {
steps:
- to: seda:myQueue?badOption=xyz
""";
- List<String> errors = SourceEditAssist.doValidateYamlEndpoints(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlEndpoints(yaml, catalog);
assertThat(errors).hasSize(1);
assertThat(errors.get(0)).contains("seda:");
}
@@ -231,7 +231,7 @@ class YamlEndpointValidationTest {
- to:
uri: seda:result
""";
- List<String> errors = SourceEditAssist.doValidateYamlEndpoints(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlEndpoints(yaml, catalog);
assertThat(errors).isEmpty();
}
@@ -250,7 +250,7 @@ class YamlEndpointValidationTest {
- log:
message: "${body}"
""";
- List<String> errors = SourceEditAssist.doValidateYamlEndpoints(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlEndpoints(yaml, catalog);
assertThat(errors).isNotEmpty();
assertThat(errors).anyMatch(e -> e.contains("timer:") && e.contains("bridgeErrorHandler2"));
}
@@ -270,7 +270,7 @@ class YamlEndpointValidationTest {
- log:
message: "${body}"
""";
- List<String> errors = SourceEditAssist.doValidateYamlEndpoints(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlEndpoints(yaml, catalog);
assertThat(errors).isEmpty();
}
@@ -285,7 +285,7 @@ class YamlEndpointValidationTest {
steps:
- log: "${body}"
""";
- List<String> errors = SourceEditAssist.doValidateYamlEndpoints(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlEndpoints(yaml, catalog);
assertThat(errors).isEmpty();
}
}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/YamlSimpleValidationTest.java b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/SourceValidatorSimpleTest.java
similarity index 84%
rename from dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/YamlSimpleValidationTest.java
rename to dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/SourceValidatorSimpleTest.java
index e9cb6a631e51..9c8350189c3b 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/YamlSimpleValidationTest.java
+++ b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/ai/SourceValidatorSimpleTest.java
@@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.camel.dsl.jbang.core.commands.tui;
+package org.apache.camel.dsl.jbang.core.commands.ai;
import java.util.List;
@@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
-class YamlSimpleValidationTest {
+class SourceValidatorSimpleTest {
private static CamelCatalog catalog;
@@ -43,7 +43,7 @@ class YamlSimpleValidationTest {
- setBody:
simple: "${body}"
""";
- List<String> errors = SourceEditAssist.doValidateYamlSimple(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlSimple(yaml, catalog);
assertThat(errors).isEmpty();
}
@@ -56,7 +56,7 @@ class YamlSimpleValidationTest {
- setBody:
simple: "${body"
""";
- List<String> errors = SourceEditAssist.doValidateYamlSimple(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlSimple(yaml, catalog);
assertThat(errors).hasSize(1);
assertThat(errors.get(0)).contains("Simple syntax error");
}
@@ -70,7 +70,7 @@ class YamlSimpleValidationTest {
- filter:
simple: "${header.foo} == 'bar'"
""";
- List<String> errors = SourceEditAssist.doValidateYamlSimple(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlSimple(yaml, catalog);
assertThat(errors).isEmpty();
}
@@ -85,7 +85,7 @@ class YamlSimpleValidationTest {
simple:
expression: "${header.name}"
""";
- List<String> errors = SourceEditAssist.doValidateYamlSimple(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlSimple(yaml, catalog);
assertThat(errors).isEmpty();
}
@@ -100,7 +100,7 @@ class YamlSimpleValidationTest {
simple:
expression: "${body"
""";
- List<String> errors = SourceEditAssist.doValidateYamlSimple(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlSimple(yaml, catalog);
assertThat(errors).hasSize(1);
assertThat(errors.get(0)).contains("Simple syntax error");
}
@@ -114,7 +114,7 @@ class YamlSimpleValidationTest {
- setBody:
simple: "{{myPlaceholder}}"
""";
- List<String> errors = SourceEditAssist.doValidateYamlSimple(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlSimple(yaml, catalog);
assertThat(errors).isEmpty();
}
@@ -127,7 +127,7 @@ class YamlSimpleValidationTest {
- log:
message: "${body"
""";
- List<String> errors = SourceEditAssist.doValidateYamlSimple(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlSimple(yaml, catalog);
assertThat(errors).hasSize(1);
assertThat(errors.get(0)).contains("Simple syntax error");
}
@@ -141,7 +141,7 @@ class YamlSimpleValidationTest {
- log:
message: "Order: ${body}"
""";
- List<String> errors = SourceEditAssist.doValidateYamlSimple(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlSimple(yaml, catalog);
assertThat(errors).isEmpty();
}
@@ -158,7 +158,7 @@ class YamlSimpleValidationTest {
steps:
- log: "big"
""";
- List<String> errors = SourceEditAssist.doValidateYamlSimple(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlSimple(yaml, catalog);
assertThat(errors).hasSize(1);
assertThat(errors.get(0)).contains("Simple syntax error");
}
@@ -175,7 +175,7 @@ class YamlSimpleValidationTest {
steps:
- log: "big"
""";
- List<String> errors = SourceEditAssist.doValidateYamlSimple(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlSimple(yaml, catalog);
assertThat(errors).isEmpty();
}
@@ -191,7 +191,7 @@ class YamlSimpleValidationTest {
name: foo
simple: "${header.bar"
""";
- List<String> errors = SourceEditAssist.doValidateYamlSimple(yaml, catalog);
+ List<String> errors = SourceValidator.validateYamlSimple(yaml, catalog);
assertThat(errors).hasSizeGreaterThanOrEqualTo(2);
}
}
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
new file mode 100644
index 000000000000..4f3e86911d94
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/AuthoringTools.java
@@ -0,0 +1,198 @@
+/*
+ * 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.util.LinkedHashMap;
+import java.util.Map;
+
+import jakarta.enterprise.context.ApplicationScoped;
+
+import io.quarkiverse.mcp.server.Tool;
+import io.quarkiverse.mcp.server.ToolArg;
+import io.quarkiverse.mcp.server.ToolCallException;
+import org.apache.camel.dsl.jbang.core.commands.ai.ToolContext;
+import org.apache.camel.dsl.jbang.core.commands.ai.ToolExecutionException;
+import org.apache.camel.dsl.jbang.core.commands.ai.ToolRegistry;
+import org.apache.camel.util.json.JsonObject;
+
+/**
+ * The neutral Camel authoring tools shared with {@code camel tui --mcp} (CAMEL-24695): thin MCP wrappers over the
+ * {@link ToolRegistry}, so an AI agent gets the same tools, names and answers through either server. The logic lives in
+ * camel-jbang-core ({@code AuthoringTools} there); these methods only carry the MCP annotations the security
+ * interceptor and access filter work on, and pass the arguments through.
+ * <p>
+ * Writing a file is validated first and refused when the content is invalid, but nobody is asked before the write: the
+ * MCP client (Claude Code, Cursor, and the others ask before a non read-only tool runs) is where the human sits. The
+ * {@code read-only} access level hides the tools that write, run and control.
+ */
+@ApplicationScoped
+public class AuthoringTools {
+
+ 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 DIRECTORY_DESC = "Project directory with the source files (absolute path)";
+
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
+ description = "Camel catalog documentation of a component, data format, language or EIP (description, "
+ + "options, Maven coordinates), with the URI rules of a component. For simple also its syntax "
+ + "rules, functions and operators: count and names by group, or with optionsFilter the "
+ + "matching ones with parameters and examples. endpoint validates a URI: unknown or invalid "
+ + "options, missing path. Replaces the former AsciiDoc-only camel_catalog_doc: includeDoc=true "
+ + "adds the AsciiDoc page.")
+ public JsonObject camel_catalog_doc(
+ @ToolArg(description = "Name, e.g. kafka, json-jackson, simple, timer, choice, split") String name,
+ @ToolArg(description = "Endpoint URI to check, e.g. kafka:orders?brokers=host:9092") String endpoint,
+ @ToolArg(description = "component, dataformat, language or eip (auto-detected)") String kind,
+ @ToolArg(description = "Include the options (default true)") Boolean includeOptions,
+ @ToolArg(description = "Include the full AsciiDoc page (default false)") Boolean includeDoc,
+ @ToolArg(description = "A language doc sub-page (simple: functions, operators, ognl, advanced) to return"
+ + " as text") String docPage,
+ @ToolArg(description = "Keyword to match in option names or descriptions") String optionsFilter,
+ @ToolArg(description = VERSION_DESC) String camelVersion) {
+ return call("camel_catalog_doc", args("name", name, "endpoint", endpoint, "kind", kind,
+ "includeOptions", includeOptions, "includeDoc", includeDoc, "docPage", docPage,
+ "optionsFilter", optionsFilter, "camelVersion", camelVersion));
+ }
+
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
+ description = "Finds Camel components, data formats and languages by a protocol, product or other term that "
+ + "is not the exact name (mqtt, s3, snowflake, csv): best match first with title and "
+ + "description. camel_catalog_doc then gives the options of one.")
+ public JsonObject camel_catalog_find(
+ @ToolArg(description = "What to look for, e.g. mqtt, s3, database, csv") String term,
+ @ToolArg(description = "component, dataformat or language (default: all)") String kind,
+ @ToolArg(description = "Maximum matches per kind (default 10)") Integer limit,
+ @ToolArg(description = VERSION_DESC) String camelVersion) {
+ return call("camel_catalog_find", args("term", term, "kind", kind, "limit", limit,
+ "camelVersion", camelVersion));
+ }
+
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
+ description = "Validates Camel YAML DSL or .properties source without writing: schema (misspelled options "
+ + "such as logLevel instead of loggingLevel), endpoint URIs, simple expressions, camel.* "
+ + "options. Use on content before writing it, or on an existing file (no content) to explain "
+ + "a reload error.")
+ public JsonObject camel_validate_source(
+ @ToolArg(description = DIRECTORY_DESC + "; needed when no content is given") String directory,
+ @ToolArg(description = "File name; picks the checks by extension, read when no content") String file,
+ @ToolArg(description = "The source to validate") String content,
+ @ToolArg(description = VERSION_DESC) String camelVersion) {
+ return call("camel_validate_source", args("directory", directory, "file", file, "content", content,
+ "camelVersion", camelVersion));
+ }
+
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
+ description = "The source files of a project directory: without file the list (name, size, type), with "
+ + "file its content. Use before editing to see the routes, configuration and other files of "
+ + "the integration.")
+ public JsonObject camel_get_files(
+ @ToolArg(description = DIRECTORY_DESC) String directory,
+ @ToolArg(description = "File name to read; omitted lists the files") String file) {
+ return call("camel_get_files", args("directory", directory, "file", file));
+ }
+
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = false, openWorldHint = false),
+ description = "Writes the complete content of a file in the project directory. YAML and .properties "
+ + "content is validated first; invalid content is not written and the errors are returned. "
+ + "An integration running in dev mode reloads the change, otherwise restart it with "
+ + "camel_control.")
+ public JsonObject camel_write_file(
+ @ToolArg(description = DIRECTORY_DESC) String directory,
+ @ToolArg(description = "File name, no path") String file,
+ @ToolArg(description = "The complete new content") String content,
+ @ToolArg(description = "Validate before writing (default true)") Boolean validate,
+ @ToolArg(description = VERSION_DESC) String camelVersion) {
+ return call("camel_write_file", args("directory", directory, "file", file, "content", content,
+ "validate", validate, "camelVersion", camelVersion));
+ }
+
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = false, openWorldHint = true),
+ description = "Starts an integration from a project directory with camel run in a separate process, in dev "
+ + "mode by default (route files reload when written). Returns the pid and log file once it is "
+ + "up; camel_get_log and camel_get_errors then tell how it does, camel_control stops it.")
+ public JsonObject camel_run(
+ @ToolArg(description = "Project directory to run in (absolute path)") String directory,
+ @ToolArg(description = "Source files to run, comma-separated (default: every route file in the"
+ + " directory)") String files,
+ @ToolArg(description = "Integration name (default: from the first file)") String name,
+ @ToolArg(description = "Dev mode with reload on file change (default true)") Boolean dev) {
+ return call("camel_run", args("directory", directory, "files", files, "name", name, "dev", dev));
+ }
+
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = true, openWorldHint = false),
+ description = "Controls a running integration: stop (graceful), kill, restart (picks up edited files "
+ + "without dev mode), stop-routes, start-routes, reset-stats (clears statistics, routes "
+ + "untouched). Never stop, kill or restart unless the user asked for it.")
+ public JsonObject camel_control(
+ @ToolArg(description = "stop, kill, restart, stop-routes, start-routes or reset-stats") String action,
+ @ToolArg(description = NAME_DESC) String name) {
+ return call("camel_control", args("action", action, "name", name));
+ }
+
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
+ description = "Recent log records of a running integration, newest first, with optional filtering; a "
+ + "stack trace comes as one record with a detail block.")
+ public JsonObject camel_get_log(
+ @ToolArg(description = NAME_DESC) String name,
+ @ToolArg(description = "Maximum records to return (default 50)") Integer limit,
+ @ToolArg(description = "Case-insensitive substring filter on the message") String filter,
+ @ToolArg(description = "Only this log level (INFO, WARN, ERROR, DEBUG, TRACE)") String level) {
+ return call("camel_get_log", args("name", name, "limit", limit, "filter", filter, "level", level));
+ }
+
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
+ description = "The failed exchanges of a running integration: routeId, exchangeId, exception with stack "
+ + "trace, body and headers.")
+ public JsonObject camel_get_errors(
+ @ToolArg(description = NAME_DESC) String name) {
+ return call("camel_get_errors", args("name", name));
+ }
+
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
+ description = "Evaluates an expression: in the running integration when there is one, else locally. "
+ + "Returns the value (true/false for a predicate) or the syntax error, so check simple before "
+ + "answering or writing it.")
+ public JsonObject camel_eval_expression(
+ @ToolArg(description = "e.g. ${random(1,10)} or ${body} ?: 'none'") String expression,
+ @ToolArg(description = "simple (default), jsonpath, xpath, jq") String language,
+ @ToolArg(description = "Message body") String body,
+ @ToolArg(description = NAME_DESC) String name) {
+ return call("camel_eval_expression", args("expression", expression, "language", language, "body", body,
+ "name", name));
+ }
+
+ /** Runs the registry tool of the same name and hands its JSON back; a tool error becomes an MCP tool error. */
+ static JsonObject call(String tool, Map<String, String> args) {
+ try {
+ return RuntimeTools.toJsonObject(ToolRegistry.execute(tool, new ToolContext(), args));
+ } catch (ToolExecutionException e) {
+ throw new ToolCallException(e.getMessage(), e);
+ }
+ }
+
+ /** Name and value pairs into the string arguments of the registry; a null value is left out. */
+ static Map<String, String> args(Object... pairs) {
+ Map<String, String> map = new LinkedHashMap<>();
+ for (int i = 0; i + 1 < pairs.length; i += 2) {
+ Object value = pairs[i + 1];
+ if (value != null) {
+ map.put(String.valueOf(pairs[i]), String.valueOf(value));
+ }
+ }
+ return map;
+ }
+}
diff --git a/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/CatalogTools.java b/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/CatalogTools.java
index 22298f6ee71f..5a3b862a307d 100644
--- a/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/CatalogTools.java
+++ b/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/CatalogTools.java
@@ -391,8 +391,8 @@ public class CatalogTools {
*/
@Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
description = "List available AsciiDoc documentation page names from the catalog. "
- + "Returns page names (without .adoc extension) that can be passed to camel_catalog_doc "
- + "to retrieve the full documentation content. "
+ + "Returns page names (without .adoc extension), e.g. kafka-component or split-eip; "
+ + "camel_catalog_doc with includeDoc=true (name kafka, kind component) returns the page. "
+ "Unlike the structured tools (camel_catalog_component_doc, camel_catalog_eip_doc, etc.) "
+ "which return parsed JSON with options and metadata, "
+ "the AsciiDoc pages contain the full human-readable documentation "
@@ -432,59 +432,6 @@ public class CatalogTools {
}
}
- /**
- * Tool to get the full AsciiDoc documentation content for a catalog page.
- */
- @Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
- description = "Get the full AsciiDoc documentation page from the catalog. "
- + "Returns the complete human-readable documentation with usage examples, "
- + "code snippets, configuration guides, and best practices. "
- + "This complements the structured tools (camel_catalog_component_doc, "
- + "camel_catalog_eip_doc, etc.) which return parsed JSON with options and metadata. "
- + "Use camel_catalog_docs to discover available page names. "
- + "Naming conventions: components use '<name>-component' (e.g., 'kafka-component'), "
- + "data formats use '<name>-dataformat' (e.g., 'jackson-dataformat'), "
- + "languages use '<name>-language' (e.g., 'simple-language'), "
- + "EIPs use '<name>-eip' (e.g., 'split-eip'), "
- + "and others use their plain name (e.g., 'cloudevents', 'debug'). "
- + "Only available from Camel 4.22 onwards.")
- public DocResult camel_catalog_doc(
- @ToolArg(description = "Documentation page name without .adoc extension "
- + "(e.g., 'kafka-component', 'split-eip', 'simple-language', 'jackson-dataformat')") String name,
- @ToolArg(description = ToolArgDocs.CAMEL_VERSION) String camelVersion) {
-
- if (name == null || name.isBlank()) {
- throw new ToolCallException("Documentation page name is required", null);
- }
-
- try {
- CamelCatalog cat = catalogService.loadCatalog(null, camelVersion, null);
- String content = cat.asciiDoc(name);
- if (content == null) {
- List<String> allNames = cat.findDocNames();
- if (allNames != null) {
- String lower = name.toLowerCase();
- List<String> suggestions = allNames.stream()
- .filter(n -> n.toLowerCase().contains(lower) || lower.contains(n.toLowerCase()))
- .limit(5)
- .collect(Collectors.toList());
- if (!suggestions.isEmpty()) {
- throw new ToolCallException(
- "Documentation page not found: " + name + ". Did you mean one of: " + suggestions, null);
- }
- }
- throw new ToolCallException("Documentation page not found: " + name, null);
- }
- return new DocResult(name, content);
- } catch (ToolCallException e) {
- throw e;
- } catch (Throwable e) {
- throw new ToolCallException(
- "Failed to load documentation: " + name + " (" + e.getClass().getName() + "): " + e.getMessage(),
- null);
- }
- }
-
private static List<String> findComponentNames(CamelCatalog catalog) {
List<String> answer = catalog.findComponentNames();
if (answer == null) {
@@ -835,7 +782,4 @@ public class CatalogTools {
public record DocListResult(int total, int returned, List<String> names) {
}
-
- public record DocResult(String name, String content) {
- }
}
diff --git a/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/DiagnoseData.java b/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/DiagnoseData.java
index f65da48865db..9f1e2cf1da39 100644
--- a/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/DiagnoseData.java
+++ b/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/DiagnoseData.java
@@ -16,447 +16,12 @@
*/
package org.apache.camel.dsl.jbang.core.commands.mcp;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
import jakarta.enterprise.context.ApplicationScoped;
-import org.apache.camel.util.json.JsonArray;
-import org.apache.camel.util.json.JsonObject;
-
/**
- * Shared holder for Camel exception diagnostic reference data used by both {@link DiagnoseTools} (MCP Tool) and
- * {@link DiagnoseResources} (MCP Resources).
- * <p>
- * Contains the registry of known Camel exceptions with their descriptions, common causes, suggested fixes, and
- * documentation links.
+ * The CDI bean the diagnose resources inject; the reference data itself lives in camel-jbang-core so the shared
+ * {@code camel_error_diagnose} tool and the TUI use the same table.
*/
@ApplicationScoped
-public class DiagnoseData {
-
- public static final String CAMEL_DOC_BASE = "https://camel.apache.org/";
- public static final String CAMEL_COMPONENT_DOC = CAMEL_DOC_BASE + "components/next/";
- public static final String CAMEL_MANUAL_DOC = CAMEL_DOC_BASE + "manual/";
- public static final String CAMEL_EIP_DOC = CAMEL_COMPONENT_DOC + "eips/";
-
- /**
- * Component doc base URL for a specific Camel version.
- *
- * @param version the version segment (e.g., "4.18.x", "4.14.x"), or null/"next" for the latest development docs
- */
- public static String componentDocBase(String version) {
- String v = (version == null || version.isBlank() || "next".equals(version)) ? "next" : version;
- return CAMEL_DOC_BASE + "components/" + v + "/";
- }
-
- /**
- * EIP doc base URL for a specific Camel version.
- */
- public static String eipDocBase(String version) {
- return componentDocBase(version) + "eips/";
- }
-
- /**
- * Resolve documentation links for a specific version by replacing the "next" version segment in component/EIP doc
- * URLs with the specified version. Manual URLs (which have no version segment) are left unchanged.
- *
- * @param links the original documentation links (using "next")
- * @param version the target version (e.g., "4.18.x"), or null/"next" to keep defaults
- */
- public static List<String> resolveDocLinks(List<String> links, String version) {
- if (version == null || version.isBlank() || "next".equals(version)) {
- return links;
- }
- List<String> resolved = new ArrayList<>(links.size());
- for (String link : links) {
- resolved.add(link.replace("components/next/", "components/" + version + "/"));
- }
- return resolved;
- }
-
- private static final Map<String, ExceptionInfo> KNOWN_EXCEPTIONS;
-
- static {
- Map<String, ExceptionInfo> exceptions = new LinkedHashMap<>();
-
- exceptions.put("NoSuchEndpointException", new ExceptionInfo(
- "The specified endpoint URI could not be resolved to any known Camel component.",
- List.of(
- "Typo in the endpoint URI scheme (e.g., 'kafak:' instead of 'kafka:')",
- "Missing component dependency in pom.xml or build.gradle",
- "Component not on the classpath",
- "Using a component scheme that does not exist"),
- List.of(
- "Verify the endpoint URI scheme is spelled correctly",
- "Add the required camel-<component> dependency to your project",
- "Check available components with 'camel-catalog' or the Camel documentation",
- "Ensure the component JAR is on the classpath"),
- List.of(
- CAMEL_MANUAL_DOC + "component.html")));
-
- exceptions.put("ResolveEndpointFailedException", new ExceptionInfo(
- "Failed to resolve or create an endpoint from the given URI. The URI syntax may be invalid or required options may be missing.",
- List.of(
- "Invalid endpoint URI syntax",
- "Missing required endpoint options",
- "Unknown or misspelled endpoint options",
- "Invalid option values (wrong type or format)",
- "Special characters in URI not properly encoded"),
- List.of(
- "Check the endpoint URI syntax against the component documentation",
- "Ensure all required options are provided",
- "Verify option names are spelled correctly",
- "URL-encode special characters in the URI",
- "Use the endpoint DSL for type-safe endpoint configuration"),
- List.of(
- CAMEL_MANUAL_DOC + "endpoint.html",
- CAMEL_MANUAL_DOC + "uris.html")));
-
- exceptions.put("FailedToCreateRouteException", new ExceptionInfo(
- "A route could not be created. This is typically a configuration or wiring issue.",
- List.of(
- "Invalid endpoint URI in from() or to()",
- "Missing required component dependency",
- "Bean reference that cannot be resolved",
- "Invalid route configuration or DSL syntax",
- "Circular route dependencies"),
- List.of(
- "Check the full exception chain for the root cause",
- "Verify all endpoint URIs in the route are valid",
- "Ensure all referenced beans are available in the registry",
- "Validate the route DSL syntax",
- "Check for missing component dependencies"),
- List.of(
- CAMEL_MANUAL_DOC + "routes.html",
- CAMEL_MANUAL_DOC + "route-configuration.html")));
-
- exceptions.put("FailedToStartRouteException", new ExceptionInfo(
- "A route was created but could not be started. This often indicates a connectivity or resource issue.",
- List.of(
- "Cannot connect to external service (broker, database, etc.)",
- "Port already in use for server-side components",
- "Authentication/authorization failure",
- "Missing or invalid SSL/TLS configuration",
- "Resource not available (queue, topic, table, etc.)"),
- List.of(
- "Verify network connectivity to external services",
- "Check credentials and authentication configuration",
- "Ensure the target resource exists (queue, topic, etc.)",
- "Review SSL/TLS configuration if using secure connections",
- "Check if the port is already in use"),
- List.of(
- CAMEL_MANUAL_DOC + "routes.html",
- CAMEL_MANUAL_DOC + "lifecycle.html")));
-
- exceptions.put("NoTypeConversionAvailableException", new ExceptionInfo(
- "Camel could not find a type converter to convert between the required types.",
- List.of(
- "Trying to convert a message body to an incompatible type",
- "Missing type converter on the classpath",
- "Custom type without a registered converter",
- "Null body when a non-null type is expected"),
- List.of(
- "Check the source and target types in the conversion",
- "Add appropriate data format or converter dependency",
- "Use explicit marshal/unmarshal instead of implicit conversion",
- "Register a custom TypeConverter if needed",
- "Check if the message body is null"),
- List.of(
- CAMEL_MANUAL_DOC + "type-converter.html",
- CAMEL_MANUAL_DOC + "data-format.html")));
-
- exceptions.put("CamelExecutionException", new ExceptionInfo(
- "A wrapper exception thrown during route execution. The root cause is in the nested exception.",
- List.of(
- "Exception thrown by a processor or bean in the route",
- "External service failure (HTTP error, broker disconnect, etc.)",
- "Data transformation error",
- "Timeout during synchronous processing"),
- List.of(
- "Inspect the nested/caused-by exception for the actual error",
- "Add error handling (onException, errorHandler, doTry/doCatch) to the route",
- "Check the processor or bean that failed",
- "Review the full stack trace for the root cause"),
- List.of(
- CAMEL_MANUAL_DOC + "exception-clause.html",
- CAMEL_MANUAL_DOC + "error-handler.html",
- CAMEL_MANUAL_DOC + "try-catch-finally.html")));
-
- exceptions.put("ExchangeTimedOutException", new ExceptionInfo(
- "An exchange did not complete within the configured timeout period.",
- List.of(
- "Slow downstream service or endpoint",
- "Network latency or connectivity issues",
- "Timeout value too low for the operation",
- "Deadlock or resource contention",
- "Direct/SEDA consumer not available"),
- List.of(
- "Increase the timeout value if appropriate",
- "Add circuit breaker pattern for unreliable services",
- "Check network connectivity to the target service",
- "Use async processing for long-running operations",
- "Add timeout error handling in the route"),
- List.of(
- CAMEL_MANUAL_DOC + "request-reply.html",
- CAMEL_EIP_DOC + "circuitBreaker-eip.html")));
-
- exceptions.put("DirectConsumerNotAvailableException", new ExceptionInfo(
- "No consumer is available for a direct endpoint. The direct component requires an active consumer.",
- List.of(
- "Target route with the direct endpoint is not started",
- "Typo in the direct endpoint name",
- "Route with the direct consumer was stopped or removed",
- "Timing issue during startup — producer route started before consumer route"),
- List.of(
- "Ensure a route with from(\"direct:name\") exists and is started",
- "Verify the direct endpoint name matches between producer and consumer",
- "Use SEDA instead of direct if startup ordering is uncertain",
- "Configure route startup ordering if needed"),
- List.of(
- CAMEL_COMPONENT_DOC + "direct-component.html",
- CAMEL_COMPONENT_DOC + "seda-component.html")));
-
- exceptions.put("CamelExchangeException", new ExceptionInfo(
- "A general exception related to exchange processing.",
- List.of(
- "Processor failure during exchange handling",
- "Invalid exchange pattern (InOnly vs InOut mismatch)",
- "Missing required headers or properties",
- "Exchange body cannot be processed"),
- List.of(
- "Check the exchange pattern matches the endpoint requirements",
- "Verify required headers are set on the exchange",
- "Add error handling to catch and process the exception",
- "Inspect the exchange body type and content"),
- List.of(
- CAMEL_MANUAL_DOC + "exchange.html",
- CAMEL_MANUAL_DOC + "exchange-pattern.html")));
-
- exceptions.put("InvalidPayloadException", new ExceptionInfo(
- "The message payload (body) is not of the expected type and cannot be converted.",
- List.of(
- "Message body is null when a value is expected",
- "Message body type does not match the expected type",
- "Missing type converter for the body type",
- "Upstream processor produced unexpected output"),
- List.of(
- "Check the message body type before the failing processor",
- "Use convertBodyTo() to explicitly convert the body type",
- "Add a null check or default value for the body",
- "Add the appropriate data format dependency for marshalling/unmarshalling"),
- List.of(
- CAMEL_MANUAL_DOC + "message.html",
- CAMEL_MANUAL_DOC + "type-converter.html")));
-
- exceptions.put("PropertyBindingException", new ExceptionInfo(
- "Failed to bind a property or option to a Camel component, endpoint, or bean.",
- List.of(
- "Property name does not exist on the target object",
- "Property value has wrong type (e.g., string for a boolean)",
- "Misspelled property or option name",
- "Property placeholder could not be resolved"),
- List.of(
- "Check the property name spelling against the component documentation",
- "Verify the property value type matches the expected type",
- "Use property placeholders correctly: {{property.name}}",
- "Check application.properties or YAML configuration for correct keys"),
- List.of(
- CAMEL_MANUAL_DOC + "using-propertyplaceholder.html",
- CAMEL_MANUAL_DOC + "component.html")));
-
- exceptions.put("NoSuchBeanException", new ExceptionInfo(
- "A referenced bean could not be found in the Camel registry.",
- List.of(
- "Bean not registered in the Spring/CDI/Camel registry",
- "Typo in the bean name reference",
- "Bean class not on the classpath",
- "Missing @Named or @Component annotation on the bean class",
- "Bean definition not scanned by component scan"),
- List.of(
- "Verify the bean is registered with the correct name",
- "Check spelling of the bean reference",
- "Ensure the bean class has proper annotations (@Named, @Component, etc.)",
- "Verify component scanning includes the bean's package",
- "Register the bean manually in RouteBuilder configure() if needed"),
- List.of(
- CAMEL_MANUAL_DOC + "registry.html",
- CAMEL_MANUAL_DOC + "bean-binding.html")));
-
- exceptions.put("NoSuchHeaderException", new ExceptionInfo(
- "A required header was not found on the message.",
- List.of(
- "Header not set by upstream processors",
- "Header name is misspelled",
- "Header was removed by a previous processor",
- "Using wrong header constant name"),
- List.of(
- "Verify the header name matches what upstream processors set",
- "Use header constants from the component's class (e.g., KafkaConstants)",
- "Add a setHeader() before the processor that requires it",
- "Add a null check or default value for the header"),
- List.of(
- CAMEL_MANUAL_DOC + "message.html")));
-
- exceptions.put("PredicateValidationException", new ExceptionInfo(
- "A predicate validation failed. This is typically thrown by the validate() DSL or a filter condition.",
- List.of(
- "Message did not match the expected validation predicate",
- "Invalid or unexpected message content",
- "Predicate expression has a syntax error",
- "Null values in the expression evaluation"),
- List.of(
- "Review the predicate expression for correctness",
- "Check the message content matches the expected format",
- "Add error handling for validation failures",
- "Use a more lenient predicate or add default values"),
- List.of(
- CAMEL_EIP_DOC + "validate-eip.html",
- CAMEL_MANUAL_DOC + "predicate.html")));
-
- exceptions.put("NoSuchLanguageException", new ExceptionInfo(
- "The specified expression language is not available.",
- List.of(
- "Missing language dependency (e.g., camel-jsonpath, camel-xpath)",
- "Typo in the language name",
- "Using a language that does not exist"),
- List.of(
- "Add the required camel-<language> dependency",
- "Verify the language name is spelled correctly",
- "Use 'simple' language which is included in camel-core"),
- List.of(
- CAMEL_MANUAL_DOC + "languages.html")));
-
- exceptions.put("FailedToCreateConsumerException", new ExceptionInfo(
- "A consumer could not be created for the endpoint.",
- List.of(
- "Cannot connect to the source system (broker, server, etc.)",
- "Invalid consumer configuration options",
- "Authentication failure",
- "Missing required consumer options",
- "Resource does not exist (topic, queue, file path, etc.)"),
- List.of(
- "Verify connectivity to the source system",
- "Check the consumer configuration options",
- "Ensure credentials are correct",
- "Verify the target resource exists",
- "Check the full exception chain for the root cause"),
- List.of(
- CAMEL_MANUAL_DOC + "component.html")));
-
- exceptions.put("FailedToCreateProducerException", new ExceptionInfo(
- "A producer could not be created for the endpoint.",
- List.of(
- "Cannot connect to the target system",
- "Invalid producer configuration options",
- "Authentication failure",
- "Missing required producer options"),
- List.of(
- "Verify connectivity to the target system",
- "Check the producer configuration options",
- "Ensure credentials are correct",
- "Check the full exception chain for the root cause"),
- List.of(
- CAMEL_MANUAL_DOC + "component.html")));
-
- exceptions.put("CamelAuthorizationException", new ExceptionInfo(
- "An authorization check failed. The current identity does not have permission to perform the operation.",
- List.of(
- "Insufficient permissions for the user or service account",
- "Missing or expired authentication token",
- "Security policy denying the operation",
- "Incorrect RBAC or ACL configuration"),
- List.of(
- "Check the user/service account permissions",
- "Verify the authentication token is valid and not expired",
- "Review the security policies and ACLs",
- "Ensure the correct security provider is configured"),
- List.of(
- CAMEL_MANUAL_DOC + "security.html")));
-
- KNOWN_EXCEPTIONS = Collections.unmodifiableMap(exceptions);
- }
-
- /**
- * Get all known Camel exceptions with their diagnostic information.
- */
- public Map<String, ExceptionInfo> getKnownExceptions() {
- return KNOWN_EXCEPTIONS;
- }
-
- /**
- * Get diagnostic information for a specific exception by name.
- *
- * @return the exception info, or null if not found
- */
- public ExceptionInfo getException(String name) {
- return KNOWN_EXCEPTIONS.get(name);
- }
-
- /**
- * Get all known exception names.
- */
- public List<String> getExceptionNames() {
- return List.copyOf(KNOWN_EXCEPTIONS.keySet());
- }
-
- /**
- * Holds diagnostic information about a known Camel exception.
- */
- public record ExceptionInfo(
- String description,
- List<String> commonCauses,
- List<String> suggestedFixes,
- List<String> documentationLinks) {
-
- /**
- * Convert this exception info to a full JSON object with all fields.
- */
- public JsonObject toJson() {
- return toJson(null);
- }
-
- /**
- * Convert this exception info to a full JSON object, resolving doc links for the given version.
- *
- * @param version the Camel doc version (e.g., "4.18.x"), or null for "next"
- */
- public JsonObject toJson(String version) {
- JsonObject json = new JsonObject();
- json.put("description", description);
- json.put("commonCauses", toJsonArray(commonCauses));
- json.put("suggestedFixes", toJsonArray(suggestedFixes));
- json.put("documentationLinks", toJsonArray(resolveDocLinks(documentationLinks, version)));
- return json;
- }
-
- /**
- * Convert this exception info to a summary JSON object (description and doc links only).
- */
- public JsonObject toSummaryJson() {
- return toSummaryJson(null);
- }
-
- /**
- * Convert this exception info to a summary JSON object, resolving doc links for the given version.
- *
- * @param version the Camel doc version (e.g., "4.18.x"), or null for "next"
- */
- public JsonObject toSummaryJson(String version) {
- JsonObject json = new JsonObject();
- json.put("description", description);
- json.put("documentationLinks", toJsonArray(resolveDocLinks(documentationLinks, version)));
- return json;
- }
-
- private static JsonArray toJsonArray(List<String> items) {
- JsonArray array = new JsonArray();
- for (String item : items) {
- array.add(item);
- }
- return array;
- }
- }
+public class DiagnoseData extends org.apache.camel.dsl.jbang.core.commands.ai.DiagnoseData {
}
diff --git a/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/DiagnoseTools.java b/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/DiagnoseTools.java
index 6a473a662c5d..b3d8dcfb2dac 100644
--- a/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/DiagnoseTools.java
+++ b/dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/DiagnoseTools.java
@@ -16,11 +16,6 @@
*/
package org.apache.camel.dsl.jbang.core.commands.mcp;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -28,8 +23,9 @@ import io.quarkiverse.mcp.server.Tool;
import io.quarkiverse.mcp.server.ToolArg;
import io.quarkiverse.mcp.server.ToolCallException;
import org.apache.camel.catalog.CamelCatalog;
-import org.apache.camel.tooling.model.ComponentModel;
-import org.apache.camel.tooling.model.EipModel;
+import org.apache.camel.dsl.jbang.core.commands.ai.ErrorDiagnoser;
+import org.apache.camel.dsl.jbang.core.commands.ai.ToolRegistry;
+import org.apache.camel.util.json.JsonObject;
/**
* MCP Tool for diagnosing Camel errors from stack traces or error messages.
@@ -41,35 +37,12 @@ import org.apache.camel.tooling.model.EipModel;
@ApplicationScoped
public class DiagnoseTools {
- private static final String CAMEL_COMPONENT_DOC = DiagnoseData.CAMEL_COMPONENT_DOC;
- private static final String CAMEL_EIP_DOC = DiagnoseData.CAMEL_EIP_DOC;
-
- /**
- * Pattern to extract component names from endpoint URIs in error messages (e.g., "kafka:myTopic", "http://host").
- */
- private static final Pattern ENDPOINT_URI_PATTERN = Pattern
- .compile("(?:endpoint|uri)[:\\s]+['\"]?([a-zA-Z][a-zA-Z0-9+.-]*):(?://)?[^\\s'\"]*", Pattern.CASE_INSENSITIVE);
-
- /**
- * Pattern to extract component scheme from common error contexts.
- */
- private static final Pattern COMPONENT_SCHEME_PATTERN
- = Pattern.compile("(?:component|scheme)[:\\s]+['\"]?([a-zA-Z][a-zA-Z0-9+.-]*)['\"]?", Pattern.CASE_INSENSITIVE);
-
- /**
- * Pattern to extract route IDs from error messages.
- */
- private static final Pattern ROUTE_ID_PATTERN
- = Pattern.compile("route[:\\s]+['\"]?([a-zA-Z0-9_-]+)['\"]?", Pattern.CASE_INSENSITIVE);
-
@Inject
CatalogService catalogService;
- @Inject
- DiagnoseData diagnoseData;
-
/**
- * Tool to diagnose Camel errors from stack traces or error messages.
+ * Tool to diagnose Camel errors from stack traces or error messages: a thin wrapper over the shared
+ * {@code camel_error_diagnose} tool of the {@link ToolRegistry} (CAMEL-24695), so the TUI answers the same.
*/
@Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
description = "Diagnose a Camel error from a stack trace or error message. "
@@ -77,7 +50,7 @@ public class DiagnoseTools {
+ "links to relevant Camel documentation, and suggested fixes. "
+ "Covers the most common Camel exceptions including NoSuchEndpointException, "
+ "ResolveEndpointFailedException, FailedToCreateRouteException, and more.")
- public DiagnoseResult camel_error_diagnose(
+ public JsonObject camel_error_diagnose(
@ToolArg(description = "The Camel stack trace or error message to diagnose") String error,
@ToolArg(description = ToolArgDocs.RUNTIME) String runtime,
@ToolArg(description = ToolArgDocs.CAMEL_VERSION) String camelVersion,
@@ -86,58 +59,9 @@ public class DiagnoseTools {
if (error == null || error.isBlank()) {
throw new ToolCallException("Error message or stack trace is required", null);
}
-
try {
CamelCatalog catalog = catalogService.loadCatalog(runtime, camelVersion, platformBom);
-
- // Identify matching exceptions
- List<String> matchedExceptions = identifyExceptions(error);
- List<IdentifiedException> exceptions = new ArrayList<>();
- for (String exceptionName : matchedExceptions) {
- DiagnoseData.ExceptionInfo info = diagnoseData.getException(exceptionName);
- if (info != null) {
- exceptions.add(new IdentifiedException(
- exceptionName, info.description(), info.commonCauses(),
- info.suggestedFixes(), info.documentationLinks()));
- }
- }
-
- // Identify components from the error
- List<String> componentNames = extractComponentNames(error, catalog);
- List<IdentifiedComponent> components = new ArrayList<>();
- for (String comp : componentNames) {
- ComponentModel model = catalog.componentModel(comp);
- if (model != null) {
- components.add(new IdentifiedComponent(
- comp, model.getTitle(), model.getDescription(),
- CAMEL_COMPONENT_DOC + comp + "-component.html"));
- }
- }
-
- // Identify EIPs from the error
- List<String> eipNames = extractEipNames(error, catalog);
- List<IdentifiedEip> eips = new ArrayList<>();
- for (String eip : eipNames) {
- EipModel model = catalog.eipModel(eip);
- if (model != null) {
- eips.add(new IdentifiedEip(
- eip, model.getTitle(), model.getDescription(),
- CAMEL_EIP_DOC + eip + "-eip.html"));
- }
- }
-
- // Extract route ID if present
- String routeId = null;
- Matcher routeMatcher = ROUTE_ID_PATTERN.matcher(error);
- if (routeMatcher.find()) {
- routeId = routeMatcher.group(1);
- }
-
- // Summary
- DiagnoseSummary summary = new DiagnoseSummary(
- exceptions.size(), components.size(), eips.size(), !exceptions.isEmpty());
-
- return new DiagnoseResult(exceptions, components, eips, routeId, summary);
+ return ErrorDiagnoser.diagnose(error, catalog);
} catch (ToolCallException e) {
throw e;
} catch (Throwable e) {
@@ -145,99 +69,4 @@ public class DiagnoseTools {
"Failed to diagnose error (" + e.getClass().getName() + "): " + e.getMessage(), null);
}
}
-
- /**
- * Identify known Camel exceptions in the error text.
- */
- private List<String> identifyExceptions(String error) {
- List<String> matched = new ArrayList<>();
- for (String exceptionName : diagnoseData.getKnownExceptions().keySet()) {
- if (error.contains(exceptionName)) {
- matched.add(exceptionName);
- }
- }
- return matched;
- }
-
- /**
- * Extract component names from endpoint URIs and other patterns in the error text.
- */
- private List<String> extractComponentNames(String error, CamelCatalog catalog) {
- List<String> found = new ArrayList<>();
-
- // Try endpoint URI pattern
- Matcher uriMatcher = ENDPOINT_URI_PATTERN.matcher(error);
- while (uriMatcher.find()) {
- String scheme = uriMatcher.group(1).toLowerCase();
- if (catalog.componentModel(scheme) != null && !found.contains(scheme)) {
- found.add(scheme);
- }
- }
-
- // Try component scheme pattern
- Matcher schemeMatcher = COMPONENT_SCHEME_PATTERN.matcher(error);
- while (schemeMatcher.find()) {
- String scheme = schemeMatcher.group(1).toLowerCase();
- if (catalog.componentModel(scheme) != null && !found.contains(scheme)) {
- found.add(scheme);
- }
- }
-
- // Scan for known component names in the error text
- String lowerError = error.toLowerCase();
- for (String comp : catalog.findComponentNames()) {
- if (!found.contains(comp) && containsComponent(lowerError, comp)) {
- found.add(comp);
- }
- }
-
- return found;
- }
-
- /**
- * Extract EIP names from the error text.
- */
- private List<String> extractEipNames(String error, CamelCatalog catalog) {
- List<String> found = new ArrayList<>();
- String lowerError = error.toLowerCase();
-
- for (String eip : catalog.findModelNames()) {
- EipModel model = catalog.eipModel(eip);
- if (model != null) {
- String eipLower = eip.toLowerCase();
- if (lowerError.contains(eipLower) && !found.contains(eip)) {
- found.add(eip);
- }
- }
- }
-
- return found;
- }
-
- private boolean containsComponent(String content, String comp) {
- return content.contains(comp + ":")
- || content.contains("\"" + comp + "\"")
- || content.contains("'" + comp + "'");
- }
-
- // Result records
-
- public record DiagnoseResult(
- List<IdentifiedException> identifiedExceptions, List<IdentifiedComponent> identifiedComponents,
- List<IdentifiedEip> identifiedEips, String routeId, DiagnoseSummary summary) {
- }
-
- public record IdentifiedException(
- String exception, String description, List<String> commonCauses,
- List<String> suggestedFixes, List<String> documentationLinks) {
- }
-
- public record IdentifiedComponent(String name, String title, String description, String documentationUrl) {
- }
-
- public record IdentifiedEip(String name, String title, String description, String documentationUrl) {
- }
-
- public record DiagnoseSummary(int exceptionCount, int componentCount, int eipCount, boolean diagnosed) {
- }
}
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
new file mode 100644
index 000000000000..abc8e38f708c
--- /dev/null
+++ b/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/AuthoringToolsTest.java
@@ -0,0 +1,111 @@
+/*
+ * 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.lang.reflect.Method;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+
+import io.quarkiverse.mcp.server.Tool;
+import io.quarkiverse.mcp.server.ToolCallException;
+import org.apache.camel.dsl.jbang.core.commands.ai.ToolDescriptor;
+import org.apache.camel.dsl.jbang.core.commands.ai.ToolRegistry;
+import org.apache.camel.util.json.JsonObject;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * The shared authoring tools as camel-jbang-mcp exposes them (CAMEL-24695): one thin wrapper per registry tool, with
+ * the same name and the annotations the access filter reads, so an agent gets the same Camel as through the TUI.
+ */
+class AuthoringToolsTest {
+
+ private final AuthoringTools tools = new AuthoringTools();
+
+ @Test
+ void everySharedToolHasAWrapperWithMatchingHints() {
+ List<String> wrapped = new ArrayList<>();
+ for (Method m : AuthoringTools.class.getMethods()) {
+ Tool tool = m.getAnnotation(Tool.class);
+ if (tool == null) {
+ continue;
+ }
+ ToolDescriptor td = ToolRegistry.findTool(m.getName());
+ assertThat(td).as(m.getName() + " is in the shared registry").isNotNull();
+ assertThat(tool.annotations().readOnlyHint()).as(m.getName() + " readOnlyHint").isEqualTo(td.isReadOnly());
+ assertThat(tool.annotations().destructiveHint()).as(m.getName() + " destructiveHint")
+ .isEqualTo(td.isDestructive());
+ wrapped.add(m.getName());
+ }
+ // camel_error_diagnose keeps its wrapper in DiagnoseTools (catalog per runtime), the rest live here
+ List<String> shared = new ArrayList<>(ToolRegistry.authoringTools().stream().map(ToolDescriptor::name).toList());
+ shared.remove("camel_error_diagnose");
+ assertThat(wrapped).containsExactlyInAnyOrderElementsOf(shared);
+ }
+
+ @Test
+ void catalogDocAnswersWithOptionsAndUriRules() {
+ JsonObject timer = tools.camel_catalog_doc("timer", null, "component", null, null, null, null, null);
+ assertThat(timer.getString("kind")).isEqualTo("component");
+ assertThat(timer.getString("uriSyntax")).contains("(timerName) go in the path");
+ assertThat(timer.getInteger("matchedOptions")).isGreaterThan(5);
+ JsonObject check = tools.camel_catalog_doc(null, "timer:tick?periodd=5s", null, null, null, null, null, null);
+ assertThat(check.getBoolean("valid")).isFalse();
+ assertThat(List.copyOf(check.getCollection("problems")).get(0).toString()).contains("periodd");
+ // a lookup that finds nothing answers with an error field and suggestions, as the TUI does, not an exception
+ assertThat(tools.camel_catalog_doc(null, null, null, null, null, null, null, null).getString("error"))
+ .contains("required");
+ JsonObject mqtt = tools.camel_catalog_doc("mqtt", null, "component", null, null, null, null, null);
+ assertThat(mqtt.getString("error")).contains("mqtt");
+ assertThat(List.copyOf(mqtt.getCollection("suggestions")).toString()).contains("paho-mqtt5");
+ }
+
+ @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(dir.toString(), "demo.camel.yaml", route, null, 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(dir.toString(), "demo.camel.yaml",
+ route.replace("message", "mesage"), null, null);
+ assertThat(invalid.getString("status")).isEqualTo("invalid");
+ assertThat(Files.readString(dir.resolve("demo.camel.yaml"), StandardCharsets.UTF_8)).isEqualTo(route);
+
+ JsonObject listed = tools.camel_get_files(dir.toString(), null);
+ assertThat(listed.getInteger("totalFiles")).isEqualTo(1);
+ assertThat(tools.camel_get_files(dir.toString(), "demo.camel.yaml").getString("content")).isEqualTo(route);
+ assertThat(tools.camel_validate_source(dir.toString(), "demo.camel.yaml", null, null).getBoolean("valid"))
+ .isTrue();
+ assertThatThrownBy(() -> tools.camel_get_files(null, null))
+ .isInstanceOf(ToolCallException.class).hasMessageContaining("directory is required");
+ }
+
+ @Test
+ void anUnknownIntegrationNameIsAnError() {
+ assertThatThrownBy(() -> tools.camel_eval_expression("${body}", null, "camel", "no-such-app-xyz-1"))
+ .isInstanceOf(ToolCallException.class).hasMessageContaining("no-such-app-xyz-1");
+ assertThatThrownBy(() -> tools.camel_get_log("no-such-app-xyz-1", null, null, null))
+ .isInstanceOf(ToolCallException.class).hasMessageContaining("no-such-app-xyz-1");
+ }
+}
diff --git a/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/DiagnoseToolsTest.java b/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/DiagnoseToolsTest.java
index 581d8ee5d6e8..0fad8f0e5801 100644
--- a/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/DiagnoseToolsTest.java
+++ b/dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/DiagnoseToolsTest.java
@@ -16,9 +16,11 @@
*/
package org.apache.camel.dsl.jbang.core.commands.mcp;
+import java.util.List;
import java.util.Optional;
import io.quarkiverse.mcp.server.ToolCallException;
+import org.apache.camel.util.json.JsonObject;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -33,7 +35,6 @@ class DiagnoseToolsTest {
CatalogService catalogService = new CatalogService();
catalogService.catalogRepos = Optional.empty();
tools.catalogService = catalogService;
- tools.diagnoseData = new DiagnoseData();
}
// ---- Input validation ----
@@ -58,10 +59,10 @@ class DiagnoseToolsTest {
void identifiesNoSuchEndpointException() {
String error = "org.apache.camel.NoSuchEndpointException: No endpoint could be found for: kafak:myTopic";
- DiagnoseTools.DiagnoseResult result = tools.camel_error_diagnose(error, null, null, null);
+ JsonObject result = tools.camel_error_diagnose(error, null, null, null);
- assertThat(result.identifiedExceptions()).isNotEmpty();
- assertThat(result.identifiedExceptions().get(0).exception()).isEqualTo("NoSuchEndpointException");
+ assertThat(exceptions(result)).isNotEmpty();
+ assertThat(firstException(result)).isEqualTo("NoSuchEndpointException");
}
@Test
@@ -70,10 +71,10 @@ class DiagnoseToolsTest {
+ "Failed to resolve endpoint: kafka:myTopic?unknownOption=value due to: "
+ "There are 1 parameters that couldn't be set on the endpoint.";
- DiagnoseTools.DiagnoseResult result = tools.camel_error_diagnose(error, null, null, null);
+ JsonObject result = tools.camel_error_diagnose(error, null, null, null);
- assertThat(result.identifiedExceptions()).isNotEmpty();
- assertThat(result.identifiedExceptions().get(0).exception()).isEqualTo("ResolveEndpointFailedException");
+ assertThat(exceptions(result)).isNotEmpty();
+ assertThat(firstException(result)).isEqualTo("ResolveEndpointFailedException");
}
@Test
@@ -81,10 +82,10 @@ class DiagnoseToolsTest {
String error = "org.apache.camel.FailedToCreateRouteException: "
+ "Failed to create route route1: Route(route1)[From[direct:start] -> [To[log:out]]]";
- DiagnoseTools.DiagnoseResult result = tools.camel_error_diagnose(error, null, null, null);
+ JsonObject result = tools.camel_error_diagnose(error, null, null, null);
- assertThat(result.identifiedExceptions()).isNotEmpty();
- assertThat(result.identifiedExceptions().get(0).exception()).isEqualTo("FailedToCreateRouteException");
+ assertThat(exceptions(result)).isNotEmpty();
+ assertThat(firstException(result)).isEqualTo("FailedToCreateRouteException");
}
@Test
@@ -92,9 +93,9 @@ class DiagnoseToolsTest {
String error = "org.apache.camel.FailedToCreateRouteException: Failed to create route\n"
+ "Caused by: org.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint";
- DiagnoseTools.DiagnoseResult result = tools.camel_error_diagnose(error, null, null, null);
+ JsonObject result = tools.camel_error_diagnose(error, null, null, null);
- assertThat(result.identifiedExceptions().size()).isGreaterThanOrEqualTo(2);
+ assertThat(exceptions(result).size()).isGreaterThanOrEqualTo(2);
}
@Test
@@ -103,10 +104,10 @@ class DiagnoseToolsTest {
+ "No type converter available to convert from type: java.lang.String "
+ "to the required type: java.io.InputStream";
- DiagnoseTools.DiagnoseResult result = tools.camel_error_diagnose(error, null, null, null);
+ JsonObject result = tools.camel_error_diagnose(error, null, null, null);
- assertThat(result.identifiedExceptions()).isNotEmpty();
- assertThat(result.identifiedExceptions().get(0).exception()).isEqualTo("NoTypeConversionAvailableException");
+ assertThat(exceptions(result)).isNotEmpty();
+ assertThat(firstException(result)).isEqualTo("NoTypeConversionAvailableException");
}
@Test
@@ -114,10 +115,10 @@ class DiagnoseToolsTest {
String error = "org.apache.camel.ExchangeTimedOutException: "
+ "The OUT message was not received within: 30000 millis";
- DiagnoseTools.DiagnoseResult result = tools.camel_error_diagnose(error, null, null, null);
+ JsonObject result = tools.camel_error_diagnose(error, null, null, null);
- assertThat(result.identifiedExceptions()).isNotEmpty();
- assertThat(result.identifiedExceptions().get(0).exception()).isEqualTo("ExchangeTimedOutException");
+ assertThat(exceptions(result)).isNotEmpty();
+ assertThat(firstException(result)).isEqualTo("ExchangeTimedOutException");
}
@Test
@@ -125,10 +126,10 @@ class DiagnoseToolsTest {
String error = "org.apache.camel.component.direct.DirectConsumerNotAvailableException: "
+ "No consumers available on endpoint: direct://myEndpoint";
- DiagnoseTools.DiagnoseResult result = tools.camel_error_diagnose(error, null, null, null);
+ JsonObject result = tools.camel_error_diagnose(error, null, null, null);
- assertThat(result.identifiedExceptions()).isNotEmpty();
- assertThat(result.identifiedExceptions().get(0).exception()).isEqualTo("DirectConsumerNotAvailableException");
+ assertThat(exceptions(result)).isNotEmpty();
+ assertThat(firstException(result)).isEqualTo("DirectConsumerNotAvailableException");
}
@Test
@@ -136,10 +137,10 @@ class DiagnoseToolsTest {
String error = "org.apache.camel.PropertyBindingException: "
+ "Error binding property (brokerz=localhost:9092) with name: brokerz on bean";
- DiagnoseTools.DiagnoseResult result = tools.camel_error_diagnose(error, null, null, null);
+ JsonObject result = tools.camel_error_diagnose(error, null, null, null);
- assertThat(result.identifiedExceptions()).isNotEmpty();
- assertThat(result.identifiedExceptions().get(0).exception()).isEqualTo("PropertyBindingException");
+ assertThat(exceptions(result)).isNotEmpty();
+ assertThat(firstException(result)).isEqualTo("PropertyBindingException");
}
@Test
@@ -147,10 +148,10 @@ class DiagnoseToolsTest {
String error = "org.apache.camel.NoSuchBeanException: "
+ "No bean could be found in the registry for: myProcessor";
- DiagnoseTools.DiagnoseResult result = tools.camel_error_diagnose(error, null, null, null);
+ JsonObject result = tools.camel_error_diagnose(error, null, null, null);
- assertThat(result.identifiedExceptions()).isNotEmpty();
- assertThat(result.identifiedExceptions().get(0).exception()).isEqualTo("NoSuchBeanException");
+ assertThat(exceptions(result)).isNotEmpty();
+ assertThat(firstException(result)).isEqualTo("NoSuchBeanException");
}
// ---- Component identification ----
@@ -160,25 +161,19 @@ class DiagnoseToolsTest {
String error = "org.apache.camel.ResolveEndpointFailedException: "
+ "Failed to resolve endpoint: kafka:myTopic?brokers=localhost:9092";
- DiagnoseTools.DiagnoseResult result = tools.camel_error_diagnose(error, null, null, null);
+ JsonObject result = tools.camel_error_diagnose(error, null, null, null);
- assertThat(result.identifiedComponents()).isNotEmpty();
- assertThat(result.identifiedComponents().stream()
- .map(DiagnoseTools.IdentifiedComponent::name)
- .toList())
- .contains("kafka");
+ assertThat(components(result)).isNotEmpty();
+ assertThat(components(result).stream().map(c -> c.getString("name")).toList()).contains("kafka");
}
@Test
void identifiesDirectComponent() {
String error = "No consumers available on endpoint: direct://start";
- DiagnoseTools.DiagnoseResult result = tools.camel_error_diagnose(error, null, null, null);
+ JsonObject result = tools.camel_error_diagnose(error, null, null, null);
- assertThat(result.identifiedComponents().stream()
- .map(DiagnoseTools.IdentifiedComponent::name)
- .toList())
- .contains("direct");
+ assertThat(components(result).stream().map(c -> c.getString("name")).toList()).contains("direct");
}
// ---- Result structure ----
@@ -187,50 +182,51 @@ class DiagnoseToolsTest {
void resultContainsCommonCauses() {
String error = "org.apache.camel.NoSuchEndpointException: No endpoint could be found for: xyz:test";
- DiagnoseTools.DiagnoseResult result = tools.camel_error_diagnose(error, null, null, null);
+ JsonObject result = tools.camel_error_diagnose(error, null, null, null);
- assertThat(result.identifiedExceptions().get(0).commonCauses()).isNotEmpty();
+ assertThat(List.copyOf(exceptions(result).get(0).getCollection("commonCauses"))).isNotEmpty();
}
@Test
void resultContainsSuggestedFixes() {
String error = "org.apache.camel.NoSuchEndpointException: No endpoint could be found for: xyz:test";
- DiagnoseTools.DiagnoseResult result = tools.camel_error_diagnose(error, null, null, null);
+ JsonObject result = tools.camel_error_diagnose(error, null, null, null);
- assertThat(result.identifiedExceptions().get(0).suggestedFixes()).isNotEmpty();
+ assertThat(List.copyOf(exceptions(result).get(0).getCollection("suggestedFixes"))).isNotEmpty();
}
@Test
void resultContainsDocumentationLinks() {
String error = "org.apache.camel.NoSuchEndpointException: No endpoint could be found for: xyz:test";
- DiagnoseTools.DiagnoseResult result = tools.camel_error_diagnose(error, null, null, null);
+ JsonObject result = tools.camel_error_diagnose(error, null, null, null);
- assertThat(result.identifiedExceptions().get(0).documentationLinks()).isNotEmpty();
- assertThat(result.identifiedExceptions().get(0).documentationLinks().get(0))
- .startsWith("https://camel.apache.org/");
+ List<String> links = List.copyOf(exceptions(result).get(0).getCollection("documentationLinks"));
+ assertThat(links).isNotEmpty();
+ assertThat(links.get(0)).startsWith("https://camel.apache.org/");
}
@Test
void resultContainsSummary() {
String error = "org.apache.camel.NoSuchEndpointException: No endpoint";
- DiagnoseTools.DiagnoseResult result = tools.camel_error_diagnose(error, null, null, null);
+ JsonObject result = tools.camel_error_diagnose(error, null, null, null);
- assertThat(result.summary()).isNotNull();
- assertThat(result.summary().diagnosed()).isTrue();
- assertThat(result.summary().exceptionCount()).isGreaterThan(0);
+ JsonObject summary = result.getMap("summary");
+ assertThat(summary).isNotNull();
+ assertThat(summary.getBoolean("diagnosed")).isTrue();
+ assertThat(summary.getInteger("exceptionCount")).isGreaterThan(0);
}
@Test
void componentDocumentationUrlPresent() {
String error = "Failed to resolve endpoint: kafka:myTopic";
- DiagnoseTools.DiagnoseResult result = tools.camel_error_diagnose(error, null, null, null);
+ JsonObject result = tools.camel_error_diagnose(error, null, null, null);
- if (!result.identifiedComponents().isEmpty()) {
- assertThat(result.identifiedComponents().get(0).documentationUrl()).contains("camel.apache.org");
+ if (!components(result).isEmpty()) {
+ assertThat(components(result).get(0).getString("documentationUrl")).contains("camel.apache.org");
}
}
@@ -240,10 +236,11 @@ class DiagnoseToolsTest {
void unrecognizedErrorReturnsDiagnosedFalse() {
String error = "Some random error that is not a Camel exception";
- DiagnoseTools.DiagnoseResult result = tools.camel_error_diagnose(error, null, null, null);
+ JsonObject result = tools.camel_error_diagnose(error, null, null, null);
- assertThat(result.summary().diagnosed()).isFalse();
- assertThat(result.summary().exceptionCount()).isEqualTo(0);
+ JsonObject summary = result.getMap("summary");
+ assertThat(summary.getBoolean("diagnosed")).isFalse();
+ assertThat(summary.getInteger("exceptionCount")).isEqualTo(0);
}
// ---- Full stack trace ----
@@ -262,14 +259,23 @@ class DiagnoseToolsTest {
\tat org.apache.camel.component.direct.DirectComponent.createEndpoint(DirectComponent.java:62)
""";
- DiagnoseTools.DiagnoseResult result = tools.camel_error_diagnose(stackTrace, null, null, null);
+ JsonObject result = tools.camel_error_diagnose(stackTrace, null, null, null);
// Should identify all three exceptions in the chain
- assertThat(result.identifiedExceptions().size()).isGreaterThanOrEqualTo(3);
+ assertThat(exceptions(result).size()).isGreaterThanOrEqualTo(3);
- assertThat(result.identifiedComponents().stream()
- .map(DiagnoseTools.IdentifiedComponent::name)
- .toList())
- .contains("kafka");
+ assertThat(components(result).stream().map(c -> c.getString("name")).toList()).contains("kafka");
+ }
+
+ private static List<JsonObject> exceptions(JsonObject result) {
+ return List.copyOf(result.getCollection("identifiedExceptions"));
+ }
+
+ private static List<JsonObject> components(JsonObject result) {
+ return List.copyOf(result.getCollection("identifiedComponents"));
+ }
+
+ private static String firstException(JsonObject result) {
+ return exceptions(result).get(0).getString("exception");
}
}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
index 72b767051948..1a45751f4eaa 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanel.java
@@ -1167,7 +1167,7 @@ class AiPanel {
if (handler != null) {
editQuestionHandler = null;
if (handler.test(input)) {
- // the waiting tui_write_file call returns with the question and the model answers in this turn
+ // the waiting camel_write_file call returns with the question and the model answers in this turn
conversation.add(new ConversationEntry(AiRole.USER, input));
questionCounter++;
log(LogLevel.QUESTION, "Question about the edit", input);
@@ -1903,10 +1903,10 @@ class AiPanel {
String kind = String.valueOf(toolCall.getStringOrDefault("kind", ""));
String tool = tuiToolName(name, title, kind);
boolean readOnly = tool != null && TuiToolRegistry.READ_ONLY_TOOLS.contains(tool);
- // the facade asks the user before a tui_write_file call touches a file (the confirm dialog or the live
+ // the facade asks the user before a camel_write_file call touches a file (the confirm dialog or the live
// replay), so a second question at the ACP layer would only make the user answer twice; in auto mode
// nothing else asks and the popup stays
- boolean confirmedByTui = "tui_write_file".equals(tool) && writeMode != McpFacade.WriteMode.AUTO;
+ boolean confirmedByTui = TuiToolRegistry.WRITE_TOOL.equals(tool) && writeMode != McpFacade.WriteMode.AUTO;
if (readOnly || confirmedByTui) {
String optionId = firstOptionOfKind(options, "allow_always");
if (optionId == null) {
@@ -1917,7 +1917,7 @@ class AiPanel {
}
log(LogLevel.TOOL, readOnly
? "Auto-approved read-only TUI tool"
- : "Auto-approved tui_write_file (the TUI confirms the write itself)", title);
+ : "Auto-approved camel_write_file (the TUI confirms the write itself)", title);
return optionId;
}
CompletableFuture<String> decision = new CompletableFuture<>();
@@ -1961,12 +1961,12 @@ class AiPanel {
/**
* The line the permission popup shows under the tool: an agent that edits a source file with its own tools bypasses
- * the TUI's diff and live replay, and the user may prefer to reject it and have the agent use tui_write_file, as
+ * the TUI's diff and live replay, and the user may prefer to reject it and have the agent use camel_write_file, as
* the preamble told it to.
*/
private static String permissionHint(String kind) {
if ("edit".equals(kind) || "delete".equals(kind) || "move".equals(kind)) {
- return "The TUI cannot show or replay this change; Esc rejects it so the agent uses tui_write_file";
+ return "The TUI cannot show or replay this change; Esc rejects it so the agent uses camel_write_file";
}
return null;
}
@@ -2859,7 +2859,7 @@ class AiPanel {
private String acpPreamble() {
String prompt = buildSystemPrompt();
return (prompt.endsWith("\n") ? prompt : prompt + "\n")
- + "- You run inside the Camel TUI: edit the integration's source files only with tui_write_file, "
+ + "- You run inside the Camel TUI: edit the integration's source files only with camel_write_file, "
+ "never with your own file tools, so the user sees the diff and confirms it, or watches the edit "
+ "being typed in the Source editor (/write live)\n";
}
@@ -2874,7 +2874,8 @@ class AiPanel {
sb.append("You are an Apache Camel assistant running inside the Camel TUI terminal console. ");
sb.append("You help users understand and troubleshoot their running Camel integrations.\n\n");
- sb.append("You have tui_* tools to observe and interact with the TUI; the tool definitions describe each one. ");
+ sb.append("You have camel_* tools for the integration and tui_* tools for the TUI; the tool definitions ");
+ sb.append("describe each one. ");
sb.append("All tui_get_* tools fetch data directly from any tab without changing what the user sees.\n\n");
sb.append("Guidelines:\n");
sb.append("- NEVER call tui_navigate just to read data; the tui_get_* tools read any tab without navigating\n");
@@ -2884,7 +2885,7 @@ class AiPanel {
sb.append("a route's steps; tui_get_status has data no tab shows (context, runtime, health, properties)\n");
sb.append("- Your own tool calls are in the AI log (tui_get_ai_log); the MCP log only has external clients\n");
sb.append("- Be concise and actionable; when something looks wrong, explain it and suggest fixes\n");
- sb.append("- tui_control stops/starts routes and integrations gracefully; its reset-stats action clears ");
+ sb.append("- camel_control stops/starts routes and integrations gracefully; its reset-stats action clears ");
sb.append("statistics without touching the routes\n");
sb.append("- tui_infra lists infra services (brokers, databases) and their logs\n");
sb.append("- Never restart, stop or kill an integration or infra service unless the user explicitly ");
@@ -2893,13 +2894,14 @@ class AiPanel {
sb.append("say what failed and what to try\n");
sb.append("- To feed a route that consumes from a broker (MQTT, Kafka, JMS), tui_send_message can publish ");
sb.append("to the broker with the route's own component and options\n");
- sb.append("- To edit: tui_get_files, then tui_write_file with the complete file; the user confirms, never retry ");
- sb.append("a rejected write. Invalid YAML/properties is refused with errors: fix them (tui_catalog_doc has the ");
+ sb.append("- To edit: camel_get_files, then camel_write_file with the complete file; the user confirms, never ");
+ sb.append(
+ "retry a rejected write. Invalid YAML/properties is refused with errors: fix them (camel_catalog_doc has the ");
sb.append("option names)\n");
sb.append("- tui_set_log_level is the app's root logger, only when asked; 'log at WARN' in a route is the log ");
sb.append("step's loggingLevel in the source\n");
sb.append("- Simple: functions inside ${...}, operators between them: ${header.a} == 'b', ");
- sb.append("${body} ?: 'none'; tui_eval_expression checks one, tui_catalog_doc simple lists them\n");
+ sb.append("${body} ?: 'none'; camel_eval_expression checks one, camel_catalog_doc simple lists them\n");
if (!useCoreTools()) {
sb.append("- Use tui_locate + tui_draw_shape to visually highlight problems on screen for the user\n");
}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CamelMonitor.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CamelMonitor.java
index ee63146660dc..90225935f5f6 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CamelMonitor.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/CamelMonitor.java
@@ -811,6 +811,7 @@ public class CamelMonitor extends CamelCommand {
}
});
mcpFacade.setSourceValidator(tabRegistry.sourceTab().editAssist()::validateSource);
+ mcpFacade.setPropertyLineValidator(tabRegistry.sourceTab().editAssist()::validateSpringBootPropertyLine);
mcpFacade.setLaunchManager(actionsPopup.getLaunchManager());
aiPanel.setMcpFacade(mcpFacade);
aiPanel.setOtelSpans(dataService.otelSpans());
@@ -951,7 +952,7 @@ public class CamelMonitor extends CamelCommand {
if (outcome.saved()) {
note = "The user saved " + file + " after the paused edit (" + outcome.applied() + " edit(s) applied"
+ (outcome.skipped().isEmpty() ? "" : ", skipped " + outcome.skipped())
- + "); read it with tui_get_files if you need the current content. Continue with any file"
+ + "); read it with camel_get_files if you need the current content. Continue with any file"
+ " write that was deferred meanwhile.";
} else {
note = "The user discarded the paused edit of " + file + "; the file is unchanged. Ask before"
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DocViewerPopup.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DocViewerPopup.java
index 75bfce6ced89..797c861a9c1e 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DocViewerPopup.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/DocViewerPopup.java
@@ -512,7 +512,9 @@ class DocViewerPopup {
+ "| `tui_navigate` | Switch tabs and select integrations |\n"
+ "| `tui_send_keys` | Send key presses to control the TUI |\n"
+ "| `tui_wait_for_idle` | Waits for the screen to settle after an action |\n"
- + "| `tui_control` | Stop/start routes, restart, stop, or kill integration |\n"
+ + "| `camel_control` | Stop/start routes, restart, stop, or kill integration |\n"
+ + "| `camel_get_files` / `camel_write_file` | Read and edit the source files |\n"
+ + "| `camel_catalog_doc` / `camel_validate_source` | Catalog docs and validation |\n"
+ "| `tui_tape_start` | Start recording interactions as a VHS .tape file |\n"
+ "| `tui_tape_stop` | Stop recording and return the tape content |\n\n"
+ "## Setup for Claude Code\n\n"
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/McpFacade.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/McpFacade.java
index 43756094b146..d0120e7379d3 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/McpFacade.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/McpFacade.java
@@ -26,8 +26,8 @@ import java.util.Locale;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
+import java.util.function.Function;
import java.util.function.Supplier;
-import java.util.regex.Pattern;
import dev.tamboui.buffer.Buffer;
import dev.tamboui.export.ExportRequest;
@@ -37,11 +37,11 @@ import dev.tamboui.tui.event.KeyCode;
import dev.tamboui.tui.event.KeyEvent;
import dev.tamboui.tui.event.KeyModifiers;
import dev.tamboui.widgets.tabs.TabsState;
+import org.apache.camel.dsl.jbang.core.commands.ai.SourceValidator;
import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
import org.apache.camel.dsl.jbang.core.common.RuntimeHelper;
import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
-import org.apache.camel.util.json.Jsoner;
import static org.apache.camel.dsl.jbang.core.commands.tui.TuiHelper.hint;
import static org.apache.camel.dsl.jbang.core.commands.tui.TuiHelper.hintLast;
@@ -304,6 +304,16 @@ class McpFacade {
return info != null ? info.camelVersion : null;
}
+ /** The source directory of the selected integration, the default directory of the shared file tools. */
+ Path getSelectedSourceDirectory() {
+ IntegrationInfo info = findIntegration(null);
+ if (info == null) {
+ return null;
+ }
+ Path dir = FilesBrowser.resolveSourceDirectory(info);
+ return dir != null && Files.isDirectory(dir) ? dir : null;
+ }
+
int getIntegrationCount() {
List<IntegrationInfo> list = data.get();
return (int) list.stream().filter(i -> !i.vanishing).count();
@@ -908,7 +918,7 @@ class McpFacade {
* integration was started (plain files, --source-dir, an example extracted to a temporary folder, an exported
* project), and edits only take effect on reload (dev mode) or restart.
*/
- // time the last tui_write_file spent waiting for the user's confirmation; the AI panel subtracts it from the
+ // time the last camel_write_file spent waiting for the user's confirmation; the AI panel subtracts it from the
// tool time of the call so the usage statistics show what the tool did, not how long the user thought about it
private volatile long lastConfirmWaitMs;
@@ -927,11 +937,21 @@ class McpFacade {
// validates source by file type (Camel YAML DSL, application.properties) with the editor's own checks,
// see SourceEditAssist#validateSource
private BiFunction<String, String, List<String>> sourceValidator;
+ // the editor's check of a properties line the catalog does not know (Spring Boot), for the shared tools
+ private Function<String, String> propertyLineValidator;
void setSourceValidator(BiFunction<String, String, List<String>> sourceValidator) {
this.sourceValidator = sourceValidator;
}
+ void setPropertyLineValidator(Function<String, String> propertyLineValidator) {
+ this.propertyLineValidator = propertyLineValidator;
+ }
+
+ Function<String, String> getPropertyLineValidator() {
+ return propertyLineValidator;
+ }
+
/**
* Validates source before it is written: {@code content} when given (the file name decides the checks), otherwise
* the file from the integration's source directory. A YAML file is validated as Camel YAML DSL and a .properties
@@ -954,7 +974,7 @@ class McpFacade {
if (sourceValidator == null) {
return writeError("Validation is not available");
}
- if (!SourceEditAssist.isValidatableFile(file)) {
+ if (!SourceValidator.isValidatableFile(file)) {
return writeError("No validation for " + file + ": only YAML routes and .properties files are validated");
}
List<String> errors = sourceValidator.apply(file, content);
@@ -983,13 +1003,13 @@ class McpFacade {
result.put("temporary", temporary);
String editing;
if (temporary) {
- editing = "The directory is a temporary copy of the sources; edits made with tui_write_file are lost when"
+ editing = "The directory is a temporary copy of the sources; edits made with camel_write_file are lost when"
+ " the integration stops"
+ (info.devMode ? ", but are reloaded while it runs (dev mode)." : ".");
} else if (info.devMode) {
- editing = "Files can be edited with tui_write_file; changes are reloaded automatically (dev mode).";
+ editing = "Files can be edited with camel_write_file; changes are reloaded automatically (dev mode).";
} else {
- editing = "Files can be edited with tui_write_file; restart the integration for changes to take effect.";
+ editing = "Files can be edited with camel_write_file; restart the integration for changes to take effect.";
}
result.put("editing", editing);
}
@@ -1087,7 +1107,7 @@ class McpFacade {
if (exists && !Files.isRegularFile(filePath)) {
return writeError(file + " is not a regular file");
}
- if (validate && sourceValidator != null && SourceEditAssist.isValidatableFile(file)) {
+ if (validate && sourceValidator != null && SourceValidator.isValidatableFile(file)) {
List<String> errors = sourceValidator.apply(file, content);
if (!errors.isEmpty()) {
JsonObject result = new JsonObject();
@@ -1097,7 +1117,7 @@ class McpFacade {
arr.addAll(errors);
result.put("errors", arr);
result.put("message", "The file was not written: the content has validation errors. Fix them and"
- + " call tui_write_file again (validate=false writes it anyway).");
+ + " call camel_write_file again (validate=false writes it anyway).");
return result;
}
}
@@ -1181,10 +1201,10 @@ class McpFacade {
+ " of " + (outcome.applied() + outcome.remaining())
+ " edit(s) and asks: " + outcome.question()
+ "\nAnswer the question briefly (what the edit does and why); look options up with"
- + " tui_catalog_doc rather than listing them from memory. Nothing is written"
+ + " camel_catalog_doc rather than listing them from memory. Nothing is written"
+ " yet: 'content' is the editor buffer with the applied edits, the file on disk"
+ " is unchanged. If the user wants the change done differently, call"
- + " tui_write_file again with the complete new content: it continues in the"
+ + " camel_write_file again with the complete new content: it continues in the"
+ " editor from 'content'. Otherwise only answer and end your turn: do not write"
+ " other files until the user has finished this edit (Enter continues the"
+ " pending edit(s), then the user saves or discards).");
@@ -1239,78 +1259,6 @@ class McpFacade {
return RuntimeHelper.sendMessage(pid, endpoint, body, headers);
}
- /**
- * Evaluates an expression (simple by default) inside the selected integration, the way {@code camel cmd eval} does,
- * with an optional message body; returns null when no integration is selected. The result is the value or the
- * parser/evaluation error, so it doubles as a validator the model can try expressions against.
- */
- JsonObject evalExpression(String language, String expression, String body) {
- if (ctx.selectedPid == null) {
- return null;
- }
- long pid;
- try {
- pid = Long.parseLong(ctx.selectedPid);
- } catch (NumberFormatException e) {
- return null;
- }
- String lang = language == null || language.isBlank() ? "simple" : language;
- boolean predicate = "simple".equals(lang) && looksLikePredicate(expression);
- String raw = RuntimeHelper.executeAction(pid, "eval", root -> {
- root.put("language", lang);
- root.put("predicate", String.valueOf(predicate));
- root.put("template", Jsoner.escape(expression));
- if (body != null) {
- root.put("body", Jsoner.escape(body));
- }
- });
- JsonObject result = new JsonObject();
- result.put("language", lang);
- result.put("expression", expression);
- if (predicate) {
- result.put("predicate", true);
- }
- if (body == null && expression.contains("${body")) {
- result.put("note", "evaluated with an empty body; pass body to evaluate against a value");
- }
- JsonObject out = null;
- try {
- out = (JsonObject) Jsoner.deserialize(raw);
- } catch (Exception e) {
- // not JSON: a timeout message
- }
- if (out == null) {
- result.put("status", "error");
- result.put("error", raw);
- return result;
- }
- if ("success".equals(out.getString("status"))) {
- result.put("status", "ok");
- result.put("result", out.get("result"));
- return result;
- }
- result.put("status", "error");
- JsonObject cause = out.getMap("exception");
- String message = cause != null ? cause.getString("message") : null;
- result.put("error", message != null ? Jsoner.unescape(message) : "evaluation failed");
- return result;
- }
-
- private static final Pattern PREDICATE_OPERATOR = Pattern.compile(
- "\\s(==|=~|!=|!=~|>|>=|<|<=|~~|!~~|contains|!contains|regex|!regex|in|!in|is|!is|range|!range"
- + "|startsWith|!startsWith|endsWith|!endsWith|equals|!equals|&&|\\|\\|)\\s");
-
- /**
- * Whether a simple expression is a predicate (an operator between placeholders, giving true or false) rather than a
- * value; the ternary and elvis forms contain operators but produce values.
- */
- static boolean looksLikePredicate(String expression) {
- if (expression == null || expression.contains(" ? ") || expression.contains(" ?: ")) {
- return false;
- }
- return PREDICATE_OPERATOR.matcher(expression).find();
- }
-
JsonObject executeSql(String sql, String datasource, int maxRows, int queryTimeout) {
if (ctx.selectedPid == null) {
return null;
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SourceEditAssist.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SourceEditAssist.java
index a767e0f0bfe0..548950dcc4c2 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SourceEditAssist.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SourceEditAssist.java
@@ -34,9 +34,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.camel.catalog.CamelCatalog;
-import org.apache.camel.catalog.ConfigurationPropertiesValidationResult;
-import org.apache.camel.catalog.EndpointValidationResult;
-import org.apache.camel.catalog.LanguageValidationResult;
+import org.apache.camel.dsl.jbang.core.commands.ai.SourceValidator;
import org.apache.camel.tooling.model.BaseOptionModel;
import org.apache.camel.tooling.model.ComponentModel;
import org.apache.camel.tooling.model.DataFormatModel;
@@ -67,12 +65,6 @@ final class SourceEditAssist {
private long placeholderCacheTime;
private Path placeholderCacheDir;
- private static final Set<String> PREDICATE_EIPS = Set.of(
- "filter", "when", "validate", "onWhen", "on-when",
- "handled", "continued", "retryWhile", "retry-while",
- "completionPredicate", "completion-predicate",
- "completion", "loopDoWhile", "loop-do-while");
-
// Properties quick-doc caches (invalidated when catalog version changes)
private String propsCatalogVersion;
private Map<String, BaseOptionModel> mainOptionsCache;
@@ -1439,25 +1431,7 @@ final class SourceEditAssist {
}
String validatePropertyLine(String line) {
- CamelCatalog catalog = getCatalog();
- if (catalog != null) {
- try {
- ConfigurationPropertiesValidationResult result = catalog.validateConfigurationProperty(line);
- if (result.isAccepted()) {
- if (!result.isSuccess()) {
- String msg = result.summaryErrorMessage(false);
- if (msg != null) {
- return msg.trim();
- }
- }
- return null;
- }
- } catch (Exception e) {
- // ignore validation errors
- }
- }
- // validate Spring Boot properties
- return validateSpringBootPropertyLine(line);
+ return SourceValidator.validatePropertyLine(line, getCatalog(), this::validateSpringBootPropertyLine);
}
String validateSpringBootPropertyLine(String line) {
@@ -1498,35 +1472,18 @@ final class SourceEditAssist {
return null;
}
- private org.apache.camel.dsl.yaml.validator.YamlValidator yamlValidator;
-
/**
* Validates Camel YAML DSL source the way the editor does on save: the YAML DSL schema (unknown or misspelled
* options, wrong structure), then endpoint URIs and simple expressions against the catalog. Returns the messages,
* empty when the source is valid.
*/
List<String> validateCamelYaml(String content) {
- List<String> msgs = new ArrayList<>();
- if (content == null || content.isBlank()) {
- return msgs;
- }
- try {
- if (yamlValidator == null) {
- yamlValidator = new org.apache.camel.dsl.yaml.validator.YamlValidator();
- }
- msgs.addAll(SourceValidationSupport.formatSchemaErrors(yamlValidator.validate(content)));
- } catch (Exception e) {
- msgs.add("Invalid YAML: " + e.getMessage());
- return msgs;
- }
- msgs.addAll(validateYamlEndpoints(content));
- msgs.addAll(validateYamlSimple(content));
- return msgs;
+ return SourceValidator.validateCamelYaml(content, getCatalog());
}
/** Validates a properties file (application.properties) line by line against the catalog, as the editor does. */
List<String> validateProperties(String content) {
- return SourceValidationSupport.validatePropertiesLines(content, this::validatePropertyLine);
+ return SourceValidator.validateProperties(content, getCatalog(), this::validateSpringBootPropertyLine);
}
/**
@@ -1534,19 +1491,11 @@ final class SourceEditAssist {
* Camel and Spring Boot options for .properties files. Other file types have no validation and yield no messages.
*/
List<String> validateSource(String fileName, String content) {
- String name = fileName == null ? "" : fileName.toLowerCase(java.util.Locale.ROOT);
- if (name.endsWith(".yaml") || name.endsWith(".yml")) {
- return validateCamelYaml(content);
- }
- if (name.endsWith(".properties")) {
- return validateProperties(content);
- }
- return List.of();
+ return SourceValidator.validate(fileName, content, getCatalog(), this::validateSpringBootPropertyLine);
}
static boolean isValidatableFile(String fileName) {
- String name = fileName == null ? "" : fileName.toLowerCase(java.util.Locale.ROOT);
- return name.endsWith(".yaml") || name.endsWith(".yml") || name.endsWith(".properties");
+ return SourceValidator.isValidatableFile(fileName);
}
List<String> validateYamlEndpoints(String content) {
@@ -1554,7 +1503,7 @@ final class SourceEditAssist {
if (catalog == null) {
return List.of();
}
- return doValidateYamlEndpoints(content, catalog);
+ return SourceValidator.validateYamlEndpoints(content, catalog);
}
List<String> validateYamlSimple(String content) {
@@ -1562,282 +1511,7 @@ final class SourceEditAssist {
if (catalog == null) {
return List.of();
}
- return doValidateYamlSimple(content, catalog);
- }
-
- static List<String> doValidateYamlSimple(String content, CamelCatalog catalog) {
- List<String> errors = new ArrayList<>();
- String[] lines = content.split("\n", -1);
-
- for (int i = 0; i < lines.length; i++) {
- String line = lines[i];
- if (line.isBlank()) {
- continue;
- }
- String trimmed = line.trim();
- if (trimmed.startsWith("#")) {
- continue;
- }
-
- String simpleText = null;
- int lineNum = i + 1;
- int lineIndent = countLeadingSpaces(line);
- boolean isLogMessage = false;
-
- // Strip YAML list prefix for matching
- String key = trimmed.startsWith("- ") ? trimmed.substring(2) : trimmed;
-
- // Match "simple: <value>" (inline shorthand)
- if (key.startsWith("simple:") && !key.equals("simple:")) {
- simpleText = SourceTab.extractYamlValue(key, "simple");
- }
- // Match "simple:" followed by "expression: <value>" on next line
- else if (key.equals("simple:")) {
- for (int j = i + 1; j < lines.length; j++) {
- String next = lines[j].trim();
- if (next.isBlank()) {
- continue;
- }
- if (next.startsWith("expression:")) {
- simpleText = SourceTab.extractYamlValue(next, "expression");
- lineNum = j + 1;
- }
- break;
- }
- }
- // Match "message: <value>" under log: EIP
- else if (key.startsWith("message:") && !key.equals("message:")) {
- String parentEip = findParentEip(lines, i, lineIndent);
- if ("log".equals(parentEip)) {
- simpleText = SourceTab.extractYamlValue(key, "message");
- isLogMessage = true;
- }
- }
-
- if (simpleText == null || simpleText.isEmpty()) {
- continue;
- }
- // Skip placeholder-only expressions
- if (simpleText.startsWith("{{") && simpleText.endsWith("}}")) {
- continue;
- }
-
- // Determine predicate vs expression context
- boolean predicate = false;
- if (!isLogMessage) {
- String parentEip = findParentEip(lines, i, lineIndent);
- predicate = parentEip != null && PREDICATE_EIPS.contains(parentEip);
- }
-
- try {
- LanguageValidationResult result = predicate
- ? catalog.validateLanguagePredicate(null, "simple", simpleText)
- : catalog.validateLanguageExpression(null, "simple", simpleText);
- if (!result.isSuccess()) {
- String error = result.getShortError() != null ? result.getShortError() : result.getError();
- if (error != null) {
- errors.add("Line " + lineNum + ": Simple syntax error: " + error);
- }
- }
- } catch (Exception e) {
- // best effort
- }
- }
- return errors;
- }
-
- static String findParentEip(String[] lines, int lineIdx, int lineIndent) {
- for (int j = lineIdx - 1; j >= 0; j--) {
- String prev = lines[j];
- if (prev.isBlank()) {
- continue;
- }
- int prevIndent = countLeadingSpaces(prev);
- if (prevIndent < lineIndent) {
- return extractEipFromLine(prev.trim());
- }
- }
- return null;
- }
-
- static List<String> doValidateYamlEndpoints(String content, CamelCatalog catalog) {
- List<String> errors = new ArrayList<>();
- String[] lines = content.split("\n", -1);
-
- for (int i = 0; i < lines.length; i++) {
- String line = lines[i];
- if (line.isBlank()) {
- continue;
- }
- String trimmed = line.trim();
- if (trimmed.startsWith("#")) {
- continue;
- }
-
- Matcher m = YAML_URI_PATTERN.matcher(line);
- if (!m.find()) {
- continue;
- }
-
- String uri = m.group(1);
- if (uri.endsWith("\"")) {
- uri = uri.substring(0, uri.length() - 1);
- }
- if (uri.startsWith("{{")) {
- continue;
- }
- // scheme-only URI (e.g., "uri: timer") needs a colon for catalog parsing
- if (!uri.contains(":")) {
- uri = uri + ":";
- }
-
- String eipName = extractEipFromLine(trimmed);
- int lineIndent = countLeadingSpaces(line);
-
- // for "uri:" lines, walk backwards to find the parent EIP (from, to, etc.)
- if ("uri".equals(eipName)) {
- for (int j = i - 1; j >= 0; j--) {
- String prev = lines[j];
- if (prev.isBlank()) {
- continue;
- }
- int prevIndent = countLeadingSpaces(prev);
- if (prevIndent < lineIndent) {
- eipName = extractEipFromLine(prev.trim());
- break;
- }
- }
- }
-
- boolean consumerOnly = eipName != null && YamlSourceContext.CONSUMER_EIPS.contains(eipName);
- boolean producerOnly = eipName != null && YamlSourceContext.PRODUCER_EIPS.contains(eipName);
-
- // look ahead for a parameters: block at the same indent level as uri
- StringBuilder uriBuilder = new StringBuilder(uri);
- boolean hasParams = uri.contains("?");
- Map<String, Integer> optionLineMap = new LinkedHashMap<>();
- for (int j = i + 1; j < lines.length; j++) {
- String next = lines[j];
- if (next.isBlank()) {
- continue;
- }
- int nextIndent = countLeadingSpaces(next);
- if (nextIndent < lineIndent) {
- break;
- }
- String nextTrimmed = next.trim();
- if (nextIndent == lineIndent && nextTrimmed.startsWith("parameters:")) {
- int paramBlockIndent = nextIndent;
- for (int k = j + 1; k < lines.length; k++) {
- String paramLine = lines[k];
- if (paramLine.isBlank()) {
- continue;
- }
- int paramIndent = countLeadingSpaces(paramLine);
- if (paramIndent <= paramBlockIndent) {
- break;
- }
- String paramTrimmed = paramLine.trim();
- int colonPos = paramTrimmed.indexOf(':');
- if (colonPos > 0) {
- String key = paramTrimmed.substring(0, colonPos).trim();
- String val = paramTrimmed.substring(colonPos + 1).trim();
- if (val.startsWith("\"") && val.endsWith("\"") && val.length() > 1) {
- val = val.substring(1, val.length() - 1);
- } else if (val.startsWith("'") && val.endsWith("'") && val.length() > 1) {
- val = val.substring(1, val.length() - 1);
- }
- char sep = hasParams ? '&' : '?';
- uriBuilder.append(sep).append(key).append('=').append(val);
- hasParams = true;
- optionLineMap.put(key, k);
- }
- }
- break;
- }
- if (nextIndent == lineIndent) {
- break;
- }
- }
-
- String fullUri = uriBuilder.toString();
- try {
- EndpointValidationResult result
- = catalog.validateEndpointProperties(fullUri, false, consumerOnly, producerOnly);
- if (!result.isSuccess()) {
- String scheme = fullUri.contains(":") ? fullUri.substring(0, fullUri.indexOf(':')) : fullUri;
- collectEndpointErrors(errors, result, scheme, i, optionLineMap);
- }
- } catch (Exception e) {
- // ignore validation errors
- }
- }
- return errors;
- }
-
- static void collectEndpointErrors(
- List<String> errors, EndpointValidationResult result, String scheme,
- int uriLineIdx, Map<String, Integer> optionLineMap) {
- if (result.getUnknown() != null) {
- for (String name : result.getUnknown()) {
- StringBuilder sb = new StringBuilder(scheme).append(": Unknown option '").append(name).append("'");
- if (result.getUnknownSuggestions() != null) {
- String[] suggestions = result.getUnknownSuggestions().get(name);
- if (suggestions != null && suggestions.length > 0) {
- sb.append(". Did you mean: ").append(Arrays.asList(suggestions));
- }
- }
- errors.add(linePrefix(optionLineMap.getOrDefault(name, uriLineIdx)) + sb);
- }
- }
- if (result.getInvalidBoolean() != null) {
- for (Map.Entry<String, String> entry : result.getInvalidBoolean().entrySet()) {
- errors.add(linePrefix(optionLineMap.getOrDefault(entry.getKey(), uriLineIdx))
- + scheme + ": Invalid boolean value '" + entry.getValue() + "' for option '" + entry.getKey() + "'");
- }
- }
- if (result.getInvalidInteger() != null) {
- for (Map.Entry<String, String> entry : result.getInvalidInteger().entrySet()) {
- errors.add(linePrefix(optionLineMap.getOrDefault(entry.getKey(), uriLineIdx))
- + scheme + ": Invalid integer value '" + entry.getValue() + "' for option '" + entry.getKey() + "'");
- }
- }
- if (result.getInvalidNumber() != null) {
- for (Map.Entry<String, String> entry : result.getInvalidNumber().entrySet()) {
- errors.add(linePrefix(optionLineMap.getOrDefault(entry.getKey(), uriLineIdx))
- + scheme + ": Invalid number value '" + entry.getValue() + "' for option '" + entry.getKey() + "'");
- }
- }
- if (result.getInvalidEnum() != null) {
- for (Map.Entry<String, String> entry : result.getInvalidEnum().entrySet()) {
- StringBuilder sb = new StringBuilder(scheme)
- .append(": Invalid enum value '").append(entry.getValue())
- .append("' for option '").append(entry.getKey()).append("'");
- if (result.getInvalidEnumChoices() != null) {
- String[] choices = result.getInvalidEnumChoices().get(entry.getKey());
- if (choices != null) {
- sb.append(". Possible values: ").append(Arrays.asList(choices));
- }
- }
- errors.add(linePrefix(optionLineMap.getOrDefault(entry.getKey(), uriLineIdx)) + sb);
- }
- }
- if (result.getNotConsumerOnly() != null) {
- for (String name : result.getNotConsumerOnly()) {
- errors.add(linePrefix(optionLineMap.getOrDefault(name, uriLineIdx))
- + scheme + ": Option '" + name + "' is not applicable in consumer only mode");
- }
- }
- if (result.getNotProducerOnly() != null) {
- for (String name : result.getNotProducerOnly()) {
- errors.add(linePrefix(optionLineMap.getOrDefault(name, uriLineIdx))
- + scheme + ": Option '" + name + "' is not applicable in producer only mode");
- }
- }
- }
-
- static String linePrefix(int lineIdx) {
- return "Line " + (lineIdx + 1) + ": ";
+ return SourceValidator.validateYamlSimple(content, catalog);
}
static String extractEipFromLine(String trimmed) {
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SourceValidationSupport.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SourceValidationSupport.java
index 5133524a3117..2f59a9b85cb3 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SourceValidationSupport.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/SourceValidationSupport.java
@@ -22,6 +22,8 @@ import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import org.apache.camel.dsl.jbang.core.commands.ai.SourceValidator;
+
/**
* Helpers that turn raw YAML schema / properties validation messages into the inline error map shown in the editor
* gutter.
@@ -58,78 +60,18 @@ final class SourceValidationSupport {
}
static String cleanValidationMessage(String msg) {
- // strip FQCN prefix like "com.fasterxml...MarkedYAMLException: "
- int colonSpace = msg.indexOf(": ");
- if (colonSpace > 0) {
- String prefix = msg.substring(0, colonSpace);
- if (prefix.contains(".") && !prefix.contains(" ")) {
- msg = msg.substring(colonSpace + 2);
- }
- }
- // strip "at [Source: (StringReader); line: N, column: N]"
- int atSource = msg.indexOf("at [Source:");
- if (atSource > 0) {
- msg = msg.substring(0, atSource).stripTrailing();
- }
- // strip "in 'reader', " prefix from snakeyaml messages
- msg = msg.replace("in 'reader', ", "");
- return msg;
+ return SourceValidator.cleanValidationMessage(msg);
}
- /** Validates a properties file line by line with the given validator, reporting {@code Line n: message}. */
static List<String> validatePropertiesLines(String content, java.util.function.Function<String, String> lineValidator) {
- List<String> msgs = new java.util.ArrayList<>();
- if (content == null) {
- return msgs;
- }
- String[] lines = content.split("\n", -1);
- for (int i = 0; i < lines.length; i++) {
- String line = lines[i].trim();
- if (line.isEmpty() || line.startsWith("#") || line.startsWith("!") || !line.contains("=")) {
- continue;
- }
- String error = lineValidator.apply(lines[i]);
- if (error != null) {
- msgs.add("Line " + (i + 1) + ": " + error);
- }
- }
- return msgs;
+ return SourceValidator.validatePropertiesLines(content, lineValidator);
}
- /** Formats YAML DSL schema errors the way the editor shows them: {@code node: message}. */
static List<String> formatSchemaErrors(List<com.networknt.schema.Error> errors) {
- List<String> msgs = new java.util.ArrayList<>();
- if (errors == null) {
- return msgs;
- }
- for (com.networknt.schema.Error error : errors) {
- String msg = error.getMessage();
- if (msg == null) {
- continue;
- }
- String loc = error.getInstanceLocation() != null ? error.getInstanceLocation().toString() : null;
- String node = extractNodeName(loc);
- String clean = cleanValidationMessage(msg);
- msgs.add(node != null ? node + ": " + clean : clean);
- }
- return msgs;
+ return SourceValidator.formatSchemaErrors(errors);
}
static String extractNodeName(String instanceLocation) {
- if (instanceLocation == null || instanceLocation.isEmpty()) {
- return null;
- }
- int slash = instanceLocation.lastIndexOf('/');
- String last = slash >= 0 ? instanceLocation.substring(slash + 1) : instanceLocation;
- if (last.isEmpty()) {
- return null;
- }
- // skip pure numeric segments (array indices)
- try {
- Integer.parseInt(last);
- return null;
- } catch (NumberFormatException e) {
- return last;
- }
+ return SourceValidator.extractNodeName(instanceLocation);
}
}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolDefinitions.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolDefinitions.java
index d3a900435264..8972afc0e00c 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolDefinitions.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolDefinitions.java
@@ -20,14 +20,18 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
+import org.apache.camel.dsl.jbang.core.commands.ai.ToolDescriptor;
+import org.apache.camel.dsl.jbang.core.commands.ai.ToolRegistry;
import org.apache.camel.dsl.jbang.core.commands.tui.TuiToolRegistry.ToolDef;
import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
/**
- * The MCP tool definitions (name, description and JSON input schema) exposed by the TUI. This class is pure data; the
- * matching implementations live in {@link TuiToolRegistry} and are dispatched by tool name, so a new tool needs an
- * entry here and a {@code call*} method there.
+ * The MCP tool definitions (name, description and JSON input schema) exposed by the TUI: the {@code camel_} authoring
+ * tools shared with every Camel MCP server ({@link ToolRegistry#authoringTools()}) and the {@code tui_} tools that only
+ * make sense in front of the screen. This class is pure data; the matching implementations live in
+ * {@link TuiToolRegistry} and are dispatched by tool name, so a new TUI tool needs an entry here and a {@code call*}
+ * method there.
*/
final class TuiToolDefinitions {
@@ -41,12 +45,38 @@ final class TuiToolDefinitions {
List<ToolDef> tools = new ArrayList<>();
addInteractionTools(tools);
addStructuredDataTools(tools);
+ addSharedTools(tools);
addCatalogTools(tools);
addLogTools(tools);
addExampleTools(tools);
return List.copyOf(tools);
}
+ /**
+ * The neutral authoring tools shared with camel-jbang-mcp (CAMEL-24695): defined once in the shared registry and
+ * exposed here under the same {@code camel_} names, so an agent gets the same Camel through either MCP server. Two
+ * of them get a TUI extra: camel_control also knows the TUI's stop-all and close actions, and camel_get_log also
+ * reads the log of an infra service.
+ */
+ private static void addSharedTools(List<ToolDef> tools) {
+ for (ToolDescriptor td : ToolRegistry.authoringTools()) {
+ JsonObject schema = td.inputSchema();
+ JsonObject properties = (JsonObject) schema.get("properties");
+ // the TUI answers for the selected integration's Camel version; the argument would only cost tokens
+ properties.remove("camelVersion");
+ String description = td.description();
+ if (TuiToolRegistry.CONTROL_TOOL.equals(td.name())) {
+ description += " In the TUI also stop-all (every process) and close (a phantom project).";
+ JsonObject action = (JsonObject) properties.get("action");
+ action.put("description", action.getString("description") + ", or stop-all, close");
+ } else if (TuiToolRegistry.LOG_TOOL.equals(td.name())) {
+ description += " With infra=<alias> the log of an infra service instead.";
+ properties.put("infra", propDef("string", "Infra service alias whose log to read instead"));
+ }
+ tools.add(new ToolDef(td.name(), description, schema));
+ }
+ }
+
/**
* Tools that read or drive the screen: screen text, events, state, captions, navigation, key presses, waiting, tape
* recording, drawing, themes and actions.
@@ -269,20 +299,6 @@ final class TuiToolDefinitions {
"Switches the TUI to a named theme. Use tui_get_themes to list available theme IDs.",
Map.of("theme", propDef("string", "Theme ID (e.g. 'dracula', 'nord', 'catppuccin-mocha')")),
List.of("theme"))));
- tools.add(toToolDef(toolDef(
- "tui_get_log",
- "Returns recent log lines as structured data with optional filtering. "
- + "Returns newest entries first. Reads the selected integration's log, or an infra "
- + "service's log when infra=<alias> is given.",
- Map.of("limit", propDef("integer", "Maximum lines to return (default 50)"),
- "filter", propDef("string", "Case-insensitive substring filter on log message"),
- "level", propDef("string", "Filter by log level (INFO, WARN, ERROR, DEBUG, TRACE)"),
- "infra", propDef("string", "Infra service alias whose log to read instead")))));
- tools.add(toToolDef(toolDef(
- "tui_get_errors",
- "Returns structured error data from the Errors tab. "
- + "Includes routeId, exchangeId, exception details, stack trace, body, and headers.",
- Map.of())));
tools.add(toToolDef(toolDef(
"tui_get_diagram",
"Returns the route topology diagram as text. "
@@ -392,14 +408,6 @@ final class TuiToolDefinitions {
+ "If no name is provided, returns the README for the currently selected integration.",
Map.of("name", propDef("string",
"Integration name. If omitted, uses the currently selected integration.")))));
- tools.add(toToolDef(toolDef(
- "tui_control",
- "Controls the selected integration. Actions: reset-stats (clear statistics, activity, errors and "
- + "traces, routes untouched), stop-routes/pause, start-routes/resume, restart, stop "
- + "(graceful), kill, stop-all (every process), close (a phantom project).",
- Map.of("action", propDef("string",
- "reset-stats, stop-routes, start-routes, pause, resume, restart, stop, kill, stop-all or close")),
- List.of("action"))));
tools.add(toToolDef(toolDef(
"tui_infra",
"Lists and controls infra services (brokers, databases started with camel infra run, e.g. "
@@ -414,53 +422,12 @@ final class TuiToolDefinitions {
tools.add(toToolDef(toolDef(
"tui_open_project",
"Opens a project directory as a phantom integration (shown as Stopped in Overview). "
- + "The project can then be browsed in the Source tab and run via tui_control. "
+ + "The project can then be browsed in the Source tab and run via camel_control. "
+ "Supports Maven projects (Spring Boot, Quarkus, Camel Main detected via pom.xml) "
+ "and flat directories with Camel route files.",
Map.of("directory", propDef("string",
"Absolute path to the project directory to open")),
List.of("directory"))));
- tools.add(toToolDef(toolDef(
- "tui_get_files",
- "Returns source files from the selected integration's directory. "
- + "Without a file parameter, returns the list of files (name, size, type). "
- + "With a file parameter, returns the file's content. "
- + "Useful for reading route source code, configuration, and other integration files.",
- Map.of("name", propDef("string",
- "Integration name. If omitted, uses the currently selected integration."),
- "file", propDef("string",
- "Filename to read. If omitted, returns the file list instead.")))));
- tools.add(toToolDef(toolDef(
- "tui_write_file",
- "Writes the complete content of a file in the integration's source directory (tui_get_files tells "
- + "the directory and whether edits reload). The user confirms in the TUI. YAML and "
- + ".properties content is validated first; invalid content is not written and the "
- + "errors are returned.",
- Map.of("name", propDef("string", "Integration name (default: the selected one)."),
- "file", propDef("string", "File name, no path."),
- "content", propDef("string", "The complete new content."),
- "confirm", propDef("boolean",
- "Set false only when the user enabled /write auto; never to retry a rejected write."),
- "validate", propDef("boolean", "Validate before writing (default true).")),
- List.of("file", "content"))));
- tools.add(toToolDef(toolDef(
- "tui_validate_source",
- "Validates Camel YAML DSL or .properties source without writing: schema (misspelled options such as "
- + "logLevel instead of loggingLevel), endpoint URIs, simple expressions, camel.* "
- + "options. Use on content before writing it, or on an existing file (no content) "
- + "to explain a reload error.",
- Map.of("name", propDef("string", "Integration name (default: the selected one)."),
- "file", propDef("string", "File name; picks the checks by extension, read when no content."),
- "content", propDef("string", "The source to validate.")),
- List.of("file"))));
- tools.add(toToolDef(toolDef(
- "tui_eval_expression",
- "Evaluates an expression in the running integration: the value (true/false for a predicate), or "
- + "the syntax error. Check simple before answering or writing it.",
- Map.of("expression", propDef("string", "e.g. ${random(1,10)} or ${body} ?: 'none'"),
- "language", propDef("string", "simple (default), jsonpath, xpath, jq"),
- "body", propDef("string", "Message body")),
- List.of("expression"))));
tools.add(toToolDef(toolDef(
"tui_get_spans",
"OpenTelemetry spans of the selected integration (traceId, spanId, parentSpanId, name, kind, "
@@ -486,23 +453,6 @@ final class TuiToolDefinitions {
* Camel catalog documentation tools.
*/
private static void addCatalogTools(List<ToolDef> tools) {
- tools.add(toToolDef(toolDef(
- "tui_catalog_doc",
- "Camel catalog documentation of a component, data format, language or EIP (description, options, "
- + "Maven coordinates) for the integration's Camel version. For simple also its "
- + "syntax rules, functions and operators: count and names by group, or with "
- + "optionsFilter the matching ones with parameters and examples. endpoint "
- + "validates a URI: unknown or invalid options, missing path.",
- Map.of("name", propDef("string", "Name, e.g. kafka, json-jackson, simple, timer, choice, split"),
- "endpoint", propDef("string", "Endpoint URI to check, e.g. kafka:orders?brokers=host:9092"),
- "kind", propDef("string", "component, dataformat, language or eip (auto-detected)"),
- "includeOptions", propDef("boolean", "Include the options (default true)"),
- "includeDoc", propDef("boolean", "Include the full AsciiDoc page (default false)"),
- "docPage", propDef("string", "A language doc sub-page (simple: functions, operators, ognl, "
- + "advanced) to return as text"),
- "optionsFilter", propDef("string", "Keyword to match in option names or descriptions")),
- List.of())));
-
tools.add(toToolDef(toolDef(
"tui_get_processor_detail",
"The processors of a route with their configured options (type, id, endpointUri, attributes, "
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistry.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistry.java
index 34b7450e4655..035a8b03a6b7 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistry.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/main/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistry.java
@@ -17,28 +17,29 @@
package org.apache.camel.dsl.jbang.core.commands.tui;
import java.util.ArrayList;
-import java.util.Arrays;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
-import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
import dev.tamboui.buffer.Buffer;
import dev.tamboui.export.ExportRequest;
import dev.tamboui.style.Color;
import dev.tamboui.style.Style;
import org.apache.camel.catalog.CamelCatalog;
-import org.apache.camel.catalog.EndpointValidationResult;
+import org.apache.camel.dsl.jbang.core.commands.ai.ToolContext;
+import org.apache.camel.dsl.jbang.core.commands.ai.ToolDescriptor;
+import org.apache.camel.dsl.jbang.core.commands.ai.ToolExecutionException;
+import org.apache.camel.dsl.jbang.core.commands.ai.ToolRegistry;
import org.apache.camel.dsl.jbang.core.common.CatalogLoader;
import org.apache.camel.dsl.jbang.core.common.ExampleHelper;
-import org.apache.camel.tooling.model.BaseModel;
import org.apache.camel.tooling.model.BaseOptionModel;
import org.apache.camel.tooling.model.ComponentModel;
-import org.apache.camel.tooling.model.DataFormatModel;
import org.apache.camel.tooling.model.EipModel;
-import org.apache.camel.tooling.model.LanguageModel;
import org.apache.camel.util.TimeUtils;
import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
@@ -84,33 +85,105 @@ class TuiToolRegistry {
return facade != null ? facade.getLaunchManager() : null;
}
+ /**
+ * Runs a shared {@code camel_} tool with the TUI's extras: the file tools work on the selected integration's source
+ * directory unless a directory is given (a write then goes through the TUI's confirm dialog or live replay),
+ * camel_control knows the TUI's own actions, camel_get_log also reads an infra service log.
+ */
+ private String executeSharedWithTuiExtras(String name, Map<String, Object> args) {
+ boolean hasDirectory = args.get("directory") instanceof String d && !d.isBlank();
+ boolean facadeSelection = facade != null && facade.getSelectedIntegrationName() != null;
+ return switch (name) {
+ case CONTROL_TOOL -> facade != null ? callControl(args) : executeShared(name, args);
+ case LOG_TOOL -> facade != null ? callGetLog(args) : executeShared(name, args);
+ case FILES_TOOL -> !hasDirectory && facadeSelection ? callGetFiles(args) : executeShared(name, args);
+ case WRITE_TOOL -> !hasDirectory && facadeSelection ? callWriteFile(args) : executeShared(name, args);
+ case VALIDATE_TOOL -> !hasDirectory && facadeSelection && args.get("content") == null
+ ? callValidateSource(args) : executeShared(name, args);
+ default -> executeShared(name, args);
+ };
+ }
+
+ /**
+ * Runs a shared tool from the registry over a context built from the TUI's selection: the selected integration's
+ * pid, Camel version and source directory, and the editor's Spring Boot property check.
+ */
+ private String executeShared(String name, Map<String, Object> args) {
+ ToolDescriptor descriptor = ToolRegistry.findTool(name);
+ if (descriptor == null) {
+ throw new IllegalArgumentException("Unknown tool: " + name);
+ }
+ Map<String, String> stringArgs = new LinkedHashMap<>();
+ for (Map.Entry<String, Object> e : args.entrySet()) {
+ if (e.getValue() != null) {
+ stringArgs.put(e.getKey(), String.valueOf(e.getValue()));
+ }
+ }
+ ToolContext ctx = new ToolContext();
+ // what the user selected is the integration; nothing selected means nothing, not the only one running
+ ctx.setAutoSelectSingleProcess(false);
+ if (facade != null) {
+ String pid = facade.getSelectedPid();
+ if (pid != null) {
+ try {
+ ctx.selectProcess(Long.parseLong(pid));
+ } catch (NumberFormatException e) {
+ // a phantom project has no process
+ }
+ }
+ ctx.setCamelVersion(facade.getSelectedCamelVersion());
+ ctx.setDefaultDirectory(facade.getSelectedSourceDirectory());
+ ctx.setPropertyLineValidator(facade.getPropertyLineValidator());
+ }
+ try {
+ Object result = ToolRegistry.execute(name, ctx, stringArgs);
+ return result != null ? result.toString() : "";
+ } catch (ToolExecutionException e) {
+ return "Error: " + e.getMessage();
+ }
+ }
+
/**
* The tools needed to answer questions and troubleshoot from the built-in AI panel. The remaining tools drive the
* screen (drawing, animation, key presses, tape recording, themes) and exist for external MCP agents. Every tool
* schema is sent on every request, and a local model pays for that in prompt-processing time, so the AI panel sends
* only this subset to local providers unless configured otherwise.
*/
- static final Set<String> CORE_TOOLS = Set.of(
- "tui_get_state", "tui_get_options", "tui_get_table", "tui_get_log", "tui_get_errors",
- "tui_get_diagram", "tui_get_topology", "tui_get_processor_detail", "tui_catalog_doc",
- "tui_get_history", "tui_get_spans", "tui_control", "tui_send_message", "tui_get_files", "tui_write_file",
- "tui_validate_source", "tui_eval_expression",
- "tui_get_readme", "tui_navigate", "tui_set_log_level", "tui_filter", "tui_get_status",
- "tui_infra");
+ static final String SHARED_PREFIX = "camel_";
+ static final String CONTROL_TOOL = "camel_control";
+ static final String LOG_TOOL = "camel_get_log";
+ static final String FILES_TOOL = "camel_get_files";
+ static final String WRITE_TOOL = "camel_write_file";
+ static final String VALIDATE_TOOL = "camel_validate_source";
+
+ /** The TUI's own tools in the core subset; the shared tools add those flagged core in the registry. */
+ private static final Set<String> CORE_TUI_TOOLS = Set.of(
+ "tui_get_state", "tui_get_options", "tui_get_table", "tui_get_diagram", "tui_get_topology",
+ "tui_get_processor_detail", "tui_get_history", "tui_get_spans", "tui_send_message",
+ "tui_get_readme", "tui_navigate", "tui_set_log_level", "tui_filter", "tui_get_status", "tui_infra");
+
+ static final Set<String> CORE_TOOLS = Stream.concat(
+ CORE_TUI_TOOLS.stream(),
+ ToolRegistry.authoringTools().stream().filter(ToolDescriptor::isCore).map(ToolDescriptor::name))
+ .collect(Collectors.toUnmodifiableSet());
+
+ /** The TUI's own read-only tools; the shared tools add those flagged read-only in the registry. */
+ private static final Set<String> READ_ONLY_TUI_TOOLS = Set.of(
+ "tui_get_ai_log", "tui_get_diagram", "tui_get_events", "tui_get_history", "tui_get_mcp_log",
+ "tui_get_options", "tui_get_processor_detail", "tui_get_readme", "tui_get_screen", "tui_get_spans",
+ "tui_get_state", "tui_get_status", "tui_get_table", "tui_get_themes", "tui_get_topology",
+ "tui_list_examples", "tui_locate", "tui_wait_for_idle");
/**
* Tools that only return information and never change the TUI, the integration or its data. The ACP permission
- * handler approves calls to these without asking; anything else, including tui_control, tui_send_message and
- * tui_execute_sql, is put in front of the user. tui_eval_expression is here because it evaluates an expression
- * against a scratch exchange in the running integration and sends nothing through a route.
+ * handler approves calls to these without asking; anything else, including camel_control, tui_send_message and
+ * tui_execute_sql, is put in front of the user. camel_eval_expression is read-only because it evaluates an
+ * expression against a scratch exchange and sends nothing through a route.
*/
- static final Set<String> READ_ONLY_TOOLS = Set.of(
- "tui_catalog_doc", "tui_eval_expression", "tui_get_ai_log", "tui_get_diagram", "tui_get_errors",
- "tui_get_events",
- "tui_get_files", "tui_get_history", "tui_get_log", "tui_get_mcp_log", "tui_get_options",
- "tui_get_processor_detail", "tui_get_readme", "tui_get_screen", "tui_get_spans", "tui_get_state",
- "tui_get_status", "tui_get_table", "tui_get_themes", "tui_get_topology", "tui_list_examples",
- "tui_locate", "tui_validate_source", "tui_wait_for_idle");
+ static final Set<String> READ_ONLY_TOOLS = Stream.concat(
+ READ_ONLY_TUI_TOOLS.stream(),
+ ToolRegistry.authoringTools().stream().filter(ToolDescriptor::isReadOnly).map(ToolDescriptor::name))
+ .collect(Collectors.toUnmodifiableSet());
/**
* Returns all tool definitions. The result is cached since it is immutable.
@@ -136,6 +209,9 @@ class TuiToolRegistry {
* Executes a tool by name, returns result string.
*/
String execute(String name, Map<String, Object> args) throws Exception {
+ if (name != null && name.startsWith(SHARED_PREFIX)) {
+ return executeSharedWithTuiExtras(name, args);
+ }
return switch (name) {
case "tui_get_screen" -> callGetScreen(args);
case "tui_get_events" -> callGetEvents(args);
@@ -155,8 +231,6 @@ class TuiToolRegistry {
case "tui_action" -> callAction(args);
case "tui_get_themes" -> callGetThemes();
case "tui_set_theme" -> callSetTheme(args);
- case "tui_get_log" -> callGetLog(args);
- case "tui_get_errors" -> callGetErrors();
case "tui_get_diagram" -> callGetDiagram();
case "tui_get_history" -> callGetHistory(args);
case "tui_get_topology" -> callGetTopology();
@@ -168,13 +242,8 @@ class TuiToolRegistry {
case "tui_set_input" -> callSetInput(args);
case "tui_toggle_trace_display" -> callToggleTraceDisplay(args);
case "tui_get_readme" -> callGetReadme(args);
- case "tui_control" -> callControl(args);
case "tui_infra" -> callInfra(args);
case "tui_open_project" -> callOpenProject(args);
- case "tui_get_files" -> callGetFiles(args);
- case "tui_write_file" -> callWriteFile(args);
- case "tui_validate_source" -> callValidateSource(args);
- case "tui_eval_expression" -> callEvalExpression(args);
case "tui_get_spans" -> callGetSpans(args);
case "tui_locate" -> callLocate(args);
case "tui_draw_shape" -> callDrawShape(args);
@@ -182,7 +251,6 @@ class TuiToolRegistry {
case "tui_canvas_close" -> callCanvasClose();
case "tui_animate" -> callAnimate(args);
case "tui_animate_status" -> callAnimateStatus(args);
- case "tui_catalog_doc" -> callCatalogDoc(args);
case "tui_get_processor_detail" -> callGetProcessorDetail(args);
case "tui_get_ai_log" -> callGetAiLog(args);
case "tui_get_mcp_log" -> callGetMcpLog(args);
@@ -961,18 +1029,17 @@ class TuiToolRegistry {
return "Theme switched to '" + themeId + "'";
}
+ /** The shared camel_get_log tool with the TUI extra: infra=<alias> reads the log of an infra service instead. */
private String callGetLog(Map<String, Object> args) {
- int limit = 50;
- if (args.get("limit") instanceof Number n) {
- limit = Math.max(1, Math.min(1000, n.intValue()));
- }
- String filter = args.get("filter") instanceof String s ? s : null;
- String level = args.get("level") instanceof String s ? s : null;
if (args.get("infra") instanceof String alias && !alias.isBlank()) {
+ int limit = 50;
+ if (args.get("limit") instanceof Number n) {
+ limit = Math.max(1, Math.min(1000, n.intValue()));
+ }
+ String filter = args.get("filter") instanceof String v ? v : null;
return infraLog(alias, limit, filter);
}
- JsonObject data = facade.getLogData(limit, filter, level);
- return Jsoner.serialize(data);
+ return executeShared(LOG_TOOL, args);
}
private void addInfraContext(JsonObject result) {
@@ -1070,18 +1137,6 @@ class TuiToolRegistry {
}
}
- private String callGetErrors() {
- JsonObject data = facade.getTableData("Errors");
- if (data == null) {
- JsonObject empty = new JsonObject();
- empty.put("tab", "Errors");
- empty.put("rows", new JsonArray());
- empty.put("totalRows", 0);
- return Jsoner.serialize(empty);
- }
- return Jsoner.serialize(data);
- }
-
private String callGetDiagram() {
JsonObject data = facade.getDiagramData();
if (data == null) {
@@ -1121,20 +1176,6 @@ class TuiToolRegistry {
return Jsoner.serialize(data);
}
- private String callEvalExpression(Map<String, Object> args) {
- String expression = args.get("expression") instanceof String s ? s : null;
- if (expression == null || expression.isBlank()) {
- return "Error: expression is required";
- }
- String language = args.get("language") instanceof String s ? s : null;
- String body = args.get("body") instanceof String s ? s : null;
- JsonObject response = facade.evalExpression(language, expression, body);
- if (response == null) {
- return "Error: no integration selected or PID unavailable";
- }
- return Jsoner.serialize(response);
- }
-
private String callSendMessage(Map<String, Object> args) {
String endpoint = (String) args.get("endpoint");
if (endpoint == null || endpoint.isBlank()) {
@@ -1179,7 +1220,7 @@ class TuiToolRegistry {
return null;
}
if (similar.isEmpty()) {
- return "Camel has no component named '" + scheme + "'. Use tui_catalog_doc to find the right component, "
+ return "Camel has no component named '" + scheme + "'. Use camel_catalog_find to find the right component, "
+ "then send again with its scheme.";
}
return "Camel has no component named '" + scheme + "'. Similar components in the catalog: "
@@ -1318,7 +1359,7 @@ class TuiToolRegistry {
return Jsoner.serialize(response);
}
- /** Time the last tool call spent waiting for the user (a tui_write_file confirmation), see the AI panel. */
+ /** Time the last tool call spent waiting for the user (a camel_write_file confirmation), see the AI panel. */
long consumeConfirmWaitMs() {
return facade != null ? facade.consumeConfirmWaitMs() : 0;
}
@@ -1449,649 +1490,6 @@ class TuiToolRegistry {
return DrawOverlay.generateShape(shape, x, y, width, height, length, color);
}
- private String callCatalogDoc(Map<String, Object> args) {
- String name = args.get("name") instanceof String v ? v : null;
- String endpoint = args.get("endpoint") instanceof String v ? v.trim() : null;
- if ((name == null || name.isEmpty()) && (endpoint == null || endpoint.isEmpty())) {
- return "{\"error\": \"'name' or 'endpoint' parameter is required\"}";
- }
- String kind = args.get("kind") instanceof String v ? v : null;
- String optionsFilter = args.get("optionsFilter") instanceof String v ? v : null;
- boolean includeOptions = !Boolean.FALSE.equals(args.get("includeOptions"));
- boolean includeDoc = Boolean.TRUE.equals(args.get("includeDoc"));
- String docPage = args.get("docPage") instanceof String v ? v.trim().toLowerCase(Locale.ROOT) : null;
-
- String version = facade != null ? facade.getSelectedCamelVersion() : null;
- try {
- CamelCatalog catalog = CatalogLoader.loadCatalog(null, version, true);
- if (catalog == null) {
- return "{\"error\": \"Could not load catalog" + (version != null ? " for version " + version : "") + "\"}";
- }
- if (endpoint != null && !endpoint.isEmpty()) {
- return validateEndpoint(catalog, endpoint);
- }
- return buildCatalogDocResult(catalog, name, kind, optionsFilter, includeOptions, includeDoc, docPage);
- } catch (Exception e) {
- JsonObject err = new JsonObject();
- err.put("error", "Failed to load catalog: " + e.getMessage());
- return Jsoner.serialize(err);
- }
- }
-
- private String buildCatalogDocResult(
- CamelCatalog catalog, String name, String kind, String optionsFilter,
- boolean includeOptions, boolean includeDoc, String docPage) {
- String lowerFilter = optionsFilter != null ? optionsFilter.toLowerCase() : null;
-
- if (kind == null || "component".equals(kind)) {
- ComponentModel cm = catalog.componentModel(name);
- if (cm != null) {
- String doc = includeDoc ? catalog.asciiDoc(name + "-component") : null;
- return buildComponentDocJson(cm, lowerFilter, includeOptions, doc);
- }
- if (kind != null) {
- return notFound("Component", name, catalog.suggestComponentNames(name, 5));
- }
- }
- if (kind == null || "dataformat".equals(kind)) {
- DataFormatModel dm = catalog.dataFormatModel(name);
- if (dm != null) {
- String doc = includeDoc ? catalog.asciiDoc(name + "-dataformat") : null;
- return buildDataFormatDocJson(dm, lowerFilter, includeOptions, doc);
- }
- if (kind != null) {
- return notFound("Data format", name, catalog.suggestDataFormatNames(name, 5));
- }
- }
- if (kind == null || "language".equals(kind)) {
- LanguageModel lm = catalog.languageModel(name);
- if (lm != null) {
- String doc = null;
- if (docPage != null && !docPage.isEmpty()) {
- doc = catalog.asciiDoc(name + "-" + docPage);
- if (doc == null) {
- JsonObject error = new JsonObject();
- error.put("error", "No doc page '" + docPage + "' for language " + name);
- error.put("docPages", new JsonArray(languageDocPages(catalog, name)));
- return error.toJson();
- }
- } else if (includeDoc) {
- doc = catalog.asciiDoc(name + "-language");
- }
- boolean docPageOnly = docPage != null && !docPage.isEmpty();
- return buildLanguageDocJson(
- lm, lowerFilter, includeOptions, doc, languageDocPages(catalog, name), docPageOnly);
- }
- if (kind != null) {
- return notFound("Language", name, catalog.suggestLanguageNames(name, 5));
- }
- }
- if (kind == null || "eip".equals(kind)) {
- EipModel em = catalog.eipModel(name);
- if (em != null) {
- String doc = includeDoc ? catalog.asciiDoc(name + "-eip") : null;
- return buildEipDocJson(em, lowerFilter, includeOptions, doc);
- }
- if (kind != null) {
- return "{\"error\": \"EIP not found: " + name + "\"}";
- }
- }
- List<String> suggestions = new ArrayList<>(catalog.suggestComponentNames(name, 5));
- suggestions.addAll(catalog.suggestDataFormatNames(name, 3));
- suggestions.addAll(catalog.suggestLanguageNames(name, 3));
- return notFound("Artifact", name, suggestions);
- }
-
- /**
- * Checks an endpoint URI against the catalog the way the YAML validator does on a write: the component is taken
- * from the scheme, the path is parsed against the component's syntax and every option is checked. The problems come
- * back in words, with the closest real option name or the allowed values, and the options the URI uses come with
- * their documentation so a follow-up needs no second call.
- */
- String validateEndpoint(CamelCatalog catalog, String endpoint) {
- int colon = endpoint.indexOf(':');
- if (colon <= 0) {
- JsonObject error = new JsonObject();
- error.put("error", "Not an endpoint URI (scheme:path?options expected): " + endpoint);
- return error.toJson();
- }
- String scheme = endpoint.substring(0, colon).toLowerCase(Locale.ROOT);
- ComponentModel cm = catalog.componentModel(scheme);
- if (cm == null) {
- JsonObject error = new JsonObject();
- error.put("error", "Camel has no component named '" + scheme + "'");
- List<String> similar = catalog.suggestComponentNames(scheme, 5);
- if (!similar.isEmpty()) {
- error.put("suggestions", new JsonArray(similar));
- error.put("hint", "Check again with one of those schemes, e.g. '" + similar.get(0)
- + endpoint.substring(colon) + "'.");
- }
- return error.toJson();
- }
- JsonObject result = new JsonObject();
- result.put("kind", "component");
- result.put("name", scheme);
- result.put("title", cm.getTitle());
- result.put("endpoint", endpoint);
- if (cm.getSyntax() != null) {
- result.put("syntax", cm.getSyntax());
- result.put("uriSyntax", uriSyntax(cm));
- }
- EndpointValidationResult validation;
- try {
- validation = catalog.validateEndpointProperties(endpoint, false, false, false);
- } catch (Exception e) {
- result.put("valid", false);
- result.put("problems", new JsonArray(List.of("Cannot parse the URI: " + e.getMessage())));
- return Jsoner.serialize(result);
- }
- List<String> problems = endpointProblems(validation);
- List<String> warnings = new ArrayList<>();
- if (validation.getDeprecated() != null) {
- for (String name : validation.getDeprecated()) {
- warnings.add("Option '" + name + "' is deprecated");
- }
- }
- if (validation.getDefaultValues() != null) {
- for (Map.Entry<String, String> entry : validation.getDefaultValues().entrySet()) {
- warnings.add("Option '" + entry.getKey() + "' is set to its default value " + entry.getValue());
- }
- }
- result.put("valid", problems.isEmpty());
- result.put("problems", new JsonArray(problems));
- if (!warnings.isEmpty()) {
- result.put("warnings", new JsonArray(warnings));
- }
- // the options the URI uses (path parts included), with their catalog documentation
- Map<String, String> used;
- try {
- used = catalog.endpointProperties(endpoint);
- } catch (Exception e) {
- used = Map.of();
- }
- JsonArray options = new JsonArray();
- if (cm.getEndpointOptions() != null) {
- for (BaseOptionModel opt : cm.getEndpointOptions()) {
- if (used.containsKey(opt.getName())) {
- JsonObject o = optionToJson(opt, "endpoint");
- o.put("value", used.get(opt.getName()));
- options.add(o);
- }
- }
- }
- result.put("usedOptions", options);
- result.put("message", problems.isEmpty()
- ? "The URI is valid for the " + scheme + " component"
- : problems.size() + " problem(s); fix them before using the URI");
- return Jsoner.serialize(result);
- }
-
- static List<String> endpointProblems(EndpointValidationResult r) {
- List<String> problems = new ArrayList<>();
- if (r.getSyntaxError() != null) {
- problems.add("Syntax error: " + r.getSyntaxError());
- }
- if (r.getUnknownComponent() != null) {
- problems.add("Unknown component: " + r.getUnknownComponent());
- }
- if (r.getIncapable() != null) {
- problems.add("Cannot validate: " + r.getIncapable());
- }
- if (r.getUnknown() != null) {
- for (String name : r.getUnknown()) {
- StringBuilder sb = new StringBuilder("Unknown option '").append(name).append("'");
- // the catalog suggests the closest names itself (edit distance, CAMEL-24666)
- String[] suggestions = r.getUnknownSuggestions() != null ? r.getUnknownSuggestions().get(name) : null;
- if (suggestions != null && suggestions.length > 0) {
- sb.append(". Did you mean: ").append(Arrays.asList(suggestions));
- }
- problems.add(sb.toString());
- }
- }
- if (r.getRequired() != null) {
- for (String name : r.getRequired()) {
- problems.add("Missing required option '" + name + "'");
- }
- }
- if (r.getInvalidEnum() != null) {
- for (Map.Entry<String, String> entry : r.getInvalidEnum().entrySet()) {
- StringBuilder sb = new StringBuilder("Invalid value '").append(entry.getValue())
- .append("' for option '").append(entry.getKey()).append("'");
- String[] choices = r.getInvalidEnumChoices() != null ? r.getInvalidEnumChoices().get(entry.getKey()) : null;
- if (choices != null) {
- sb.append(". Possible values: ").append(Arrays.asList(choices));
- }
- problems.add(sb.toString());
- }
- }
- addInvalid(problems, r.getInvalidBoolean(), "boolean");
- addInvalid(problems, r.getInvalidInteger(), "integer");
- addInvalid(problems, r.getInvalidNumber(), "number");
- addInvalid(problems, r.getInvalidDuration(), "duration");
- addInvalid(problems, r.getInvalidReference(), "reference (#bean)");
- addInvalid(problems, r.getInvalidMap(), "map");
- addInvalid(problems, r.getInvalidArray(), "array");
- if (r.getNotConsumerOnly() != null) {
- for (String name : r.getNotConsumerOnly()) {
- problems.add("Option '" + name + "' is a producer option; not for a from (consumer) endpoint");
- }
- }
- if (r.getNotProducerOnly() != null) {
- for (String name : r.getNotProducerOnly()) {
- problems.add("Option '" + name + "' is a consumer option; not for a to (producer) endpoint");
- }
- }
- return problems;
- }
-
- private static void addInvalid(List<String> problems, Map<String, String> invalid, String type) {
- if (invalid != null) {
- for (Map.Entry<String, String> entry : invalid.entrySet()) {
- problems.add("Invalid " + type + " value '" + entry.getValue() + "' for option '" + entry.getKey() + "'");
- }
- }
- }
-
- /**
- * Error for a catalog lookup that found nothing, with the names the catalog suggests for the term (a protocol or
- * product name such as mqtt or s3) so the next call can use one of them.
- */
- private static String notFound(String kind, String name, List<String> suggestions) {
- JsonObject error = new JsonObject();
- error.put("error", kind + " not found: " + name);
- if (!suggestions.isEmpty()) {
- error.put("suggestions", new JsonArray(suggestions));
- }
- return error.toJson();
- }
-
- @SuppressWarnings("unchecked")
- private static void addCommonModelFields(JsonObject result, BaseModel<?> model) {
- if (model.getFirstVersion() != null) {
- result.put("since", model.getFirstVersion());
- }
- if (model.getSupportLevel() != null) {
- result.put("supportLevel", model.getSupportLevel().name());
- }
- if (model.isNativeSupported()) {
- result.put("nativeSupported", true);
- }
- if (model.isDeprecated()) {
- result.put("deprecated", true);
- if (model.getDeprecatedSince() != null) {
- result.put("deprecatedSince", model.getDeprecatedSince());
- }
- if (model.getDeprecationNote() != null) {
- result.put("deprecationNote", model.getDeprecationNote());
- }
- }
- }
-
- /**
- * The rules of an endpoint URI for this component, spelled out with its own path parts: what a small model gets
- * wrong most is a path option written as a query parameter or the other way round, and the YAML form.
- */
- static String uriSyntax(ComponentModel model) {
- List<String> path = new ArrayList<>();
- if (model.getEndpointOptions() != null) {
- for (BaseOptionModel opt : model.getEndpointOptions()) {
- if ("path".equals(opt.getKind())) {
- path.add(opt.getName());
- }
- }
- }
- StringBuilder sb = new StringBuilder();
- sb.append("URI: ").append(model.getSyntax()).append("?option=value&option=value. ");
- if (path.isEmpty()) {
- sb.append("The path has no options; ");
- } else {
- sb.append("The path options (").append(String.join(", ", path))
- .append(") go in the path, never as ?name=value; ");
- }
- sb.append("every other endpoint option is a query parameter after ?, separated by &.")
- .append(" In YAML DSL: uri: ").append(model.getScheme()).append(":<path> plus a parameters: map of the")
- .append(" query options (or the full URI in uri). Values may use {{property.placeholders}};")
- .append(" wrap a value containing & or + in RAW(value). Component options (scope component) are")
- .append(" set in application.properties as camel.component.").append(model.getScheme())
- .append(".<option>=value, not on the URI.");
- return sb.toString();
- }
-
- private String buildComponentDocJson(ComponentModel model, String filter, boolean includeOptions, String doc) {
- JsonObject result = new JsonObject();
- result.put("kind", "component");
- result.put("name", model.getScheme());
- result.put("title", model.getTitle());
- result.put("description", model.getDescription());
- if (model.getLabel() != null) {
- result.put("label", model.getLabel());
- }
- if (model.getSyntax() != null) {
- result.put("syntax", model.getSyntax());
- result.put("uriSyntax", uriSyntax(model));
- }
- result.put("consumerOnly", model.isConsumerOnly());
- result.put("producerOnly", model.isProducerOnly());
- result.put("remote", model.isRemote());
- result.put("groupId", model.getGroupId());
- result.put("artifactId", model.getArtifactId());
- addCommonModelFields(result, model);
-
- if (includeOptions) {
- JsonArray options = new JsonArray();
- if (model.getComponentOptions() != null) {
- for (BaseOptionModel opt : model.getComponentOptions()) {
- if (matchesOptionFilter(opt, filter)) {
- options.add(optionToJson(opt, "component"));
- }
- }
- }
- if (model.getEndpointOptions() != null) {
- for (BaseOptionModel opt : model.getEndpointOptions()) {
- if (matchesOptionFilter(opt, filter)) {
- options.add(optionToJson(opt, "endpoint"));
- }
- }
- }
- result.put("options", options);
- result.put("matchedOptions", options.size());
- }
- if (doc != null) {
- result.put("doc", doc);
- }
- return Jsoner.serialize(result);
- }
-
- private String buildDataFormatDocJson(DataFormatModel model, String filter, boolean includeOptions, String doc) {
- JsonObject result = new JsonObject();
- result.put("kind", "dataformat");
- result.put("name", model.getName());
- result.put("title", model.getTitle());
- result.put("description", model.getDescription());
- if (model.getLabel() != null) {
- result.put("label", model.getLabel());
- }
- result.put("groupId", model.getGroupId());
- result.put("artifactId", model.getArtifactId());
- addCommonModelFields(result, model);
-
- if (includeOptions) {
- JsonArray options = new JsonArray();
- if (model.getOptions() != null) {
- for (BaseOptionModel opt : model.getOptions()) {
- if (matchesOptionFilter(opt, filter)) {
- options.add(optionToJson(opt, null));
- }
- }
- }
- result.put("options", options);
- result.put("matchedOptions", options.size());
- }
- if (doc != null) {
- result.put("doc", doc);
- }
- return Jsoner.serialize(result);
- }
-
- /** The sub-pages of a language's documentation (simple has functions, operators, ognl and advanced). */
- private static List<String> languageDocPages(CamelCatalog catalog, String name) {
- List<String> pages = new ArrayList<>();
- for (String page : LANGUAGE_DOC_PAGES) {
- if (catalog.asciiDoc(name + "-" + page) != null) {
- pages.add(page);
- }
- }
- return pages;
- }
-
- private static final List<String> LANGUAGE_DOC_PAGES = List.of("functions", "operators", "ognl", "advanced");
-
- /**
- * The rules a small model gets wrong most: functions live inside the placeholder, operators between placeholders.
- * Sent with the simple language result so an answer's examples follow the same shape as the catalog's.
- */
- static final String SIMPLE_SYNTAX = "Values and functions go inside ${...}: ${body}, ${header.name},"
- + " ${exchangeProperty.name}, ${variable.name}, ${random(1,10)},"
- + " ${date:now:yyyy-MM-dd}. Operators go BETWEEN placeholders, with spaces,"
- + " never inside one: ${header.foo} == 'bar', ${header.user} ?: 'Guest',"
- + " ${header.n} > 5 && ${body} != null, ${header.a} == 'x' ? 'yes' : 'no'."
- + " Text literals are in single quotes; text outside ${...} is kept as is:"
- + " Hello ${header.name}. Nesting works: ${header.${header.key}}.";
-
- private String buildLanguageDocJson(
- LanguageModel model, String filter, boolean includeOptions, String doc, List<String> docPages,
- boolean docPageOnly) {
- JsonObject result = new JsonObject();
- result.put("kind", "language");
- result.put("name", model.getName());
- result.put("title", model.getTitle());
- result.put("description", model.getDescription());
- if (model.getLabel() != null) {
- result.put("label", model.getLabel());
- }
- result.put("groupId", model.getGroupId());
- result.put("artifactId", model.getArtifactId());
- addCommonModelFields(result, model);
-
- // a requested doc page is the answer; the options, functions and operators would only add tokens around it
- if (includeOptions && !docPageOnly) {
- JsonArray options = new JsonArray();
- if (model.getOptions() != null) {
- for (BaseOptionModel opt : model.getOptions()) {
- if (matchesOptionFilter(opt, filter)) {
- options.add(optionToJson(opt, null));
- }
- }
- }
- result.put("options", options);
- result.put("matchedOptions", options.size());
- }
- if (!docPageOnly) {
- addLanguageFunctions(result, model, filter);
- }
- if ("simple".equals(model.getName()) || "csimple".equals(model.getName())) {
- result.put("syntax", SIMPLE_SYNTAX);
- }
- if (!docPages.isEmpty()) {
- result.put("docPages", new JsonArray(docPages));
- result.put("docPagesHint", "docPage=<name> returns that documentation page as text");
- }
- if (doc != null) {
- result.put("doc", doc);
- }
- return Jsoner.serialize(result);
- }
-
- /**
- * The functions and operators of a language that has them (simple): without a filter their count and names by
- * group, which answers "what is there" in a few hundred tokens; with a filter the matching ones in full, with
- * parameters and examples, the way the options are filtered.
- */
- private static void addLanguageFunctions(JsonObject result, LanguageModel model, String filter) {
- List<LanguageModel.LanguageFunctionModel> functions = model.getFunctions();
- if (functions != null && !functions.isEmpty()) {
- result.put("functionCount", functions.size());
- if (filter != null) {
- JsonArray arr = new JsonArray();
- for (LanguageModel.LanguageFunctionModel fn : functions) {
- if (matchesOptionFilter(fn, filter)
- || (fn.getDisplayName() != null && fn.getDisplayName().toLowerCase().contains(filter))) {
- arr.add(functionToJson(fn));
- }
- }
- result.put("functions", arr);
- result.put("matchedFunctions", arr.size());
- } else {
- Map<String, JsonArray> groups = new TreeMap<>();
- for (LanguageModel.LanguageFunctionModel fn : functions) {
- String group = fn.getGroup() != null ? fn.getGroup() : "other";
- groups.computeIfAbsent(group, g -> new JsonArray()).add(fn.getName());
- }
- result.put("functionGroups", new JsonObject(groups));
- result.put("functionsHint", "optionsFilter with a function name, a group above or a word from its"
- + " description returns the matching functions with their parameters"
- + " and examples");
- }
- }
- List<LanguageModel.LanguageOperatorModel> operators = model.getOperators();
- if (operators != null && !operators.isEmpty()) {
- result.put("operatorCount", operators.size());
- if (filter != null) {
- JsonArray arr = new JsonArray();
- for (LanguageModel.LanguageOperatorModel op : operators) {
- if (matchesOptionFilter(op, filter)
- || (op.getOperatorKind() != null && op.getOperatorKind().toLowerCase().contains(filter))) {
- arr.add(operatorToJson(op));
- }
- }
- result.put("operators", arr);
- result.put("matchedOperators", arr.size());
- } else {
- JsonArray syntaxes = new JsonArray();
- for (LanguageModel.LanguageOperatorModel op : operators) {
- syntaxes.add(op.getOperatorSyntax() != null ? op.getOperatorSyntax() : op.getName());
- }
- result.put("operatorSyntax", syntaxes);
- }
- }
- }
-
- private static JsonObject functionToJson(LanguageModel.LanguageFunctionModel fn) {
- JsonObject o = new JsonObject();
- o.put("name", fn.getName());
- if (fn.getDisplayName() != null) {
- o.put("displayName", fn.getDisplayName());
- }
- if (fn.getGroup() != null) {
- o.put("group", fn.getGroup());
- }
- if (fn.getJavaType() != null) {
- o.put("javaType", fn.getJavaType());
- }
- if (fn.getDescription() != null) {
- o.put("description", fn.getDescription());
- }
- if (fn.getParams() != null && !fn.getParams().isEmpty()) {
- JsonArray params = new JsonArray();
- for (LanguageModel.FunctionParamModel param : fn.getParams()) {
- JsonObject p = new JsonObject();
- p.put("name", param.getName());
- if (param.getJavaType() != null) {
- p.put("javaType", param.getJavaType());
- }
- p.put("required", param.isRequired());
- if (param.getDescription() != null) {
- p.put("description", param.getDescription());
- }
- params.add(p);
- }
- o.put("params", params);
- }
- if (fn.getExamples() != null && !fn.getExamples().isEmpty()) {
- o.put("examples", new JsonArray(fn.getExamples()));
- }
- if (fn.isOgnl()) {
- o.put("ognl", true);
- }
- if (fn.isDeprecated()) {
- o.put("deprecated", true);
- }
- return o;
- }
-
- private static JsonObject operatorToJson(LanguageModel.LanguageOperatorModel op) {
- JsonObject o = new JsonObject();
- o.put("name", op.getName());
- if (op.getDisplayName() != null) {
- o.put("displayName", op.getDisplayName());
- }
- if (op.getOperatorKind() != null) {
- o.put("kind", op.getOperatorKind());
- }
- if (op.getOperatorSyntax() != null) {
- o.put("syntax", op.getOperatorSyntax());
- }
- if (op.getDescription() != null) {
- o.put("description", op.getDescription());
- }
- if (op.getExamples() != null && !op.getExamples().isEmpty()) {
- o.put("examples", new JsonArray(op.getExamples()));
- }
- return o;
- }
-
- private String buildEipDocJson(EipModel model, String filter, boolean includeOptions, String doc) {
- JsonObject result = new JsonObject();
- result.put("kind", "eip");
- result.put("name", model.getName());
- result.put("title", model.getTitle());
- result.put("description", model.getDescription());
- if (model.getLabel() != null) {
- result.put("label", model.getLabel());
- }
- result.put("input", model.isInput());
- result.put("output", model.isOutput());
- addCommonModelFields(result, model);
-
- if (includeOptions) {
- JsonArray options = new JsonArray();
- if (model.getOptions() != null) {
- for (BaseOptionModel opt : model.getOptions()) {
- if (matchesOptionFilter(opt, filter)) {
- options.add(optionToJson(opt, null));
- }
- }
- }
- result.put("options", options);
- result.put("matchedOptions", options.size());
- }
- if (doc != null) {
- result.put("doc", doc);
- }
- return Jsoner.serialize(result);
- }
-
- private static boolean matchesOptionFilter(BaseOptionModel opt, String filter) {
- if (filter == null) {
- return true;
- }
- return (opt.getName() != null && opt.getName().toLowerCase().contains(filter))
- || (opt.getDescription() != null && opt.getDescription().toLowerCase().contains(filter))
- || (opt.getGroup() != null && opt.getGroup().toLowerCase().contains(filter))
- || (opt.getLabel() != null && opt.getLabel().toLowerCase().contains(filter));
- }
-
- private static JsonObject optionToJson(BaseOptionModel opt, String scope) {
- JsonObject o = new JsonObject();
- o.put("name", opt.getName());
- o.put("description", opt.getDescription());
- o.put("type", opt.getType());
- o.put("required", opt.isRequired());
- if ("path".equals(opt.getKind()) || "parameter".equals(opt.getKind())) {
- // an endpoint option is either part of the URI path or a query parameter; a model must not mix them up
- o.put("kind", opt.getKind());
- }
- if (opt.getDefaultValue() != null) {
- o.put("defaultValue", opt.getDefaultValue().toString());
- }
- if (opt.getGroup() != null) {
- o.put("group", opt.getGroup());
- }
- if (scope != null) {
- o.put("scope", scope);
- }
- if (opt.isDeprecated()) {
- o.put("deprecated", true);
- }
- if (opt.isSecret()) {
- o.put("secret", true);
- }
- if (opt.getEnums() != null && !opt.getEnums().isEmpty()) {
- o.put("enumValues", toJsonArray(opt.getEnums()));
- }
- return o;
- }
-
private String callGetProcessorDetail(Map<String, Object> args) {
String routeId = args.get("routeId") instanceof String v ? v : "*";
boolean includeDocs = Boolean.TRUE.equals(args.get("includeDocs"));
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AcpPermissionPopupTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AcpPermissionPopupTest.java
index 887d228b3c86..cdc1d9f4652f 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AcpPermissionPopupTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AcpPermissionPopupTest.java
@@ -102,13 +102,13 @@ class AcpPermissionPopupTest {
@Test
void hintIsShownUnderTheKindWhenGiven() {
AcpPermissionPopup popup = new AcpPermissionPopup();
- popup.open(toolCall(), options(), "Esc rejects it so the agent uses tui_write_file");
+ popup.open(toolCall(), options(), "Esc rejects it so the agent uses camel_write_file");
Rect area = new Rect(0, 0, 100, 30);
Buffer buffer = Buffer.empty(area);
popup.render(Frame.forTesting(buffer), area);
String rendered = TuiTestHelper.bufferToString(buffer);
assertTrue(rendered.contains("kind: edit"));
- assertTrue(rendered.contains("Esc rejects it so the agent uses tui_write_file"));
+ assertTrue(rendered.contains("Esc rejects it so the agent uses camel_write_file"));
assertTrue(rendered.contains("file_path"), "the input still follows the hint");
assertTrue(rendered.contains("Allow once"));
}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelAcpTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelAcpTest.java
index 99d61ca3d43c..4902bf9cd52c 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelAcpTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelAcpTest.java
@@ -528,12 +528,12 @@ class AiPanelAcpTest {
@Test
void mutatingTuiToolOpensThePopupEvenByName() throws Exception {
AiPanel panel = acpPanel();
- askPermissionDuringPrompt(permissionParams("mcp__camel-tui__tui_control", "tui_control"));
+ askPermissionDuringPrompt(permissionParams("mcp__camel-tui__camel_control", "camel_control"));
ask(panel, "hi");
await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> assertTrue(panel.isPermissionPopupVisibleForTesting()));
panel.handleKeyEvent(KeyEvent.ofKey(KeyCode.ESCAPE, KeyModifiers.NONE));
awaitIdle(panel);
- assertTrue(hasEntry(panel, AiRole.SYSTEM, "(stopped: opt-reject)"), "tui_control is not read-only");
+ assertTrue(hasEntry(panel, AiRole.SYSTEM, "(stopped: opt-reject)"), "camel_control is not read-only");
}
@Test
@@ -566,7 +566,7 @@ class AiPanelAcpTest {
void writeFileIsAutoApprovedWhenTheTuiConfirmsTheWriteItself() throws Exception {
AiPanel panel = acpPanel();
assertTrue(panel.describeWriteModeForTesting().startsWith("confirm"));
- askPermissionDuringPrompt(permissionParams("mcp__camel-tui__tui_write_file", "tui_write_file"));
+ askPermissionDuringPrompt(permissionParams("mcp__camel-tui__camel_write_file", "camel_write_file"));
ask(panel, "hi");
awaitIdle(panel);
assertFalse(panel.isPermissionPopupVisibleForTesting());
@@ -579,7 +579,7 @@ class AiPanelAcpTest {
AiPanel panel = acpPanel();
ask(panel, "/write auto");
assertTrue(panel.describeWriteModeForTesting().startsWith("auto"));
- askPermissionDuringPrompt(permissionParams("mcp__camel-tui__tui_write_file", "tui_write_file"));
+ askPermissionDuringPrompt(permissionParams("mcp__camel-tui__camel_write_file", "camel_write_file"));
ask(panel, "hi");
await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> assertTrue(panel.isPermissionPopupVisibleForTesting()));
panel.handleKeyEvent(KeyEvent.ofKey(KeyCode.ESCAPE, KeyModifiers.NONE));
@@ -590,7 +590,7 @@ class AiPanelAcpTest {
@Test
void evalExpressionIsReadOnly() throws Exception {
AiPanel panel = acpPanel();
- askPermissionDuringPrompt(permissionParams("mcp__camel-tui__tui_eval_expression", "tui_eval_expression"));
+ askPermissionDuringPrompt(permissionParams("mcp__camel-tui__camel_eval_expression", "camel_eval_expression"));
ask(panel, "hi");
awaitIdle(panel);
assertFalse(panel.isPermissionPopupVisibleForTesting());
@@ -603,7 +603,7 @@ class AiPanelAcpTest {
ask(panel, "hi");
awaitIdle(panel);
String prompt = promptText(agent.received("session/prompt").get(0));
- assertTrue(prompt.contains("only with tui_write_file"), prompt);
+ assertTrue(prompt.contains("only with camel_write_file"), prompt);
assertTrue(prompt.contains("/write live"), prompt);
}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelHistoryCompactionTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelHistoryCompactionTest.java
index 9ae95529d22a..c9738a1f185a 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelHistoryCompactionTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelHistoryCompactionTest.java
@@ -37,7 +37,7 @@ class AiPanelHistoryCompactionTest {
List<LlmClient.Message> turn = new ArrayList<>();
turn.add(LlmClient.Message.user(question));
turn.add(LlmClient.Message.assistantWithToolCalls(null,
- List.of(new LlmClient.ToolCall("call-" + question, "tui_get_log", new JsonObject()))));
+ List.of(new LlmClient.ToolCall("call-" + question, "camel_get_log", new JsonObject()))));
turn.add(LlmClient.Message.toolResults(List.of(new LlmClient.ToolResult("call-" + question, toolResult))));
turn.add(LlmClient.Message.assistantWithToolCalls("answer to " + question, List.of()));
return turn;
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelPromptBudgetTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelPromptBudgetTest.java
index 758c8909795b..144d64a93e2b 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelPromptBudgetTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/AiPanelPromptBudgetTest.java
@@ -36,10 +36,14 @@ class AiPanelPromptBudgetTest {
// raised from 3500 when file editing (tui_write_file and its guidance) joined the core set for local models,
// and from 3800 when tui_catalog_doc gained the endpoint argument (validates a URI, the endpoint counterpart of
// tui_eval_expression for simple)
- static final int CORE_BUDGET_TOKENS = 3_900;
+ // and from 3900 when the authoring tools became the camel_* set shared with camel-jbang-mcp (CAMEL-24695):
+ // their schemas carry the directory and name arguments a server without a selection needs, and
+ // camel_error_diagnose joined the core set
+ static final int CORE_BUDGET_TOKENS = 4_300;
/** Measured ~6.9k tokens for 47 tools. */
// raised from 7500 with tui_write_file and tui_validate_source
- static final int FULL_BUDGET_TOKENS = 7_900;
+ // and from 7900 with the shared camel_* set (camel_catalog_find, camel_run and camel_error_diagnose added)
+ static final int FULL_BUDGET_TOKENS = 8_500;
record Prefix(String mode, int tools, long promptChars, long toolChars) {
@@ -115,7 +119,8 @@ class AiPanelPromptBudgetTest {
// the tool definitions already describe every tool; repeating them in prose doubles the cost
// 450 before the file editing guidance (two bullets) was added
- assertTrue(AiPanel.estimateTokens(prompt.length()) <= 530,
+ // 530 before the tools were split into camel_* and tui_* in the introduction
+ assertTrue(AiPanel.estimateTokens(prompt.length()) <= 545,
"system prompt grew to ~" + AiPanel.estimateTokens(prompt.length()) + " tokens");
assertTrue(!prompt.contains("- tui_get_table:"), "system prompt must not list the tools again");
}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/McpFacadeWriteFileTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/McpFacadeWriteFileTest.java
index 4a65ce9a7ba5..6e94fc252192 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/McpFacadeWriteFileTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/McpFacadeWriteFileTest.java
@@ -250,7 +250,7 @@ class McpFacadeWriteFileTest {
assertEquals(2, result.getInteger("pendingHunks"));
assertEquals("- route:\n id: typed\n", result.getString("content"));
assertTrue(result.getString("message").contains("why an id?"));
- assertTrue(result.getString("message").contains("call tui_write_file again"));
+ assertTrue(result.getString("message").contains("call camel_write_file again"));
assertEquals(0, bridge.asked, "no confirm dialog: the replay is parked in the editor");
assertEquals("- route: {}\n", Files.readString(dir.resolve("demo.camel.yaml"), StandardCharsets.UTF_8),
"nothing is written while the question is open");
@@ -312,6 +312,6 @@ class McpFacadeWriteFileTest {
assertNotNull(files);
assertEquals(dir.toString(), files.getString("directory"));
assertTrue(files.getBoolean("devMode"));
- assertTrue(files.getString("editing").contains("tui_write_file"));
+ assertTrue(files.getString("editing").contains("camel_write_file"));
}
}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistryCoreToolsTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistryCoreToolsTest.java
index ec79299aa682..26881083370f 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistryCoreToolsTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistryCoreToolsTest.java
@@ -72,8 +72,8 @@ class TuiToolRegistryCoreToolsTest {
assertTrue(TuiToolRegistry.READ_ONLY_TOOLS.containsAll(getters),
"a new getter must be classified deliberately: " + getters.stream()
.filter(name -> !TuiToolRegistry.READ_ONLY_TOOLS.contains(name)).toList());
- for (String mutating : List.of("tui_control", "tui_execute_sql", "tui_send_message", "tui_write_file",
- "tui_infra")) {
+ for (String mutating : List.of("camel_control", "tui_execute_sql", "tui_send_message", "camel_write_file",
+ "camel_run", "tui_infra")) {
assertFalse(TuiToolRegistry.READ_ONLY_TOOLS.contains(mutating), mutating + " changes something");
}
}
diff --git a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistryEvalExpressionTest.java b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistryEvalExpressionTest.java
index 3d2850730a6f..85496eba96b7 100644
--- a/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistryEvalExpressionTest.java
+++ b/dsl/camel-jbang/camel-jbang-plugin-tui/src/test/java/org/apache/camel/dsl/jbang/core/commands/tui/TuiToolRegistryEvalExpressionTest.java
@@ -21,45 +21,39 @@ import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.camel.util.json.JsonObject;
+import org.apache.camel.util.json.Jsoner;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
+/**
+ * The shared camel_eval_expression tool as the TUI exposes it (CAMEL-24695): with an integration selected the
+ * expression is evaluated inside it, without one locally, so a simple expression can be checked before it is written.
+ */
class TuiToolRegistryEvalExpressionTest {
@Test
- void predicatesAreRecognisedByTheirOperators() {
- assertTrue(McpFacade.looksLikePredicate("${body} > 200 && ${body} < 300"));
- assertTrue(McpFacade.looksLikePredicate("${header.type} in 'gold,silver'"));
- assertTrue(McpFacade.looksLikePredicate("${header.foo} == 'bar' || ${header.bar} != null"));
- assertTrue(McpFacade.looksLikePredicate("${header.title} contains 'Camel'"));
- assertFalse(McpFacade.looksLikePredicate("${random(1,10)}"));
- assertFalse(McpFacade.looksLikePredicate("${header.user} ?: 'Guest'"), "elvis gives a value");
- assertFalse(McpFacade.looksLikePredicate("${header.a} == 'x' ? 'yes' : 'no'"), "ternary gives a value");
- assertFalse(McpFacade.looksLikePredicate("Hello ${body}, price>100"), "operators need spaces around them");
- assertFalse(McpFacade.looksLikePredicate(null));
- }
-
- @Test
- void evalIsACoreToolAndNeedsAnExpressionAndASelectedIntegration() throws Exception {
- assertTrue(TuiToolRegistry.CORE_TOOLS.contains("tui_eval_expression"), "local models get it too");
+ void evalIsACoreToolAndFallsBackToALocalContextWithoutASelectedIntegration() throws Exception {
+ assertTrue(TuiToolRegistry.CORE_TOOLS.contains("camel_eval_expression"), "local models get it too");
+ assertTrue(TuiToolRegistry.READ_ONLY_TOOLS.contains("camel_eval_expression"));
assertTrue(new TuiToolRegistry(null).getToolDefinitions().stream()
- .anyMatch(def -> "tui_eval_expression".equals(def.name())));
-
+ .anyMatch(def -> "camel_eval_expression".equals(def.name())));
MonitorContext ctx = new MonitorContext(new AtomicReference<>(List.of()), new AtomicReference<>(List.of()));
McpFacade facade = new McpFacade(
ctx, new AtomicReference<>(List.of()), null, null, null, null, null, null, null, null, null, null,
null);
TuiToolRegistry registry = new TuiToolRegistry(facade);
-
assertEquals("Error: expression is required",
- registry.execute("tui_eval_expression", new JsonObject(Map.of("language", "simple"))));
- // nothing selected: the expression cannot be evaluated anywhere
- assertNull(facade.evalExpression("simple", "${body}", null));
- assertEquals("Error: no integration selected or PID unavailable",
- registry.execute("tui_eval_expression", new JsonObject(Map.of("expression", "${body}"))));
+ registry.execute("camel_eval_expression", new JsonObject(Map.of("language", "simple"))));
+ // nothing selected: the expression is evaluated in a scratch context instead
+ JsonObject result = (JsonObject) Jsoner.deserialize(
+ registry.execute("camel_eval_expression", new JsonObject(
+ Map.of("expression", "${body} == 'x'",
+ "body", "x"))));
+ assertEquals("ok", result.getString("status"));
+ assertEquals("true", result.getString("result"));
+ assertTrue(result.getBoolean("predicate"));
+ assertTrue(result.getString("evaluatedIn").contains("local"));
}
}
(camel) 02/02: CAMEL-24695: Address review feedback
Posted by da...@apache.org.
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
commit 10ac427f27ad685114afa423bce65de46f932c6c
Author: Claus Ibsen <cl...@gmail.com>
AuthorDate: Sat Sep 12 13:54:19 2026 +0200
CAMEL-24695: Address review feedback
Document the threading contract of ToolContext: one tool call at a time,
the Camel version is set before the catalog is asked for.
Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
Signed-off-by: Claus Ibsen <cl...@gmail.com>
---
.../java/org/apache/camel/dsl/jbang/core/commands/ai/ToolContext.java | 4 ++++
1 file changed, 4 insertions(+)
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 92bd550c6dd9..5b6fc19a108d 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
@@ -96,6 +96,10 @@ public class ToolContext {
/**
* The Camel version the catalog tools answer for: null for the version of the running CLI, otherwise the version of
* the integration being worked on (the TUI passes the selected integration's version), downloaded on demand.
+ * <p>
+ * Not synchronized with {@link #catalog()}: a context serves one tool call at a time (the MCP servers and the TUI
+ * build a fresh one per call, {@code camel ask} runs its calls one after the other), and the version is set before
+ * the catalog is first asked for, so a change of version simply drops the cached catalog for the next call.
*/
public String camelVersion() {
return camelVersion;