You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by "Croway (via GitHub)" <gi...@apache.org> on 2026/10/16 15:48:05 UTC
[PR] CAMEL-25642: camel-jbang-mcp - runtime tools wiring: receive in one call, routeId honoured, prompts name real tools, timeouts are errors [camel]
Croway opened a new pull request, #27958:
URL: https://github.com/apache/camel/pull/27958
Section A of [CAMEL-25642](https://issues.apache.org/jira/browse/CAMEL-25642): the runtime tools of camel-jbang-mcp that were wired to the wrong keys, tools or protocol. Sections B (migration and dependency data) and C (OpenAPI scaffold) are separate PRs.
### Changes
- **`camel_runtime_receive`** started a permanent consumer through the receive dev console, stole messages from the routes and answered only `{enabled, endpoints}`. It is now one call: enable the console for the endpoint, poll the `{pid}-receive.json` file the CLI connector appends to (the same file `camel receive` reads) for up to `timeoutSeconds` (default 10, at most 60), return what arrived, and disable the console in a `finally`. It is `destructiveHint=true`, refuses to run while `camel receive` is active on the process (disabling would stop that consumer too) and reports an endpoint nothing matches. `RuntimeService` gains `receiveFileSize` and `readReceivedMessages`.
- **`routeId` was ignored** by `camel_runtime_route_dump`, `route_structure`, `route_analysis` and the `routeFilter` of `ai_trace`: the registry sent the pattern as `id`, `LocalCliConnector` reads `filter` (as `CamelRouteDumpAction` sends it). Fixed in the registry; `get_eip_stats` and `detect_config_drift` send `filter=*`; `brief` is passed to route_structure (the connector forwards it). `limit` is not added: the connector does not forward it for these actions.
- **Prompts**: `camel_diagnose_route` and `camel_optimize_route` named tools that do not exist (`get_context`, `get_routes`, `get_top_processors`, ...). Rewritten with the MCP names (`camel_runtime_context`, `camel_runtime_top`, ...). `PromptDefinitionsTest#everyToolAPromptNamesExists` checks every backticked tool name of every prompt is a listed tool; the `@Tool` scan moved to a shared test helper `McpToolClasses`, used by `McpSecuredToolClassesTest` too.
- **`camel_runtime_ai_trace`**: `nameOrPid` is optional like the other runtime tools. Rebased on main after CAMEL-25398 (#27931), which already turns a `ToolExecutionException` of the registry queries into an error; this PR adds the timeout-text detection (`RuntimeHelper.TIMEOUT_PREFIX`, `RuntimeTools.failOnTimeout`) so every registry-backed runtime tool reports "Timeout waiting for response" as an error instead of a success answer.
- **Smaller**: `camel_runtime_http_request` passes the `timeoutSeconds` the registry declares; `camel_runtime_memory_leak` defaults to `single` (start returns at once, 60 s recording, matching the argument text), `dual` (about 90 s, blocking) is opt-in and documented, a `compare` command gives a trend without blocking, `duration` and `mode` are validated and the dual wait sleeps by the console's `remainingMs`; `camel_runtime_history` no longer claims history is "always captured" (it needs message history on and the tracer enabled or on standby, which the dev profile of `camel run` sets; the description names the keys for other setups).
- **Hints**: `send_message` is destructive in the registry too (it keeps `core(true)` from main); `route_control` stays destructive for all commands, with a comment (an MCP hint is per tool; stop and suspend take the consumer offline); new read-only `camel_runtime_trace_dump` so read-only clients can dump traces; the heap dump name is refused when it contains a path separator or `..` and the MCP tool delegates to the registry.
- **Docs**: tool rows in `camel-jbang-mcp.adoc`; upgrade guide 4.24 section "runtime tools that changed behaviour" (receive, memory_leak default, routeId filtering, timeouts as errors).
### Tests
- New `ToolRegistryRuntimeActionsTest` (camel-jbang-core, 5 tests, records the requests through a fake `ToolContext`) and `RuntimeToolsWiringTest` (camel-jbang-mcp, 10 tests, recording `RuntimeService` plus a temp-home test for reading the receive file); `RuntimeToolsTest` adapted to the http_request argument.
- After the rebase: `mvnd -P apache-snapshots test -pl dsl/camel-jbang/camel-jbang-core,dsl/camel-jbang/camel-jbang-mcp -Dtest='ToolRegistry*Test,RuntimeHelperTest,org.apache.camel.dsl.jbang.core.commands.mcp.**.*Test'`: camel-jbang-mcp 479 tests, 0 failures; the core tests pass.
- Not verified against a running integration: the receive flow follows the protocol of `ReceiveDevConsole`, `LocalCliConnector.doActionReceiveTask` and `FileCliConnectorTransport` as read from the code.
Not in this PR: `limit` for route_dump/route_structure (needs a camel-cli-connector change), `camel_runtime_trace_dump` in the TUI tool groups, the registry `summary` argument of `history`.
_Claude Code on behalf of Croway_
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@camel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] CAMEL-25642: camel-jbang-mcp - runtime tools wiring: receive in one call, routeId honoured, prompts name real tools, timeouts are errors [camel]
Posted by "Croway (via GitHub)" <gi...@apache.org>.
Croway commented on PR #27958:
URL: https://github.com/apache/camel/pull/27958#issuecomment-6233843459
Follow-ups are in f5e8ae9c6d94 (rebased on main again, the upgrade guide conflict kept both sides, hence the force push), and the title no longer says "timeouts are errors".
@allthingssecurity thanks, the lag is real and the fix follows your shape: the `total` of the receive status before enabling bounds this call's messages (`uid` above it), one call at a time per pid, and the status read after the stop gives the exact count. I went one step further than counting: the call waits (3 s at most) until the status shows the console disabled and the file holds the messages the count announces, so the messages taken between the dump it read and the stop are returned too, not only counted. On the timeout path that turns "received 0" into the real number. The wait is bounded, and the answer says when the process did not confirm the stop or had not written every message in time.
Both doc pages describe `received` as every message the consumer took and the one-call-at-a-time rule. Tests: camel-jbang-mcp test package 512, camel-jbang-core runtime tests, TUI `AiPanelPromptBudgetTest` (no change), all passing.
_Claude Code on behalf of Croway_
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@camel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] CAMEL-25642: camel-jbang-mcp - runtime tools wiring: receive in one call, routeId honoured, prompts name real tools [camel]
Posted by "Croway (via GitHub)" <gi...@apache.org>.
Croway commented on code in PR #27958:
URL: https://github.com/apache/camel/pull/27958#discussion_r4302737516
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeService.java:
##########
@@ -123,6 +132,68 @@ public String stopApplication(long pid) {
return RuntimeHelper.stopApplication(pid);
}
+ /**
+ * The size of the file the CLI connector appends the messages of the receive console to
+ * ({@code {pid}-receive.json}, read by {@code camel cmd receive} too), to read only what arrives after this point.
+ */
+ public long receiveFileSize(long pid) {
+ try {
+ Path file = receiveFile(pid);
+ return Files.exists(file) ? Files.size(file) : 0;
+ } catch (IOException e) {
+ return 0;
+ }
+ }
+
+ /**
+ * The messages the CLI connector appended to the receive file after the given offset: each complete line is a
+ * {@code {"messages": [...]}} dump of the receive console. Only what was appended after the offset is read, as the
+ * file is append-only and kept across sessions.
+ */
+ public List<JsonObject> readReceivedMessages(long pid, long offset) {
+ List<JsonObject> messages = new ArrayList<>();
+ Path file = receiveFile(pid);
+ try {
+ if (!Files.exists(file)) {
+ return messages;
+ }
+ String text;
+ try (SeekableByteChannel channel = Files.newByteChannel(file, StandardOpenOption.READ)) {
+ long size = channel.size();
+ // camel cmd receive --action=clear rewrites the file: read it from the start then
+ long from = offset <= size ? offset : 0;
+ ByteBuffer buffer = ByteBuffer.allocate(Math.toIntExact(size - from));
Review Comment:
Same point as your thread from yesterday on this line, answered there: `offset` is the size of the file at the start of the call (or 0 after a clear, which truncates the file), so `size - from` is what the connector appended during one call of at most 60 seconds and cannot reach 2 GB. Clamping to `Integer.MAX_VALUE` would allocate a 2 GB buffer and silently truncate the read, which is worse than a loud `ArithmeticException` in a case that cannot happen; kept as it is.
_Claude Code on behalf of Croway_
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@camel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] CAMEL-25642: camel-jbang-mcp - runtime tools wiring: receive in one call, routeId honoured, prompts name real tools, timeouts are errors [camel]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #27958:
URL: https://github.com/apache/camel/pull/27958#discussion_r4300252324
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeTools.java:
##########
@@ -662,50 +715,161 @@ private JsonObject doDualJfrRecording(long pid, String duration, String stacktra
});
}
+ /**
+ * Waits until the recording stopped by itself: sleeps for the time the console says is left, then checks again (a
+ * recording ends a little after its duration, as it is parsed).
+ */
private void waitForJfrRecordingComplete(long pid, int dur) {
long deadline = System.currentTimeMillis() + (dur + 30) * 1000L;
while (System.currentTimeMillis() < deadline) {
+ JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
+ root.put("command", "status");
+ });
+ if (status == null || !"recording".equals(status.getString("status"))) {
+ return;
+ }
+ long remaining = status.getLongOrDefault("remainingMs", 1000L);
+ long wait = Math.min(Math.max(remaining, 500L), Math.max(1L, deadline - System.currentTimeMillis()));
try {
- Thread.sleep(3000);
+ TimeUnit.MILLISECONDS.sleep(wait);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ToolCallException("Interrupted while waiting for recording", null);
}
- JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
- root.put("command", "status");
- });
- if (status != null && !"recording".equals(status.getString("status"))) {
- break;
- }
}
}
@Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
description = """
- Get the message history trace of the last completed exchange. \
- This is always captured (no need to enable tracing) and shows the single most recent exchange \
- with its route path, processors visited, headers, body, and timing.""")
+ Get the message history trace of the last completed exchange, with its route path, processors \
+ visited, headers, body, and timing. Recorded when message history is on and the tracer is \
+ enabled or on standby: the default of camel run (dev profile); otherwise set \
+ camel.main.message-history=true and camel.trace.standby=true.""")
public JsonObject camel_runtime_history(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid) {
return delegateToRegistry("get_history", nameOrPid, Map.of());
}
- @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = false, openWorldHint = false),
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = true, openWorldHint = false),
description = """
- Receive (poll) a message from a Camel endpoint in the running application. \
- This is the complement to camel_runtime_send — it consumes one message from the endpoint.""")
+ Receive (consume) a message from an endpoint of the running application, the complement of \
+ camel_runtime_send: starts a consumer on the endpoint, waits for a message, returns it and stops \
+ the consumer again. Receives one message by default; limit returns up to that many of the messages \
+ that arrived together, and the answer says how many more were taken and not returned. The consumer \
+ competes with the routes that consume the endpoint, so the messages it takes do not reach them (a \
+ queue or topic message is gone). To look at queued messages without taking them use \
+ camel_runtime_browse.""")
public JsonObject camel_runtime_receive(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid,
- @ToolArg(description = "Endpoint URI to receive from") String endpoint) {
+ @ToolArg(description = "Endpoint URI to receive from, or a pattern matching an endpoint the application "
+ + "sends to, e.g. seda:orders or kafka*") String endpoint,
+ @ToolArg(description = "How long to wait for a message in seconds (default 10, at most 60)",
+ required = false) Integer timeoutSeconds,
+ @ToolArg(description = "How many of the messages that arrived together to return (default 1, at least 1)",
+ required = false) Integer limit) {
if (endpoint == null || endpoint.isBlank()) {
throw new ToolCallException("endpoint is required", null);
}
- // receive is MCP-only (no ToolRegistry equivalent) — call RuntimeService directly
+ if (limit != null && limit < 1) {
+ throw new ToolCallException("limit must be at least 1: " + limit, null);
+ }
+ int timeout = timeoutSeconds == null || timeoutSeconds <= 0
+ ? RECEIVE_DEFAULT_TIMEOUT : Math.min(timeoutSeconds, RECEIVE_MAX_TIMEOUT);
RuntimeService.ProcessInfo p = runtimeService.findSingleProcess(nameOrPid);
- return runtimeService.executeAction(p.pid(), "receive", root -> {
+ return receive(p.pid(), endpoint, timeout * 1000L, limit != null ? limit : 1);
+ }
+
+ /**
+ * Enables the receive console of the process for the endpoint, waits for the messages the CLI connector writes to
+ * the receive file, and disables it again whatever happens.
+ */
+ JsonObject receive(long pid, String endpoint, long timeoutMs, int limit) {
+ JsonObject state = runtimeService.readStatusSection(pid, "receive");
+ Collection<?> active = state.getCollection("endpoints");
+ if (Boolean.TRUE.equals(state.getBoolean("enabled")) && active != null && !active.isEmpty()) {
+ // disabling would stop those consumers too
+ throw new ToolCallException(
+ "The process is already receiving from " + active
+ + " (camel cmd receive); stop that first with: camel cmd receive --action=stop",
+ null);
+ }
+ long offset = runtimeService.receiveFileSize(pid);
+ JsonObject started = runtimeService.executeAction(pid, "receive", root -> {
root.put("enabled", "true");
root.put("endpoint", endpoint);
});
+ JsonObject answer;
+ try {
+ answer = awaitMessages(pid, endpoint, started, offset, timeoutMs, limit);
+ } catch (RuntimeException e) {
+ try {
+ stopReceiving(pid);
+ } catch (RuntimeException stop) {
+ throw new ToolCallException(
+ e.getMessage() + ". The consumer could not be stopped (" + stop.getMessage()
+ + "): stop it with: camel cmd receive --action=stop",
+ e);
Review Comment:
💡 **Robustness (low):** `e.getMessage()` and `stop.getMessage()` can both return `null` (e.g. when the exception is constructed without a message, or is a `NullPointerException`). Java string concatenation coerces `null` to the literal string `"null"`, producing a confusing message like `"null. The consumer could not be stopped (null): stop it with: camel cmd receive --action=stop"`.
Consider:
```suggestion
throw new ToolCallException(
e + ". The consumer could not be stopped (" + stop
+ "): stop it with: camel cmd receive --action=stop",
e);
```
`Throwable.toString()` always returns a non-null string (e.g. `java.lang.RuntimeException: message` or just `java.lang.NullPointerException`), giving more context than `getMessage()` alone.
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeService.java:
##########
@@ -123,6 +132,68 @@ public String stopApplication(long pid) {
return RuntimeHelper.stopApplication(pid);
}
+ /**
+ * The size of the file the CLI connector appends the messages of the receive console to
+ * ({@code {pid}-receive.json}, read by {@code camel cmd receive} too), to read only what arrives after this point.
+ */
+ public long receiveFileSize(long pid) {
+ try {
+ Path file = receiveFile(pid);
+ return Files.exists(file) ? Files.size(file) : 0;
+ } catch (IOException e) {
+ return 0;
+ }
+ }
+
+ /**
+ * The messages the CLI connector appended to the receive file after the given offset: each complete line is a
+ * {@code {"messages": [...]}} dump of the receive console. Only what was appended after the offset is read, as the
+ * file is append-only and kept across sessions.
+ */
+ public List<JsonObject> readReceivedMessages(long pid, long offset) {
+ List<JsonObject> messages = new ArrayList<>();
+ Path file = receiveFile(pid);
+ try {
+ if (!Files.exists(file)) {
+ return messages;
+ }
+ String text;
+ try (SeekableByteChannel channel = Files.newByteChannel(file, StandardOpenOption.READ)) {
+ long size = channel.size();
+ // camel cmd receive --action=clear rewrites the file: read it from the start then
+ long from = offset <= size ? offset : 0;
+ ByteBuffer buffer = ByteBuffer.allocate(Math.toIntExact(size - from));
Review Comment:
⚠️ **Bug (medium):** `Math.toIntExact(size - from)` throws `ArithmeticException` (extends `RuntimeException`) on overflow — not `IOException`. The `catch (IOException e)` block below (line 187) won't catch it. If the receive file ever grows beyond ~2 GB, this exception escapes unhandled.
The comment says `// not readable yet: the caller polls again`, implying any failure here should be swallowed. Add a guard:
```suggestion
if (size - from > Integer.MAX_VALUE) {
return messages; // file too large to read in one buffer; caller polls again
}
ByteBuffer buffer = ByteBuffer.allocate((int) (size - from));
```
Or, if you prefer keeping `Math.toIntExact`, wrap it:
```java
} catch (IOException | ArithmeticException e) {
// not readable yet: the caller polls again
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@camel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] CAMEL-25642: camel-jbang-mcp - runtime tools wiring: receive in one call, routeId honoured, prompts name real tools, timeouts are errors [camel]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #27958:
URL: https://github.com/apache/camel/pull/27958#issuecomment-6220137567
<!-- ci-tested-modules -->
:test_tube: **CI tested the following changed modules:**
- `docs`
- `dsl/camel-jbang/camel-jbang-core`
- `dsl/camel-jbang/camel-jbang-mcp`
:repeat: **1 test passed only after a retry on JDK 25** (1 retried attempt)
<details><summary>Recovered flaky tests on JDK 25 (1)</summary>
| Module | Test | Failed attempts | First failure |
| --- | --- | --- | --- |
| `dsl/camel-jbang/camel-jbang-core` | `ExpressionEvaluatorTest.evaluatesLocallyWithoutARunningIntegration` | 1 | expected: <true> but was: <false> |
> :information_source: These tests did **not** fail the build. Surefire retried them and they passed.
> Retries are enabled project-wide by `surefire.rerunFailingTestsCount` in `parent/pom.xml`.
</details>
---
<details><summary>:microscope: Scalpel shadow comparison — Scalpel: 5 of 706 tested, 8 compile-only — current: 5 all tested</summary>
[Maveniverse Scalpel](https://github.com/maveniverse/scalpel) detected **5 affected modules** (current approach: 5).
**Skip-tests mode would test 5 modules** (3 direct + 4 downstream), **skip tests for 8** (generated code, meta-modules)
<details><summary>Modules Scalpel would test (5)</summary>
- `camel-jbang-mcp` ← dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/AiTraceTools.java, dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/PromptDefinitions.java, dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeService.java, dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeTools.java, dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/McpSecuredToolClassesTest.java, dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/McpToolClasses.java, dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/PromptDefinitionsTest.java, dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeToolsTest.java, dsl/camel-jbang/camel-jbang-mcp/src/test/java/org/apache
/camel/dsl/jbang/core/commands/mcp/RuntimeToolsWiringTest.java
- `camel-jbang-plugin-mcp` ← downstream of org.apache.camel:camel-jbang-core
- `camel-jbang-plugin-tui` ← downstream of org.apache.camel:camel-jbang-core
- `camel-jbang-plugin-validate` ← downstream of org.apache.camel:camel-jbang-core
- `camel-launcher-container` ← downstream of org.apache.camel:camel-launcher
</details>
<details><summary>Modules with tests skipped (8)</summary>
- `camel-jbang-it`
- `camel-jbang-main`
- `camel-jbang-plugin-edit`
- `camel-jbang-plugin-generate`
- `camel-jbang-plugin-kubernetes`
- `camel-jbang-plugin-test`
- `camel-launcher`
- `coverage`
</details>
> :information_source: Shadow mode — Scalpel observes but does not affect test execution. [Learn more](https://github.com/maveniverse/scalpel)
</details>
:warning: **Some tests are disabled on GitHub Actions** (`@DisabledIfSystemProperty(named = "ci.env.name")`) and require manual verification:
- `dsl/camel-jbang/camel-jbang-core`: 2 test(s) disabled on GitHub Actions
- `dsl/camel-jbang/camel-jbang-mcp`: 2 test(s) disabled on GitHub Actions
:bulb: **Manual integration tests recommended:**
> You modified `dsl/camel-jbang/camel-jbang-core`. The related integration tests in `dsl/camel-jbang/camel-jbang-it` are excluded from CI. Consider running them manually:
> ```
> mvn verify -f dsl/camel-jbang/camel-jbang-it -Djbang-it-test
> ```
<details><summary>All tested modules (15 modules, 3m 30s total)</summary>
**Total reactor time:** 3m 30s
| Module | Duration | Status |
| --- | --- | --- |
| Camel :: Launcher | 53.4s | SUCCESS |
| Camel :: JBang :: MCP | 44.8s | SUCCESS |
| Camel :: JBang :: Plugin :: Validate | 40.4s | SUCCESS |
| Camel :: Docs | 21.3s | SUCCESS |
| Camel :: JBang :: Plugin :: Testing | 19.7s | SUCCESS |
| Camel :: JBang :: Plugin :: Kubernetes | 18.1s | SUCCESS |
| Camel :: JBang :: Plugin :: MCP | 3.0s | SUCCESS |
| Camel :: JBang :: Plugin :: Edit | 2.2s | SUCCESS |
| Camel :: Coverage | 1.9s | SUCCESS |
| Camel :: JBang :: Plugin :: Generate | 1.5s | SUCCESS |
| Camel :: JBang :: Integration tests | 1.3s | SUCCESS |
| Camel :: JBang :: Main | 1.2s | SUCCESS |
| Camel :: Launcher :: Container | 0.8s | SUCCESS |
| Camel :: JBang :: Core | n/a | |
| Camel :: JBang :: Plugin :: TUI | n/a | |
**Top 20 slowest modules:**
- `Camel :: Launcher` (53.4s)
- `Camel :: JBang :: MCP` (44.8s)
- `Camel :: JBang :: Plugin :: Validate` (40.4s)
- `Camel :: Docs` (21.3s)
- `Camel :: JBang :: Plugin :: Testing` (19.7s)
- `Camel :: JBang :: Plugin :: Kubernetes` (18.1s)
- `Camel :: JBang :: Plugin :: MCP` (3.0s)
- `Camel :: JBang :: Plugin :: Edit` (2.2s)
- `Camel :: Coverage` (1.9s)
- `Camel :: JBang :: Plugin :: Generate` (1.5s)
- `Camel :: JBang :: Integration tests` (1.3s)
- `Camel :: JBang :: Main` (1.2s)
- `Camel :: Launcher :: Container` (0.8s)
</details>
---
:gear: [View full build and test results](https://github.com/apache/camel/actions/runs/38926860247)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@camel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] CAMEL-25642: camel-jbang-mcp - runtime tools wiring: receive in one call, routeId honoured, prompts name real tools, timeouts are errors [camel]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #27958:
URL: https://github.com/apache/camel/pull/27958#issuecomment-6219232620
:star2: Thank you for your contribution to the Apache Camel project! :star2:
:robot: CI automation will test this PR automatically.
:camel: Apache Camel Committers, please review the following items:
* First-time contributors **require MANUAL approval** for the GitHub Actions to run
* You can use the command `/component-test (camel-)component-name1 (camel-)component-name2..` to request a test from the test bot although they are normally detected and executed by CI.
* You can label PRs using `skip-tests` and `test-dependents` to fine-tune the checks executed by this PR.
* Build and test logs are available in the summary page. **Only** [Apache Camel committers](https://camel.apache.org/community/team/#committers) have access to the summary.
:warning: Be careful when sharing logs. Review their contents before sharing them publicly.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@camel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] CAMEL-25642: camel-jbang-mcp - runtime tools wiring: receive in one call, routeId honoured, prompts name real tools, timeouts are errors [camel]
Posted by "davsclaus (via GitHub)" <gi...@apache.org>.
davsclaus commented on code in PR #27958:
URL: https://github.com/apache/camel/pull/27958#discussion_r4301786607
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeTools.java:
##########
@@ -662,50 +715,161 @@ private JsonObject doDualJfrRecording(long pid, String duration, String stacktra
});
}
+ /**
+ * Waits until the recording stopped by itself: sleeps for the time the console says is left, then checks again (a
+ * recording ends a little after its duration, as it is parsed).
+ */
private void waitForJfrRecordingComplete(long pid, int dur) {
long deadline = System.currentTimeMillis() + (dur + 30) * 1000L;
while (System.currentTimeMillis() < deadline) {
+ JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
+ root.put("command", "status");
+ });
+ if (status == null || !"recording".equals(status.getString("status"))) {
+ return;
+ }
+ long remaining = status.getLongOrDefault("remainingMs", 1000L);
+ long wait = Math.min(Math.max(remaining, 500L), Math.max(1L, deadline - System.currentTimeMillis()));
try {
- Thread.sleep(3000);
+ TimeUnit.MILLISECONDS.sleep(wait);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ToolCallException("Interrupted while waiting for recording", null);
}
- JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
- root.put("command", "status");
- });
- if (status != null && !"recording".equals(status.getString("status"))) {
- break;
- }
}
}
@Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
description = """
- Get the message history trace of the last completed exchange. \
- This is always captured (no need to enable tracing) and shows the single most recent exchange \
- with its route path, processors visited, headers, body, and timing.""")
+ Get the message history trace of the last completed exchange, with its route path, processors \
+ visited, headers, body, and timing. Recorded when message history is on and the tracer is \
+ enabled or on standby: the default of camel run (dev profile); otherwise set \
+ camel.main.message-history=true and camel.trace.standby=true.""")
public JsonObject camel_runtime_history(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid) {
return delegateToRegistry("get_history", nameOrPid, Map.of());
}
- @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = false, openWorldHint = false),
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = true, openWorldHint = false),
description = """
- Receive (poll) a message from a Camel endpoint in the running application. \
- This is the complement to camel_runtime_send — it consumes one message from the endpoint.""")
+ Receive (consume) a message from an endpoint of the running application, the complement of \
+ camel_runtime_send: starts a consumer on the endpoint, waits for a message, returns it and stops \
+ the consumer again. Receives one message by default; limit returns up to that many of the messages \
+ that arrived together, and the answer says how many more were taken and not returned. The consumer \
+ competes with the routes that consume the endpoint, so the messages it takes do not reach them (a \
+ queue or topic message is gone). To look at queued messages without taking them use \
+ camel_runtime_browse.""")
public JsonObject camel_runtime_receive(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid,
- @ToolArg(description = "Endpoint URI to receive from") String endpoint) {
+ @ToolArg(description = "Endpoint URI to receive from, or a pattern matching an endpoint the application "
+ + "sends to, e.g. seda:orders or kafka*") String endpoint,
+ @ToolArg(description = "How long to wait for a message in seconds (default 10, at most 60)",
+ required = false) Integer timeoutSeconds,
+ @ToolArg(description = "How many of the messages that arrived together to return (default 1, at least 1)",
+ required = false) Integer limit) {
if (endpoint == null || endpoint.isBlank()) {
throw new ToolCallException("endpoint is required", null);
}
- // receive is MCP-only (no ToolRegistry equivalent) — call RuntimeService directly
+ if (limit != null && limit < 1) {
+ throw new ToolCallException("limit must be at least 1: " + limit, null);
+ }
+ int timeout = timeoutSeconds == null || timeoutSeconds <= 0
+ ? RECEIVE_DEFAULT_TIMEOUT : Math.min(timeoutSeconds, RECEIVE_MAX_TIMEOUT);
RuntimeService.ProcessInfo p = runtimeService.findSingleProcess(nameOrPid);
- return runtimeService.executeAction(p.pid(), "receive", root -> {
+ return receive(p.pid(), endpoint, timeout * 1000L, limit != null ? limit : 1);
+ }
+
+ /**
+ * Enables the receive console of the process for the endpoint, waits for the messages the CLI connector writes to
+ * the receive file, and disables it again whatever happens.
+ */
+ JsonObject receive(long pid, String endpoint, long timeoutMs, int limit) {
+ JsonObject state = runtimeService.readStatusSection(pid, "receive");
+ Collection<?> active = state.getCollection("endpoints");
+ if (Boolean.TRUE.equals(state.getBoolean("enabled")) && active != null && !active.isEmpty()) {
+ // disabling would stop those consumers too
+ throw new ToolCallException(
+ "The process is already receiving from " + active
+ + " (camel cmd receive); stop that first with: camel cmd receive --action=stop",
+ null);
+ }
+ long offset = runtimeService.receiveFileSize(pid);
+ JsonObject started = runtimeService.executeAction(pid, "receive", root -> {
root.put("enabled", "true");
root.put("endpoint", endpoint);
});
+ JsonObject answer;
+ try {
+ answer = awaitMessages(pid, endpoint, started, offset, timeoutMs, limit);
+ } catch (RuntimeException e) {
+ try {
+ stopReceiving(pid);
+ } catch (RuntimeException stop) {
+ throw new ToolCallException(
+ e.getMessage() + ". The consumer could not be stopped (" + stop.getMessage()
+ + "): stop it with: camel cmd receive --action=stop",
+ e);
+ }
+ throw e;
+ }
+ try {
+ stopReceiving(pid);
+ } catch (RuntimeException e) {
+ // the messages are taken from the endpoint already: return them, and say the consumer may still run
+ answer.put("warning", "The consumer could not be stopped (" + e.getMessage()
+ + ") and may still take messages from the endpoint: stop it with: "
+ + "camel cmd receive --action=stop");
+ }
+ return answer;
+ }
+
+ private JsonObject awaitMessages(
+ long pid, String endpoint, JsonObject started, long offset, long timeoutMs, int limit) {
+ if (started.getString("error") != null) {
+ throw new ToolCallException("Cannot receive from " + endpoint + ": " + started.getString("error"), null);
+ }
+ String uri = started.getString("url");
+ if (uri == null) {
+ throw new ToolCallException(
+ "No endpoint matches " + endpoint
+ + " (a pattern matches the endpoints the application sends to; "
+ + "camel_runtime_endpoints lists them)",
+ null);
+ }
+ JsonObject answer = new JsonObject();
+ answer.put("endpoint", uri);
+ StopWatch watch = new StopWatch();
+ while (true) {
+ List<JsonObject> messages = runtimeService.readReceivedMessages(pid, offset);
Review Comment:
Following up on @allthingssecurity's review: this returns every message appended after `offset`, also the leftovers of an earlier call (taken after the dump it read, written on the next tick) and those of a parallel call on the same process. Reading the console's `total` from the `receive` status section before enabling, and keeping only messages with a `uid` above it, makes the answer this call's own:
```java
long startTotal = state.getLongOrDefault("total", 0L); // in receive(), before enabling
...
messages.removeIf(m -> m.getLongOrDefault("uid", 0L) <= startTotal);
```
The undercount (messages taken in the last tick before the stop) needs the status read after the stop has been applied; if that is too much for this PR, the note at line 852 ("taken from the endpoint all the same") could say that more messages than counted may have been taken, so the agent does not take `received` as the exact number.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@camel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] CAMEL-25642: camel-jbang-mcp - runtime tools wiring: receive in one call, routeId honoured, prompts name real tools, timeouts are errors [camel]
Posted by "Croway (via GitHub)" <gi...@apache.org>.
Croway commented on PR #27958:
URL: https://github.com/apache/camel/pull/27958#issuecomment-6226586675
Review follow-ups are in 6676883e9f13, one commit on top of the three existing ones, and the branch is rebased on main (hence the force push). Rebase notes: `ToolRegistry` keeps main's `json(String)` helper from #27982 next to this branch's `routeFilter` and `isPlainFileName`, and main's new `RuntimeToolsTest` in camel-jbang-core asserted the `id` key for route-dump and route-structure, which this branch changes to `filter` on purpose, so those three assertions now read `filter`.
- `camel cmd receive` everywhere; `camel.trace.standby` in the history hint and on the MCP page.
- `camel_runtime_receive` takes `limit` (default 1): the first `limit` messages of the poll are returned and the rest are counted as `notReturned`.
- The timeout-text check and `RuntimeHelper.TIMEOUT_PREFIX` are removed, as it could not trigger since #27931; the description and the upgrade guide no longer present it as a change.
- The receive file is read from the offset; a failed stop of the receive console no longer loses the answer and names the stop command.
On the TUI note: agreed, the AI panel only reads `isReadOnly()` and `isCore()`, so the destructive flag on `send_message` changes nothing there; that is the MCP hint only.
Tests: whole camel-jbang-mcp module (485), camel-jbang-core `RuntimeToolsTest` and `ToolRegistryRuntimeActionsTest`, TUI `AiPanelPromptBudgetTest` (no budget change), all passing.
_Claude Code on behalf of Croway_
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@camel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] CAMEL-25642: camel-jbang-mcp - runtime tools wiring: receive in one call, routeId honoured, prompts name real tools [camel]
Posted by "Croway (via GitHub)" <gi...@apache.org>.
Croway merged PR #27958:
URL: https://github.com/apache/camel/pull/27958
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@camel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] CAMEL-25642: camel-jbang-mcp - runtime tools wiring: receive in one call, routeId honoured, prompts name real tools, timeouts are errors [camel]
Posted by "Croway (via GitHub)" <gi...@apache.org>.
Croway commented on code in PR #27958:
URL: https://github.com/apache/camel/pull/27958#discussion_r4302646062
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeService.java:
##########
@@ -123,6 +132,68 @@ public String stopApplication(long pid) {
return RuntimeHelper.stopApplication(pid);
}
+ /**
+ * The size of the file the CLI connector appends the messages of the receive console to
+ * ({@code {pid}-receive.json}, read by {@code camel cmd receive} too), to read only what arrives after this point.
+ */
+ public long receiveFileSize(long pid) {
+ try {
+ Path file = receiveFile(pid);
+ return Files.exists(file) ? Files.size(file) : 0;
+ } catch (IOException e) {
+ return 0;
+ }
+ }
+
+ /**
+ * The messages the CLI connector appended to the receive file after the given offset: each complete line is a
+ * {@code {"messages": [...]}} dump of the receive console. Only what was appended after the offset is read, as the
+ * file is append-only and kept across sessions.
+ */
+ public List<JsonObject> readReceivedMessages(long pid, long offset) {
+ List<JsonObject> messages = new ArrayList<>();
+ Path file = receiveFile(pid);
+ try {
+ if (!Files.exists(file)) {
+ return messages;
+ }
+ String text;
+ try (SeekableByteChannel channel = Files.newByteChannel(file, StandardOpenOption.READ)) {
+ long size = channel.size();
+ // camel cmd receive --action=clear rewrites the file: read it from the start then
+ long from = offset <= size ? offset : 0;
+ ByteBuffer buffer = ByteBuffer.allocate(Math.toIntExact(size - from));
Review Comment:
Kept as it is: `offset` is the size of the file at the start of the call (or 0 after a clear, which truncates the file), so `size - from` is what the connector appended during one call of at most 60 seconds, and it cannot reach 2 GB. If it ever did, a loud `ArithmeticException` is better than a poll loop that silently finds nothing until the timeout.
_Claude Code on behalf of Croway_
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeTools.java:
##########
@@ -662,50 +715,161 @@ private JsonObject doDualJfrRecording(long pid, String duration, String stacktra
});
}
+ /**
+ * Waits until the recording stopped by itself: sleeps for the time the console says is left, then checks again (a
+ * recording ends a little after its duration, as it is parsed).
+ */
private void waitForJfrRecordingComplete(long pid, int dur) {
long deadline = System.currentTimeMillis() + (dur + 30) * 1000L;
while (System.currentTimeMillis() < deadline) {
+ JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
+ root.put("command", "status");
+ });
+ if (status == null || !"recording".equals(status.getString("status"))) {
+ return;
+ }
+ long remaining = status.getLongOrDefault("remainingMs", 1000L);
+ long wait = Math.min(Math.max(remaining, 500L), Math.max(1L, deadline - System.currentTimeMillis()));
try {
- Thread.sleep(3000);
+ TimeUnit.MILLISECONDS.sleep(wait);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ToolCallException("Interrupted while waiting for recording", null);
}
- JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
- root.put("command", "status");
- });
- if (status != null && !"recording".equals(status.getString("status"))) {
- break;
- }
}
}
@Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
description = """
- Get the message history trace of the last completed exchange. \
- This is always captured (no need to enable tracing) and shows the single most recent exchange \
- with its route path, processors visited, headers, body, and timing.""")
+ Get the message history trace of the last completed exchange, with its route path, processors \
+ visited, headers, body, and timing. Recorded when message history is on and the tracer is \
+ enabled or on standby: the default of camel run (dev profile); otherwise set \
+ camel.main.message-history=true and camel.trace.standby=true.""")
public JsonObject camel_runtime_history(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid) {
return delegateToRegistry("get_history", nameOrPid, Map.of());
}
- @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = false, openWorldHint = false),
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = true, openWorldHint = false),
description = """
- Receive (poll) a message from a Camel endpoint in the running application. \
- This is the complement to camel_runtime_send — it consumes one message from the endpoint.""")
+ Receive (consume) a message from an endpoint of the running application, the complement of \
+ camel_runtime_send: starts a consumer on the endpoint, waits for a message, returns it and stops \
+ the consumer again. Receives one message by default; limit returns up to that many of the messages \
+ that arrived together, and the answer says how many more were taken and not returned. The consumer \
+ competes with the routes that consume the endpoint, so the messages it takes do not reach them (a \
+ queue or topic message is gone). To look at queued messages without taking them use \
+ camel_runtime_browse.""")
public JsonObject camel_runtime_receive(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid,
- @ToolArg(description = "Endpoint URI to receive from") String endpoint) {
+ @ToolArg(description = "Endpoint URI to receive from, or a pattern matching an endpoint the application "
+ + "sends to, e.g. seda:orders or kafka*") String endpoint,
+ @ToolArg(description = "How long to wait for a message in seconds (default 10, at most 60)",
+ required = false) Integer timeoutSeconds,
+ @ToolArg(description = "How many of the messages that arrived together to return (default 1, at least 1)",
+ required = false) Integer limit) {
if (endpoint == null || endpoint.isBlank()) {
throw new ToolCallException("endpoint is required", null);
}
- // receive is MCP-only (no ToolRegistry equivalent) — call RuntimeService directly
+ if (limit != null && limit < 1) {
+ throw new ToolCallException("limit must be at least 1: " + limit, null);
+ }
+ int timeout = timeoutSeconds == null || timeoutSeconds <= 0
+ ? RECEIVE_DEFAULT_TIMEOUT : Math.min(timeoutSeconds, RECEIVE_MAX_TIMEOUT);
RuntimeService.ProcessInfo p = runtimeService.findSingleProcess(nameOrPid);
- return runtimeService.executeAction(p.pid(), "receive", root -> {
+ return receive(p.pid(), endpoint, timeout * 1000L, limit != null ? limit : 1);
+ }
+
+ /**
+ * Enables the receive console of the process for the endpoint, waits for the messages the CLI connector writes to
+ * the receive file, and disables it again whatever happens.
+ */
+ JsonObject receive(long pid, String endpoint, long timeoutMs, int limit) {
+ JsonObject state = runtimeService.readStatusSection(pid, "receive");
+ Collection<?> active = state.getCollection("endpoints");
+ if (Boolean.TRUE.equals(state.getBoolean("enabled")) && active != null && !active.isEmpty()) {
+ // disabling would stop those consumers too
+ throw new ToolCallException(
+ "The process is already receiving from " + active
+ + " (camel cmd receive); stop that first with: camel cmd receive --action=stop",
+ null);
+ }
+ long offset = runtimeService.receiveFileSize(pid);
+ JsonObject started = runtimeService.executeAction(pid, "receive", root -> {
root.put("enabled", "true");
root.put("endpoint", endpoint);
});
+ JsonObject answer;
+ try {
+ answer = awaitMessages(pid, endpoint, started, offset, timeoutMs, limit);
+ } catch (RuntimeException e) {
+ try {
+ stopReceiving(pid);
+ } catch (RuntimeException stop) {
+ throw new ToolCallException(
+ e.getMessage() + ". The consumer could not be stopped (" + stop.getMessage()
+ + "): stop it with: camel cmd receive --action=stop",
+ e);
Review Comment:
Done in f5e8ae9c6d94: a `message(Throwable)` helper gives the message, or the exception name when there is none, in both places.
_Claude Code on behalf of Croway_
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeTools.java:
##########
@@ -662,50 +715,161 @@ private JsonObject doDualJfrRecording(long pid, String duration, String stacktra
});
}
+ /**
+ * Waits until the recording stopped by itself: sleeps for the time the console says is left, then checks again (a
+ * recording ends a little after its duration, as it is parsed).
+ */
private void waitForJfrRecordingComplete(long pid, int dur) {
long deadline = System.currentTimeMillis() + (dur + 30) * 1000L;
while (System.currentTimeMillis() < deadline) {
+ JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
+ root.put("command", "status");
+ });
+ if (status == null || !"recording".equals(status.getString("status"))) {
+ return;
+ }
+ long remaining = status.getLongOrDefault("remainingMs", 1000L);
+ long wait = Math.min(Math.max(remaining, 500L), Math.max(1L, deadline - System.currentTimeMillis()));
try {
- Thread.sleep(3000);
+ TimeUnit.MILLISECONDS.sleep(wait);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ToolCallException("Interrupted while waiting for recording", null);
}
- JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
- root.put("command", "status");
- });
- if (status != null && !"recording".equals(status.getString("status"))) {
- break;
- }
}
}
@Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
description = """
- Get the message history trace of the last completed exchange. \
- This is always captured (no need to enable tracing) and shows the single most recent exchange \
- with its route path, processors visited, headers, body, and timing.""")
+ Get the message history trace of the last completed exchange, with its route path, processors \
+ visited, headers, body, and timing. Recorded when message history is on and the tracer is \
+ enabled or on standby: the default of camel run (dev profile); otherwise set \
+ camel.main.message-history=true and camel.trace.standby=true.""")
public JsonObject camel_runtime_history(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid) {
return delegateToRegistry("get_history", nameOrPid, Map.of());
}
- @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = false, openWorldHint = false),
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = true, openWorldHint = false),
description = """
- Receive (poll) a message from a Camel endpoint in the running application. \
- This is the complement to camel_runtime_send — it consumes one message from the endpoint.""")
+ Receive (consume) a message from an endpoint of the running application, the complement of \
+ camel_runtime_send: starts a consumer on the endpoint, waits for a message, returns it and stops \
+ the consumer again. Receives one message by default; limit returns up to that many of the messages \
+ that arrived together, and the answer says how many more were taken and not returned. The consumer \
+ competes with the routes that consume the endpoint, so the messages it takes do not reach them (a \
+ queue or topic message is gone). To look at queued messages without taking them use \
+ camel_runtime_browse.""")
public JsonObject camel_runtime_receive(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid,
- @ToolArg(description = "Endpoint URI to receive from") String endpoint) {
+ @ToolArg(description = "Endpoint URI to receive from, or a pattern matching an endpoint the application "
+ + "sends to, e.g. seda:orders or kafka*") String endpoint,
+ @ToolArg(description = "How long to wait for a message in seconds (default 10, at most 60)",
+ required = false) Integer timeoutSeconds,
+ @ToolArg(description = "How many of the messages that arrived together to return (default 1, at least 1)",
+ required = false) Integer limit) {
if (endpoint == null || endpoint.isBlank()) {
throw new ToolCallException("endpoint is required", null);
}
- // receive is MCP-only (no ToolRegistry equivalent) — call RuntimeService directly
+ if (limit != null && limit < 1) {
+ throw new ToolCallException("limit must be at least 1: " + limit, null);
+ }
+ int timeout = timeoutSeconds == null || timeoutSeconds <= 0
+ ? RECEIVE_DEFAULT_TIMEOUT : Math.min(timeoutSeconds, RECEIVE_MAX_TIMEOUT);
RuntimeService.ProcessInfo p = runtimeService.findSingleProcess(nameOrPid);
- return runtimeService.executeAction(p.pid(), "receive", root -> {
+ return receive(p.pid(), endpoint, timeout * 1000L, limit != null ? limit : 1);
+ }
+
+ /**
+ * Enables the receive console of the process for the endpoint, waits for the messages the CLI connector writes to
+ * the receive file, and disables it again whatever happens.
+ */
+ JsonObject receive(long pid, String endpoint, long timeoutMs, int limit) {
+ JsonObject state = runtimeService.readStatusSection(pid, "receive");
+ Collection<?> active = state.getCollection("endpoints");
+ if (Boolean.TRUE.equals(state.getBoolean("enabled")) && active != null && !active.isEmpty()) {
+ // disabling would stop those consumers too
+ throw new ToolCallException(
+ "The process is already receiving from " + active
+ + " (camel cmd receive); stop that first with: camel cmd receive --action=stop",
+ null);
+ }
+ long offset = runtimeService.receiveFileSize(pid);
+ JsonObject started = runtimeService.executeAction(pid, "receive", root -> {
root.put("enabled", "true");
root.put("endpoint", endpoint);
});
+ JsonObject answer;
+ try {
+ answer = awaitMessages(pid, endpoint, started, offset, timeoutMs, limit);
+ } catch (RuntimeException e) {
+ try {
+ stopReceiving(pid);
+ } catch (RuntimeException stop) {
+ throw new ToolCallException(
+ e.getMessage() + ". The consumer could not be stopped (" + stop.getMessage()
+ + "): stop it with: camel cmd receive --action=stop",
+ e);
+ }
+ throw e;
+ }
+ try {
+ stopReceiving(pid);
+ } catch (RuntimeException e) {
+ // the messages are taken from the endpoint already: return them, and say the consumer may still run
+ answer.put("warning", "The consumer could not be stopped (" + e.getMessage()
+ + ") and may still take messages from the endpoint: stop it with: "
+ + "camel cmd receive --action=stop");
+ }
+ return answer;
+ }
+
+ private JsonObject awaitMessages(
+ long pid, String endpoint, JsonObject started, long offset, long timeoutMs, int limit) {
+ if (started.getString("error") != null) {
+ throw new ToolCallException("Cannot receive from " + endpoint + ": " + started.getString("error"), null);
+ }
+ String uri = started.getString("url");
+ if (uri == null) {
+ throw new ToolCallException(
+ "No endpoint matches " + endpoint
+ + " (a pattern matches the endpoints the application sends to; "
+ + "camel_runtime_endpoints lists them)",
+ null);
+ }
+ JsonObject answer = new JsonObject();
+ answer.put("endpoint", uri);
+ StopWatch watch = new StopWatch();
+ while (true) {
+ List<JsonObject> messages = runtimeService.readReceivedMessages(pid, offset);
Review Comment:
Done in f5e8ae9c6d94, with the status read after the stop too: `receive` reads `total` from the receive status before enabling and keeps only the messages with a `uid` above it; after the stop it waits (3 s at most, the connector applies the stop and writes the status in one tick and dumps the queue every second tick) until the status shows the console disabled, and the `total` then is the exact number this call took, so the messages dumped after the stop are returned as well (up to `limit`) and otherwise counted in `notReturned`. When the process does not confirm the stop or has not written every message in that time, the note says so. A `ReentrantLock` per pid runs one call at a time: a second call waits up to its own timeout, then fails with a message naming the first. Tests in `RuntimeToolsWiringTest` with a recording runtime whose status follows the actions (leftovers of an earlier session, messages written after the stop, unwritten and unconfirmed cases, parallel call).
_Claude Code on behalf of Croway_
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@camel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] CAMEL-25642: camel-jbang-mcp - runtime tools wiring: receive in one call, routeId honoured, prompts name real tools [camel]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #27958:
URL: https://github.com/apache/camel/pull/27958#discussion_r4302674231
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeService.java:
##########
@@ -123,6 +132,68 @@ public String stopApplication(long pid) {
return RuntimeHelper.stopApplication(pid);
}
+ /**
+ * The size of the file the CLI connector appends the messages of the receive console to
+ * ({@code {pid}-receive.json}, read by {@code camel cmd receive} too), to read only what arrives after this point.
+ */
+ public long receiveFileSize(long pid) {
+ try {
+ Path file = receiveFile(pid);
+ return Files.exists(file) ? Files.size(file) : 0;
+ } catch (IOException e) {
+ return 0;
+ }
+ }
+
+ /**
+ * The messages the CLI connector appended to the receive file after the given offset: each complete line is a
+ * {@code {"messages": [...]}} dump of the receive console. Only what was appended after the offset is read, as the
+ * file is append-only and kept across sessions.
+ */
+ public List<JsonObject> readReceivedMessages(long pid, long offset) {
+ List<JsonObject> messages = new ArrayList<>();
+ Path file = receiveFile(pid);
+ try {
+ if (!Files.exists(file)) {
+ return messages;
+ }
+ String text;
+ try (SeekableByteChannel channel = Files.newByteChannel(file, StandardOpenOption.READ)) {
+ long size = channel.size();
+ // camel cmd receive --action=clear rewrites the file: read it from the start then
+ long from = offset <= size ? offset : 0;
+ ByteBuffer buffer = ByteBuffer.allocate(Math.toIntExact(size - from));
Review Comment:
⚠️ **Bug: `Math.toIntExact` overflow uncaught by `IOException` handler**
`Math.toIntExact(size - from)` throws `ArithmeticException` (a `RuntimeException`) when `size - from > Integer.MAX_VALUE` — i.e. when the file is larger than ~2 GB. The enclosing `catch (IOException e)` block does not catch `RuntimeException`, so the exception would propagate uncaught to the caller instead of silently returning so the caller can poll again.
Suggested fix using `Math.min` to clamp the allocation size:
```suggestion
ByteBuffer buffer = ByteBuffer.allocate((int) Math.min(size - from, Integer.MAX_VALUE));
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@camel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] CAMEL-25642: camel-jbang-mcp - runtime tools wiring: receive in one call, routeId honoured, prompts name real tools, timeouts are errors [camel]
Posted by "davsclaus (via GitHub)" <gi...@apache.org>.
davsclaus commented on code in PR #27958:
URL: https://github.com/apache/camel/pull/27958#discussion_r4297379127
##########
docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc:
##########
@@ -1256,3 +1256,23 @@ The consumer now sets the `CamelMiloNodeId` header on every exchange, including
Stopping a consumer now deletes its monitored items. Previously they stayed on the server while another endpoint kept
the shared connection open, so a restarted consumer received each value twice. While the server is unreachable, the
stop waits until the client's next attempt to reconnect has failed.
+
+=== camel-jbang-mcp - runtime tools that changed behaviour
+
+Some runtime tools of the Camel MCP server now do what their description says, which changes what a client sees:
+
+* `camel_runtime_receive` receives a message in one call: it starts a consumer on the endpoint, waits up to
+ `timeoutSeconds` (default 10, at most 60) for a message, returns it and stops the consumer. Before, it started a
+ consumer that kept running, took the messages from the routes, and returned none of them. It is now marked
+ destructive, so the `read-write` access level (`camel.mcp.security.access-level`) no longer offers it, only
+ `admin` does. It refuses to run while
+ `camel receive` is receiving from the same process.
Review Comment:
Same as in `RuntimeTools`: the command is `camel cmd receive`.
```suggestion
`camel cmd receive` is receiving from the same process.
```
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeTools.java:
##########
@@ -662,50 +727,120 @@ private JsonObject doDualJfrRecording(long pid, String duration, String stacktra
});
}
+ /**
+ * Waits until the recording stopped by itself: sleeps for the time the console says is left, then checks again (a
+ * recording ends a little after its duration, as it is parsed).
+ */
private void waitForJfrRecordingComplete(long pid, int dur) {
long deadline = System.currentTimeMillis() + (dur + 30) * 1000L;
while (System.currentTimeMillis() < deadline) {
+ JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
+ root.put("command", "status");
+ });
+ if (status == null || !"recording".equals(status.getString("status"))) {
+ return;
+ }
+ long remaining = status.getLongOrDefault("remainingMs", 1000L);
+ long wait = Math.min(Math.max(remaining, 500L), Math.max(1L, deadline - System.currentTimeMillis()));
try {
- Thread.sleep(3000);
+ TimeUnit.MILLISECONDS.sleep(wait);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ToolCallException("Interrupted while waiting for recording", null);
}
- JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
- root.put("command", "status");
- });
- if (status != null && !"recording".equals(status.getString("status"))) {
- break;
- }
}
}
@Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
description = """
- Get the message history trace of the last completed exchange. \
- This is always captured (no need to enable tracing) and shows the single most recent exchange \
- with its route path, processors visited, headers, body, and timing.""")
+ Get the message history trace of the last completed exchange, with its route path, processors \
+ visited, headers, body, and timing. Recorded when message history is on and the tracer is \
+ enabled or on standby: the default of camel run (dev profile); otherwise set \
+ camel.main.message-history=true and camel.main.tracing-standby=true.""")
public JsonObject camel_runtime_history(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid) {
return delegateToRegistry("get_history", nameOrPid, Map.of());
}
- @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = false, openWorldHint = false),
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = true, openWorldHint = false),
description = """
- Receive (poll) a message from a Camel endpoint in the running application. \
- This is the complement to camel_runtime_send — it consumes one message from the endpoint.""")
+ Receive (consume) a message from an endpoint of the running application, the complement of \
+ camel_runtime_send: starts a consumer on the endpoint, waits for a message, returns it and stops \
+ the consumer again. The consumer competes with the routes that consume the endpoint, so the \
+ message it takes does not reach them (a queue or topic message is gone). \
+ To look at queued messages without taking them use camel_runtime_browse.""")
public JsonObject camel_runtime_receive(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid,
- @ToolArg(description = "Endpoint URI to receive from") String endpoint) {
+ @ToolArg(description = "Endpoint URI to receive from, or a pattern matching an endpoint the application "
+ + "sends to, e.g. seda:orders or kafka*") String endpoint,
+ @ToolArg(description = "How long to wait for a message in seconds (default 10, at most 60)",
+ required = false) Integer timeoutSeconds) {
if (endpoint == null || endpoint.isBlank()) {
throw new ToolCallException("endpoint is required", null);
}
- // receive is MCP-only (no ToolRegistry equivalent) — call RuntimeService directly
+ int timeout = timeoutSeconds == null || timeoutSeconds <= 0
+ ? RECEIVE_DEFAULT_TIMEOUT : Math.min(timeoutSeconds, RECEIVE_MAX_TIMEOUT);
RuntimeService.ProcessInfo p = runtimeService.findSingleProcess(nameOrPid);
- return runtimeService.executeAction(p.pid(), "receive", root -> {
+ return receive(p.pid(), endpoint, timeout * 1000L);
+ }
+
+ /**
+ * Enables the receive console of the process for the endpoint, waits for the messages the CLI connector writes to
+ * the receive file, and disables it again whatever happens.
+ */
+ JsonObject receive(long pid, String endpoint, long timeoutMs) {
+ JsonObject state = runtimeService.readStatusSection(pid, "receive");
+ Collection<?> active = state.getCollection("endpoints");
+ if (Boolean.TRUE.equals(state.getBoolean("enabled")) && active != null && !active.isEmpty()) {
+ // disabling would stop those consumers too
+ throw new ToolCallException(
+ "The process is already receiving from " + active
+ + " (camel receive); stop that first with: camel receive --action=stop",
Review Comment:
`receive` is a subcommand of `camel cmd` (`CamelJBangMain.java:179`), so `camel receive --action=stop` is not a command, and an agent runs this text as it is. The same name is in `camel-jbang-mcp.adoc` (line 1016), in the upgrade guide (line 1269) and in two comments of `RuntimeService` (lines 134 and 157).
```suggestion
+ " (camel cmd receive); stop that first with: camel cmd receive --action=stop",
```
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeTools.java:
##########
@@ -662,50 +727,120 @@ private JsonObject doDualJfrRecording(long pid, String duration, String stacktra
});
}
+ /**
+ * Waits until the recording stopped by itself: sleeps for the time the console says is left, then checks again (a
+ * recording ends a little after its duration, as it is parsed).
+ */
private void waitForJfrRecordingComplete(long pid, int dur) {
long deadline = System.currentTimeMillis() + (dur + 30) * 1000L;
while (System.currentTimeMillis() < deadline) {
+ JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
+ root.put("command", "status");
+ });
+ if (status == null || !"recording".equals(status.getString("status"))) {
+ return;
+ }
+ long remaining = status.getLongOrDefault("remainingMs", 1000L);
+ long wait = Math.min(Math.max(remaining, 500L), Math.max(1L, deadline - System.currentTimeMillis()));
try {
- Thread.sleep(3000);
+ TimeUnit.MILLISECONDS.sleep(wait);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ToolCallException("Interrupted while waiting for recording", null);
}
- JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
- root.put("command", "status");
- });
- if (status != null && !"recording".equals(status.getString("status"))) {
- break;
- }
}
}
@Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
description = """
- Get the message history trace of the last completed exchange. \
- This is always captured (no need to enable tracing) and shows the single most recent exchange \
- with its route path, processors visited, headers, body, and timing.""")
+ Get the message history trace of the last completed exchange, with its route path, processors \
+ visited, headers, body, and timing. Recorded when message history is on and the tracer is \
+ enabled or on standby: the default of camel run (dev profile); otherwise set \
+ camel.main.message-history=true and camel.main.tracing-standby=true.""")
Review Comment:
`camel.main.tracing-standby` puts the log `Tracer` on standby (`camelContext.setTracingStandby`). The history comes from the `BacklogTracer`: `MessageHistoryDevConsole` reads `getLatestMessageHistory()`, which `BacklogTracer.shouldTrace` records when it is enabled or on standby and message history is on. Its standby is `camel.trace.standby`, which is what the dev profile sets (`ProfileConfigurer.configureMain`: `tracerConfig().withStandby(true)`). With `tracing-standby` the history stays empty, and the agent has followed the tool's advice.
```suggestion
camel.main.message-history=true and camel.trace.standby=true.""")
```
##########
docs/user-manual/modules/ROOT/pages/camel-jbang-mcp.adoc:
##########
@@ -979,23 +987,33 @@ xref:camel-jbang-tui-local-models.adoc#_tool_groups_from_the_selected_integratio
| Tool | Description
| `camel_runtime_send`
-| Send a test message to a Camel endpoint in the running application.
+| Send a test message to a Camel endpoint in the running application. Marked destructive: the message runs through
+ the routes and whatever they call.
| `camel_runtime_trace`
| Enable, disable, or dump message tracing for the running Camel application.
+| `camel_runtime_trace_dump`
+| Dump the traced messages, the same as `camel_runtime_trace` with `action=dump`, as a read-only tool, so a client
+ at the `read-only` access level can read the traces.
+
| `camel_runtime_ai_trace`
| Trace the AI-specific exchange flow of a running application: token usage, model ids, guardrail outcomes,
completion reasons, streaming chunk counts and per-component latency for the AI components (Bedrock,
LangChain4j, Docling, Textract, OpenAI, KServe, DJL, TensorFlow Serving, HuggingFace). It combines the message
- history with the processor statistics, filtered to the AI steps.
+ history with the processor statistics, filtered to the AI steps. A process that does not answer is reported as
+ an error.
| `camel_runtime_browse`
| Browse messages in a Camel endpoint (e.g., messages queued in a SEDA endpoint).
| `camel_runtime_receive`
-| Receive (poll) a message from a Camel endpoint in the running application. Consumes one message
- from the endpoint.
+| Receive a message from an endpoint of the running application, the complement of `camel_runtime_send`, in one
+ call: it starts a consumer on the endpoint (an endpoint uri, or a pattern matching an endpoint the application
+ sends to), waits up to `timeoutSeconds` (default 10, at most 60) for a message, returns it and stops the consumer.
+ The consumer competes with the routes that consume the endpoint, so the message it takes does not reach them:
+ the tool is marked destructive. Use `camel_runtime_browse` to look at queued messages without taking them. It
+ refuses to run while `camel receive` is receiving from the same process.
Review Comment:
The command is `camel cmd receive`, as in the error message above.
```suggestion
refuses to run while `camel cmd receive` is receiving from the same process.
```
##########
docs/user-manual/modules/ROOT/pages/camel-jbang-mcp.adoc:
##########
@@ -846,16 +849,21 @@ process is running).
| `camel_runtime_heap_dump`
| Write a heap dump (`.hprof`) from a running integration for deep memory analysis with tools such as Eclipse MAT,
- VisualVM or jhat. The dump is written to the process working directory.
+ VisualVM or jhat. The dump is written to the process working directory; a `name` with a directory is refused.
| `camel_runtime_memory_leak`
| Diagnose memory leaks in a running Camel integration using Java Flight Recorder (JFR).
- Use command 'start' to begin recording, 'stop' to get results, 'status' to check state,
- and 'query' to retrieve cached results. Supports dual-recording mode for trend comparison.
+ `start` begins a recording of `duration` seconds (default 60) and returns at once; `status` checks it, `query`
+ (or `stop`, to end it early) returns the results, and `compare` compares the last two recordings (growth and
+ trend per class). For a trend, record X seconds, then 2X seconds, then compare. `mode=dual` does all of this in one
+ call that blocks for about three times the duration (90 seconds with its default of 30), longer than many MCP
+ clients wait: use it only with a client that waits that long.
| `camel_runtime_history`
| Get the message history trace of the last completed exchange. Shows the route path, processors visited,
- headers, body, and timing.
+ headers, body, and timing. It is recorded when message history is on and the tracer is enabled or on standby,
+ which is the default of `camel run` (dev profile); elsewhere set `camel.main.message-history=true` and
+ `camel.main.tracing-standby=true`.
Review Comment:
Same as the tool description: the history needs the backlog tracer on standby (`camel.trace.standby`), not the log tracer.
```suggestion
`camel.trace.standby=true`.
```
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeTools.java:
##########
@@ -662,50 +727,120 @@ private JsonObject doDualJfrRecording(long pid, String duration, String stacktra
});
}
+ /**
+ * Waits until the recording stopped by itself: sleeps for the time the console says is left, then checks again (a
+ * recording ends a little after its duration, as it is parsed).
+ */
private void waitForJfrRecordingComplete(long pid, int dur) {
long deadline = System.currentTimeMillis() + (dur + 30) * 1000L;
while (System.currentTimeMillis() < deadline) {
+ JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
+ root.put("command", "status");
+ });
+ if (status == null || !"recording".equals(status.getString("status"))) {
+ return;
+ }
+ long remaining = status.getLongOrDefault("remainingMs", 1000L);
+ long wait = Math.min(Math.max(remaining, 500L), Math.max(1L, deadline - System.currentTimeMillis()));
try {
- Thread.sleep(3000);
+ TimeUnit.MILLISECONDS.sleep(wait);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ToolCallException("Interrupted while waiting for recording", null);
}
- JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
- root.put("command", "status");
- });
- if (status != null && !"recording".equals(status.getString("status"))) {
- break;
- }
}
}
@Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
description = """
- Get the message history trace of the last completed exchange. \
- This is always captured (no need to enable tracing) and shows the single most recent exchange \
- with its route path, processors visited, headers, body, and timing.""")
+ Get the message history trace of the last completed exchange, with its route path, processors \
+ visited, headers, body, and timing. Recorded when message history is on and the tracer is \
+ enabled or on standby: the default of camel run (dev profile); otherwise set \
+ camel.main.message-history=true and camel.main.tracing-standby=true.""")
public JsonObject camel_runtime_history(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid) {
return delegateToRegistry("get_history", nameOrPid, Map.of());
}
- @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = false, openWorldHint = false),
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = true, openWorldHint = false),
description = """
- Receive (poll) a message from a Camel endpoint in the running application. \
- This is the complement to camel_runtime_send — it consumes one message from the endpoint.""")
+ Receive (consume) a message from an endpoint of the running application, the complement of \
+ camel_runtime_send: starts a consumer on the endpoint, waits for a message, returns it and stops \
+ the consumer again. The consumer competes with the routes that consume the endpoint, so the \
+ message it takes does not reach them (a queue or topic message is gone). \
+ To look at queued messages without taking them use camel_runtime_browse.""")
public JsonObject camel_runtime_receive(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid,
- @ToolArg(description = "Endpoint URI to receive from") String endpoint) {
+ @ToolArg(description = "Endpoint URI to receive from, or a pattern matching an endpoint the application "
+ + "sends to, e.g. seda:orders or kafka*") String endpoint,
+ @ToolArg(description = "How long to wait for a message in seconds (default 10, at most 60)",
+ required = false) Integer timeoutSeconds) {
if (endpoint == null || endpoint.isBlank()) {
throw new ToolCallException("endpoint is required", null);
}
- // receive is MCP-only (no ToolRegistry equivalent) — call RuntimeService directly
+ int timeout = timeoutSeconds == null || timeoutSeconds <= 0
+ ? RECEIVE_DEFAULT_TIMEOUT : Math.min(timeoutSeconds, RECEIVE_MAX_TIMEOUT);
RuntimeService.ProcessInfo p = runtimeService.findSingleProcess(nameOrPid);
- return runtimeService.executeAction(p.pid(), "receive", root -> {
+ return receive(p.pid(), endpoint, timeout * 1000L);
+ }
+
+ /**
+ * Enables the receive console of the process for the endpoint, waits for the messages the CLI connector writes to
+ * the receive file, and disables it again whatever happens.
+ */
+ JsonObject receive(long pid, String endpoint, long timeoutMs) {
+ JsonObject state = runtimeService.readStatusSection(pid, "receive");
+ Collection<?> active = state.getCollection("endpoints");
+ if (Boolean.TRUE.equals(state.getBoolean("enabled")) && active != null && !active.isEmpty()) {
+ // disabling would stop those consumers too
+ throw new ToolCallException(
+ "The process is already receiving from " + active
+ + " (camel receive); stop that first with: camel receive --action=stop",
+ null);
+ }
+ long offset = runtimeService.receiveFileSize(pid);
+ JsonObject started = runtimeService.executeAction(pid, "receive", root -> {
root.put("enabled", "true");
root.put("endpoint", endpoint);
});
+ try {
+ if (started.getString("error") != null) {
+ throw new ToolCallException("Cannot receive from " + endpoint + ": " + started.getString("error"), null);
+ }
+ String uri = started.getString("url");
+ if (uri == null) {
+ throw new ToolCallException(
+ "No endpoint matches " + endpoint
+ + " (a pattern matches the endpoints the application sends to; "
+ + "camel_runtime_endpoints lists them)",
+ null);
+ }
+ JsonObject answer = new JsonObject();
+ answer.put("endpoint", uri);
+ StopWatch watch = new StopWatch();
+ while (true) {
+ List<JsonObject> messages = runtimeService.readReceivedMessages(pid, offset);
+ if (!messages.isEmpty()) {
+ answer.put("received", messages.size());
+ answer.put("messages", messages);
+ return answer;
+ }
+ if (watch.taken() >= timeoutMs) {
+ answer.put("received", 0);
+ answer.put("note", "No message arrived within " + (timeoutMs / 1000) + " seconds");
+ return answer;
+ }
+ try {
+ TimeUnit.MILLISECONDS.sleep(RECEIVE_POLL_MS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new ToolCallException("Interrupted while waiting for a message", null);
+ }
+ }
+ } finally {
+ // an action without an endpoint stops the consumers of the receive console
+ runtimeService.executeAction(pid, "receive", null);
Review Comment:
Nit: if this call fails (`executeAction` throws a `ToolCallException` on a timeout), its exception replaces the answer with the received messages, and the consumer keeps taking messages from the routes, which is the leak this PR fixes. Catching it and returning the answer with a warning that names the stop command (`camel cmd receive --action=stop`) keeps both.
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeTools.java:
##########
@@ -69,12 +83,23 @@ private JsonObject delegateToRegistry(String registryToolName, String nameOrPid,
ctx.selectProcess(p.pid());
try {
Object result = ToolRegistry.execute(registryToolName, ctx, args);
+ failOnTimeout(result);
return toJsonObject(result);
} catch (ToolExecutionException e) {
throw new ToolCallException(e.getMessage(), e);
}
}
+ /**
+ * The registry answers an action the process did not answer in time (a dead or hung process) with a text, not an
+ * exception: report it as the failure it is rather than as a result.
+ */
+ static void failOnTimeout(Object result) {
Review Comment:
Nit: since #27931, `ToolContext.executeAction` throws a `ToolExecutionException` when the integration does not answer in time, and `delegateToRegistry` (and `AiTraceTools.executeRegistryTool`) already turn it into an error. No registry tool returns the timeout text any more (only `RuntimeService` uses the `RuntimeHelper.executeAction` text API, and it checks the text itself), so this check cannot trigger, and `aTimeoutIsAnError` tests it with a made-up string. Could it go, together with `TIMEOUT_PREFIX`? Otherwise a comment saying it is only a guard would help, as the PR description presents it as what turns timeouts into errors.
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeTools.java:
##########
@@ -662,50 +727,120 @@ private JsonObject doDualJfrRecording(long pid, String duration, String stacktra
});
}
+ /**
+ * Waits until the recording stopped by itself: sleeps for the time the console says is left, then checks again (a
+ * recording ends a little after its duration, as it is parsed).
+ */
private void waitForJfrRecordingComplete(long pid, int dur) {
long deadline = System.currentTimeMillis() + (dur + 30) * 1000L;
while (System.currentTimeMillis() < deadline) {
+ JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
+ root.put("command", "status");
+ });
+ if (status == null || !"recording".equals(status.getString("status"))) {
+ return;
+ }
+ long remaining = status.getLongOrDefault("remainingMs", 1000L);
+ long wait = Math.min(Math.max(remaining, 500L), Math.max(1L, deadline - System.currentTimeMillis()));
try {
- Thread.sleep(3000);
+ TimeUnit.MILLISECONDS.sleep(wait);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ToolCallException("Interrupted while waiting for recording", null);
}
- JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
- root.put("command", "status");
- });
- if (status != null && !"recording".equals(status.getString("status"))) {
- break;
- }
}
}
@Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
description = """
- Get the message history trace of the last completed exchange. \
- This is always captured (no need to enable tracing) and shows the single most recent exchange \
- with its route path, processors visited, headers, body, and timing.""")
+ Get the message history trace of the last completed exchange, with its route path, processors \
+ visited, headers, body, and timing. Recorded when message history is on and the tracer is \
+ enabled or on standby: the default of camel run (dev profile); otherwise set \
+ camel.main.message-history=true and camel.main.tracing-standby=true.""")
public JsonObject camel_runtime_history(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid) {
return delegateToRegistry("get_history", nameOrPid, Map.of());
}
- @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = false, openWorldHint = false),
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = true, openWorldHint = false),
description = """
- Receive (poll) a message from a Camel endpoint in the running application. \
- This is the complement to camel_runtime_send — it consumes one message from the endpoint.""")
+ Receive (consume) a message from an endpoint of the running application, the complement of \
+ camel_runtime_send: starts a consumer on the endpoint, waits for a message, returns it and stops \
+ the consumer again. The consumer competes with the routes that consume the endpoint, so the \
+ message it takes does not reach them (a queue or topic message is gone). \
+ To look at queued messages without taking them use camel_runtime_browse.""")
public JsonObject camel_runtime_receive(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid,
- @ToolArg(description = "Endpoint URI to receive from") String endpoint) {
+ @ToolArg(description = "Endpoint URI to receive from, or a pattern matching an endpoint the application "
+ + "sends to, e.g. seda:orders or kafka*") String endpoint,
+ @ToolArg(description = "How long to wait for a message in seconds (default 10, at most 60)",
+ required = false) Integer timeoutSeconds) {
if (endpoint == null || endpoint.isBlank()) {
throw new ToolCallException("endpoint is required", null);
}
- // receive is MCP-only (no ToolRegistry equivalent) — call RuntimeService directly
+ int timeout = timeoutSeconds == null || timeoutSeconds <= 0
+ ? RECEIVE_DEFAULT_TIMEOUT : Math.min(timeoutSeconds, RECEIVE_MAX_TIMEOUT);
RuntimeService.ProcessInfo p = runtimeService.findSingleProcess(nameOrPid);
- return runtimeService.executeAction(p.pid(), "receive", root -> {
+ return receive(p.pid(), endpoint, timeout * 1000L);
+ }
+
+ /**
+ * Enables the receive console of the process for the endpoint, waits for the messages the CLI connector writes to
+ * the receive file, and disables it again whatever happens.
+ */
+ JsonObject receive(long pid, String endpoint, long timeoutMs) {
+ JsonObject state = runtimeService.readStatusSection(pid, "receive");
+ Collection<?> active = state.getCollection("endpoints");
+ if (Boolean.TRUE.equals(state.getBoolean("enabled")) && active != null && !active.isEmpty()) {
+ // disabling would stop those consumers too
+ throw new ToolCallException(
+ "The process is already receiving from " + active
+ + " (camel receive); stop that first with: camel receive --action=stop",
+ null);
+ }
+ long offset = runtimeService.receiveFileSize(pid);
+ JsonObject started = runtimeService.executeAction(pid, "receive", root -> {
root.put("enabled", "true");
root.put("endpoint", endpoint);
});
+ try {
+ if (started.getString("error") != null) {
+ throw new ToolCallException("Cannot receive from " + endpoint + ": " + started.getString("error"), null);
+ }
+ String uri = started.getString("url");
+ if (uri == null) {
+ throw new ToolCallException(
+ "No endpoint matches " + endpoint
+ + " (a pattern matches the endpoints the application sends to; "
+ + "camel_runtime_endpoints lists them)",
+ null);
+ }
+ JsonObject answer = new JsonObject();
+ answer.put("endpoint", uri);
+ StopWatch watch = new StopWatch();
+ while (true) {
+ List<JsonObject> messages = runtimeService.readReceivedMessages(pid, offset);
+ if (!messages.isEmpty()) {
+ answer.put("received", messages.size());
+ answer.put("messages", messages);
Review Comment:
Every message of the first poll that finds any is returned, each with its headers and its body (the receive console keeps up to 100 messages, with bodies of up to 32 KB). On a busy Kafka or JMS endpoint the file transport can write many messages in one tick, so one call can answer with megabytes, while #27839 caps the catalog answers at 16 000 characters. The description says the tool returns *a* message: could it return the first one (or a `limit`, default 1) and say how many more were taken? The others are gone from the routes either way, so the count tells the agent that.
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeService.java:
##########
@@ -123,6 +129,58 @@ public String stopApplication(long pid) {
return RuntimeHelper.stopApplication(pid);
}
+ /**
+ * The size of the file the CLI connector appends the messages of the receive console to
+ * ({@code {pid}-receive.json}, read by {@code camel receive} too), to read only what arrives after this point.
+ */
+ public long receiveFileSize(long pid) {
+ try {
+ Path file = receiveFile(pid);
+ return Files.exists(file) ? Files.size(file) : 0;
+ } catch (IOException e) {
+ return 0;
+ }
+ }
+
+ /**
+ * The messages the CLI connector appended to the receive file after the given offset: each complete line is a
+ * {@code {"messages": [...]}} dump of the receive console.
+ */
+ public List<JsonObject> readReceivedMessages(long pid, long offset) {
+ List<JsonObject> messages = new ArrayList<>();
+ Path file = receiveFile(pid);
+ try {
+ if (!Files.exists(file)) {
+ return messages;
+ }
+ byte[] data = Files.readAllBytes(file);
Review Comment:
Nit: the receive file is only appended to (and kept across `camel cmd receive` sessions), and this reads all of it every 200 ms for up to 60 seconds. Reading from `offset` (a `SeekableByteChannel` positioned there, or a `RandomAccessFile`) keeps the poll cheap when the file has grown.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@camel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] CAMEL-25642: camel-jbang-mcp - runtime tools wiring: receive in one call, routeId honoured, prompts name real tools, timeouts are errors [camel]
Posted by "Croway (via GitHub)" <gi...@apache.org>.
Croway commented on code in PR #27958:
URL: https://github.com/apache/camel/pull/27958#discussion_r4300209719
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeTools.java:
##########
@@ -662,50 +727,120 @@ private JsonObject doDualJfrRecording(long pid, String duration, String stacktra
});
}
+ /**
+ * Waits until the recording stopped by itself: sleeps for the time the console says is left, then checks again (a
+ * recording ends a little after its duration, as it is parsed).
+ */
private void waitForJfrRecordingComplete(long pid, int dur) {
long deadline = System.currentTimeMillis() + (dur + 30) * 1000L;
while (System.currentTimeMillis() < deadline) {
+ JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
+ root.put("command", "status");
+ });
+ if (status == null || !"recording".equals(status.getString("status"))) {
+ return;
+ }
+ long remaining = status.getLongOrDefault("remainingMs", 1000L);
+ long wait = Math.min(Math.max(remaining, 500L), Math.max(1L, deadline - System.currentTimeMillis()));
try {
- Thread.sleep(3000);
+ TimeUnit.MILLISECONDS.sleep(wait);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ToolCallException("Interrupted while waiting for recording", null);
}
- JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
- root.put("command", "status");
- });
- if (status != null && !"recording".equals(status.getString("status"))) {
- break;
- }
}
}
@Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
description = """
- Get the message history trace of the last completed exchange. \
- This is always captured (no need to enable tracing) and shows the single most recent exchange \
- with its route path, processors visited, headers, body, and timing.""")
+ Get the message history trace of the last completed exchange, with its route path, processors \
+ visited, headers, body, and timing. Recorded when message history is on and the tracer is \
+ enabled or on standby: the default of camel run (dev profile); otherwise set \
+ camel.main.message-history=true and camel.main.tracing-standby=true.""")
public JsonObject camel_runtime_history(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid) {
return delegateToRegistry("get_history", nameOrPid, Map.of());
}
- @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = false, openWorldHint = false),
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = true, openWorldHint = false),
description = """
- Receive (poll) a message from a Camel endpoint in the running application. \
- This is the complement to camel_runtime_send — it consumes one message from the endpoint.""")
+ Receive (consume) a message from an endpoint of the running application, the complement of \
+ camel_runtime_send: starts a consumer on the endpoint, waits for a message, returns it and stops \
+ the consumer again. The consumer competes with the routes that consume the endpoint, so the \
+ message it takes does not reach them (a queue or topic message is gone). \
+ To look at queued messages without taking them use camel_runtime_browse.""")
public JsonObject camel_runtime_receive(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid,
- @ToolArg(description = "Endpoint URI to receive from") String endpoint) {
+ @ToolArg(description = "Endpoint URI to receive from, or a pattern matching an endpoint the application "
+ + "sends to, e.g. seda:orders or kafka*") String endpoint,
+ @ToolArg(description = "How long to wait for a message in seconds (default 10, at most 60)",
+ required = false) Integer timeoutSeconds) {
if (endpoint == null || endpoint.isBlank()) {
throw new ToolCallException("endpoint is required", null);
}
- // receive is MCP-only (no ToolRegistry equivalent) — call RuntimeService directly
+ int timeout = timeoutSeconds == null || timeoutSeconds <= 0
+ ? RECEIVE_DEFAULT_TIMEOUT : Math.min(timeoutSeconds, RECEIVE_MAX_TIMEOUT);
RuntimeService.ProcessInfo p = runtimeService.findSingleProcess(nameOrPid);
- return runtimeService.executeAction(p.pid(), "receive", root -> {
+ return receive(p.pid(), endpoint, timeout * 1000L);
+ }
+
+ /**
+ * Enables the receive console of the process for the endpoint, waits for the messages the CLI connector writes to
+ * the receive file, and disables it again whatever happens.
+ */
+ JsonObject receive(long pid, String endpoint, long timeoutMs) {
+ JsonObject state = runtimeService.readStatusSection(pid, "receive");
+ Collection<?> active = state.getCollection("endpoints");
+ if (Boolean.TRUE.equals(state.getBoolean("enabled")) && active != null && !active.isEmpty()) {
+ // disabling would stop those consumers too
+ throw new ToolCallException(
+ "The process is already receiving from " + active
+ + " (camel receive); stop that first with: camel receive --action=stop",
Review Comment:
Done in 6676883e9f13: `camel cmd receive` in the error, in both `RuntimeService` comments, on the MCP page and in the upgrade guide; `camel receive` no longer appears in the diff.
_Claude Code on behalf of Croway_
##########
docs/user-manual/modules/ROOT/pages/camel-jbang-mcp.adoc:
##########
@@ -979,23 +987,33 @@ xref:camel-jbang-tui-local-models.adoc#_tool_groups_from_the_selected_integratio
| Tool | Description
| `camel_runtime_send`
-| Send a test message to a Camel endpoint in the running application.
+| Send a test message to a Camel endpoint in the running application. Marked destructive: the message runs through
+ the routes and whatever they call.
| `camel_runtime_trace`
| Enable, disable, or dump message tracing for the running Camel application.
+| `camel_runtime_trace_dump`
+| Dump the traced messages, the same as `camel_runtime_trace` with `action=dump`, as a read-only tool, so a client
+ at the `read-only` access level can read the traces.
+
| `camel_runtime_ai_trace`
| Trace the AI-specific exchange flow of a running application: token usage, model ids, guardrail outcomes,
completion reasons, streaming chunk counts and per-component latency for the AI components (Bedrock,
LangChain4j, Docling, Textract, OpenAI, KServe, DJL, TensorFlow Serving, HuggingFace). It combines the message
- history with the processor statistics, filtered to the AI steps.
+ history with the processor statistics, filtered to the AI steps. A process that does not answer is reported as
+ an error.
| `camel_runtime_browse`
| Browse messages in a Camel endpoint (e.g., messages queued in a SEDA endpoint).
| `camel_runtime_receive`
-| Receive (poll) a message from a Camel endpoint in the running application. Consumes one message
- from the endpoint.
+| Receive a message from an endpoint of the running application, the complement of `camel_runtime_send`, in one
+ call: it starts a consumer on the endpoint (an endpoint uri, or a pattern matching an endpoint the application
+ sends to), waits up to `timeoutSeconds` (default 10, at most 60) for a message, returns it and stops the consumer.
+ The consumer competes with the routes that consume the endpoint, so the message it takes does not reach them:
+ the tool is marked destructive. Use `camel_runtime_browse` to look at queued messages without taking them. It
+ refuses to run while `camel receive` is receiving from the same process.
Review Comment:
Done in 6676883e9f13.
_Claude Code on behalf of Croway_
##########
docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc:
##########
@@ -1256,3 +1256,23 @@ The consumer now sets the `CamelMiloNodeId` header on every exchange, including
Stopping a consumer now deletes its monitored items. Previously they stayed on the server while another endpoint kept
the shared connection open, so a restarted consumer received each value twice. While the server is unreachable, the
stop waits until the client's next attempt to reconnect has failed.
+
+=== camel-jbang-mcp - runtime tools that changed behaviour
+
+Some runtime tools of the Camel MCP server now do what their description says, which changes what a client sees:
+
+* `camel_runtime_receive` receives a message in one call: it starts a consumer on the endpoint, waits up to
+ `timeoutSeconds` (default 10, at most 60) for a message, returns it and stops the consumer. Before, it started a
+ consumer that kept running, took the messages from the routes, and returned none of them. It is now marked
+ destructive, so the `read-write` access level (`camel.mcp.security.access-level`) no longer offers it, only
+ `admin` does. It refuses to run while
+ `camel receive` is receiving from the same process.
Review Comment:
Done in 6676883e9f13.
_Claude Code on behalf of Croway_
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeTools.java:
##########
@@ -662,50 +727,120 @@ private JsonObject doDualJfrRecording(long pid, String duration, String stacktra
});
}
+ /**
+ * Waits until the recording stopped by itself: sleeps for the time the console says is left, then checks again (a
+ * recording ends a little after its duration, as it is parsed).
+ */
private void waitForJfrRecordingComplete(long pid, int dur) {
long deadline = System.currentTimeMillis() + (dur + 30) * 1000L;
while (System.currentTimeMillis() < deadline) {
+ JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
+ root.put("command", "status");
+ });
+ if (status == null || !"recording".equals(status.getString("status"))) {
+ return;
+ }
+ long remaining = status.getLongOrDefault("remainingMs", 1000L);
+ long wait = Math.min(Math.max(remaining, 500L), Math.max(1L, deadline - System.currentTimeMillis()));
try {
- Thread.sleep(3000);
+ TimeUnit.MILLISECONDS.sleep(wait);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ToolCallException("Interrupted while waiting for recording", null);
}
- JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
- root.put("command", "status");
- });
- if (status != null && !"recording".equals(status.getString("status"))) {
- break;
- }
}
}
@Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
description = """
- Get the message history trace of the last completed exchange. \
- This is always captured (no need to enable tracing) and shows the single most recent exchange \
- with its route path, processors visited, headers, body, and timing.""")
+ Get the message history trace of the last completed exchange, with its route path, processors \
+ visited, headers, body, and timing. Recorded when message history is on and the tracer is \
+ enabled or on standby: the default of camel run (dev profile); otherwise set \
+ camel.main.message-history=true and camel.main.tracing-standby=true.""")
Review Comment:
Done in 6676883e9f13: the description and the MCP page name `camel.trace.standby`. Checked on the branch: the dev profile sets `tracerConfig().withStandby(true)` (`TracerConfigurationProperties.standby`, key `camel.trace.standby`), `BaseMainSupport` creates the `BacklogTracer` when it is enabled or on standby, and `MessageHistoryDevConsole` reads `BacklogTracer.getLatestMessageHistory()`; `camel.main.tracingStandby` goes to `CamelContext.setTracingStandby`, the log `Tracer`.
_Claude Code on behalf of Croway_
##########
docs/user-manual/modules/ROOT/pages/camel-jbang-mcp.adoc:
##########
@@ -846,16 +849,21 @@ process is running).
| `camel_runtime_heap_dump`
| Write a heap dump (`.hprof`) from a running integration for deep memory analysis with tools such as Eclipse MAT,
- VisualVM or jhat. The dump is written to the process working directory.
+ VisualVM or jhat. The dump is written to the process working directory; a `name` with a directory is refused.
| `camel_runtime_memory_leak`
| Diagnose memory leaks in a running Camel integration using Java Flight Recorder (JFR).
- Use command 'start' to begin recording, 'stop' to get results, 'status' to check state,
- and 'query' to retrieve cached results. Supports dual-recording mode for trend comparison.
+ `start` begins a recording of `duration` seconds (default 60) and returns at once; `status` checks it, `query`
+ (or `stop`, to end it early) returns the results, and `compare` compares the last two recordings (growth and
+ trend per class). For a trend, record X seconds, then 2X seconds, then compare. `mode=dual` does all of this in one
+ call that blocks for about three times the duration (90 seconds with its default of 30), longer than many MCP
+ clients wait: use it only with a client that waits that long.
| `camel_runtime_history`
| Get the message history trace of the last completed exchange. Shows the route path, processors visited,
- headers, body, and timing.
+ headers, body, and timing. It is recorded when message history is on and the tracer is enabled or on standby,
+ which is the default of `camel run` (dev profile); elsewhere set `camel.main.message-history=true` and
+ `camel.main.tracing-standby=true`.
Review Comment:
Done in 6676883e9f13.
_Claude Code on behalf of Croway_
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeTools.java:
##########
@@ -662,50 +727,120 @@ private JsonObject doDualJfrRecording(long pid, String duration, String stacktra
});
}
+ /**
+ * Waits until the recording stopped by itself: sleeps for the time the console says is left, then checks again (a
+ * recording ends a little after its duration, as it is parsed).
+ */
private void waitForJfrRecordingComplete(long pid, int dur) {
long deadline = System.currentTimeMillis() + (dur + 30) * 1000L;
while (System.currentTimeMillis() < deadline) {
+ JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
+ root.put("command", "status");
+ });
+ if (status == null || !"recording".equals(status.getString("status"))) {
+ return;
+ }
+ long remaining = status.getLongOrDefault("remainingMs", 1000L);
+ long wait = Math.min(Math.max(remaining, 500L), Math.max(1L, deadline - System.currentTimeMillis()));
try {
- Thread.sleep(3000);
+ TimeUnit.MILLISECONDS.sleep(wait);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ToolCallException("Interrupted while waiting for recording", null);
}
- JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
- root.put("command", "status");
- });
- if (status != null && !"recording".equals(status.getString("status"))) {
- break;
- }
}
}
@Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
description = """
- Get the message history trace of the last completed exchange. \
- This is always captured (no need to enable tracing) and shows the single most recent exchange \
- with its route path, processors visited, headers, body, and timing.""")
+ Get the message history trace of the last completed exchange, with its route path, processors \
+ visited, headers, body, and timing. Recorded when message history is on and the tracer is \
+ enabled or on standby: the default of camel run (dev profile); otherwise set \
+ camel.main.message-history=true and camel.main.tracing-standby=true.""")
public JsonObject camel_runtime_history(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid) {
return delegateToRegistry("get_history", nameOrPid, Map.of());
}
- @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = false, openWorldHint = false),
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = true, openWorldHint = false),
description = """
- Receive (poll) a message from a Camel endpoint in the running application. \
- This is the complement to camel_runtime_send — it consumes one message from the endpoint.""")
+ Receive (consume) a message from an endpoint of the running application, the complement of \
+ camel_runtime_send: starts a consumer on the endpoint, waits for a message, returns it and stops \
+ the consumer again. The consumer competes with the routes that consume the endpoint, so the \
+ message it takes does not reach them (a queue or topic message is gone). \
+ To look at queued messages without taking them use camel_runtime_browse.""")
public JsonObject camel_runtime_receive(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid,
- @ToolArg(description = "Endpoint URI to receive from") String endpoint) {
+ @ToolArg(description = "Endpoint URI to receive from, or a pattern matching an endpoint the application "
+ + "sends to, e.g. seda:orders or kafka*") String endpoint,
+ @ToolArg(description = "How long to wait for a message in seconds (default 10, at most 60)",
+ required = false) Integer timeoutSeconds) {
if (endpoint == null || endpoint.isBlank()) {
throw new ToolCallException("endpoint is required", null);
}
- // receive is MCP-only (no ToolRegistry equivalent) — call RuntimeService directly
+ int timeout = timeoutSeconds == null || timeoutSeconds <= 0
+ ? RECEIVE_DEFAULT_TIMEOUT : Math.min(timeoutSeconds, RECEIVE_MAX_TIMEOUT);
RuntimeService.ProcessInfo p = runtimeService.findSingleProcess(nameOrPid);
- return runtimeService.executeAction(p.pid(), "receive", root -> {
+ return receive(p.pid(), endpoint, timeout * 1000L);
+ }
+
+ /**
+ * Enables the receive console of the process for the endpoint, waits for the messages the CLI connector writes to
+ * the receive file, and disables it again whatever happens.
+ */
+ JsonObject receive(long pid, String endpoint, long timeoutMs) {
+ JsonObject state = runtimeService.readStatusSection(pid, "receive");
+ Collection<?> active = state.getCollection("endpoints");
+ if (Boolean.TRUE.equals(state.getBoolean("enabled")) && active != null && !active.isEmpty()) {
+ // disabling would stop those consumers too
+ throw new ToolCallException(
+ "The process is already receiving from " + active
+ + " (camel receive); stop that first with: camel receive --action=stop",
+ null);
+ }
+ long offset = runtimeService.receiveFileSize(pid);
+ JsonObject started = runtimeService.executeAction(pid, "receive", root -> {
root.put("enabled", "true");
root.put("endpoint", endpoint);
});
+ try {
+ if (started.getString("error") != null) {
+ throw new ToolCallException("Cannot receive from " + endpoint + ": " + started.getString("error"), null);
+ }
+ String uri = started.getString("url");
+ if (uri == null) {
+ throw new ToolCallException(
+ "No endpoint matches " + endpoint
+ + " (a pattern matches the endpoints the application sends to; "
+ + "camel_runtime_endpoints lists them)",
+ null);
+ }
+ JsonObject answer = new JsonObject();
+ answer.put("endpoint", uri);
+ StopWatch watch = new StopWatch();
+ while (true) {
+ List<JsonObject> messages = runtimeService.readReceivedMessages(pid, offset);
+ if (!messages.isEmpty()) {
+ answer.put("received", messages.size());
+ answer.put("messages", messages);
Review Comment:
Done in 6676883e9f13: `limit` (default 1, at least 1). The answer keeps the first `limit` messages of the poll that found them; `received` is the total taken in that poll, and `notReturned` with a note says how many are left out and that they were taken from the endpoint all the same. The description says "receives one message by default". Two tests in `RuntimeToolsWiringTest` (`receiveReturnsTheFirstMessagesUpToTheLimitAndCountsTheOthers`, `receiveRefusesALimitBelowOne`).
_Claude Code on behalf of Croway_
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeTools.java:
##########
@@ -69,12 +83,23 @@ private JsonObject delegateToRegistry(String registryToolName, String nameOrPid,
ctx.selectProcess(p.pid());
try {
Object result = ToolRegistry.execute(registryToolName, ctx, args);
+ failOnTimeout(result);
return toJsonObject(result);
} catch (ToolExecutionException e) {
throw new ToolCallException(e.getMessage(), e);
}
}
+ /**
+ * The registry answers an action the process did not answer in time (a dead or hung process) with a text, not an
+ * exception: report it as the failure it is rather than as a result.
+ */
+ static void failOnTimeout(Object result) {
Review Comment:
You are right. On the rebased branch `ToolContext.executeAction` throws `ToolExecutionException` when the integration does not answer, and `delegateToRegistry` / `executeRegistryTool` turn it into a `ToolCallException`; the one text path left in the registry, `execute_sql_query`, wraps the timeout text as `{"result": ...}`, so the prefix check never caught it either. Removed in 6676883e9f13: `failOnTimeout`, `RuntimeHelper.TIMEOUT_PREFIX`, the `aTimeoutIsAnError` test and the upgrade-guide bullet that presented it as a change; `RuntimeHelper` is back to the main version. The PR description no longer claims it. `execute_sql_query` answering a timeout as a result is pre-existing and left out of this PR.
_Claude Code on behalf of Croway_
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@camel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] CAMEL-25642: camel-jbang-mcp - runtime tools wiring: receive in one call, routeId honoured, prompts name real tools, timeouts are errors [camel]
Posted by "Croway (via GitHub)" <gi...@apache.org>.
Croway commented on code in PR #27958:
URL: https://github.com/apache/camel/pull/27958#discussion_r4300210732
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeService.java:
##########
@@ -123,6 +129,58 @@ public String stopApplication(long pid) {
return RuntimeHelper.stopApplication(pid);
}
+ /**
+ * The size of the file the CLI connector appends the messages of the receive console to
+ * ({@code {pid}-receive.json}, read by {@code camel receive} too), to read only what arrives after this point.
+ */
+ public long receiveFileSize(long pid) {
+ try {
+ Path file = receiveFile(pid);
+ return Files.exists(file) ? Files.size(file) : 0;
+ } catch (IOException e) {
+ return 0;
+ }
+ }
+
+ /**
+ * The messages the CLI connector appended to the receive file after the given offset: each complete line is a
+ * {@code {"messages": [...]}} dump of the receive console.
+ */
+ public List<JsonObject> readReceivedMessages(long pid, long offset) {
+ List<JsonObject> messages = new ArrayList<>();
+ Path file = receiveFile(pid);
+ try {
+ if (!Files.exists(file)) {
+ return messages;
+ }
+ byte[] data = Files.readAllBytes(file);
Review Comment:
Done in 6676883e9f13: `readReceivedMessages` opens a `SeekableByteChannel`, positions it at the offset and reads only `size - offset` bytes (from 0 when the file is shorter than the offset, after a clear). The clear case is added to `readReceivedMessagesReadsTheLinesAfterTheOffset`.
_Claude Code on behalf of Croway_
##########
dsl/camel-jbang/camel-jbang-mcp/src/main/java/org/apache/camel/dsl/jbang/core/commands/mcp/RuntimeTools.java:
##########
@@ -662,50 +727,120 @@ private JsonObject doDualJfrRecording(long pid, String duration, String stacktra
});
}
+ /**
+ * Waits until the recording stopped by itself: sleeps for the time the console says is left, then checks again (a
+ * recording ends a little after its duration, as it is parsed).
+ */
private void waitForJfrRecordingComplete(long pid, int dur) {
long deadline = System.currentTimeMillis() + (dur + 30) * 1000L;
while (System.currentTimeMillis() < deadline) {
+ JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
+ root.put("command", "status");
+ });
+ if (status == null || !"recording".equals(status.getString("status"))) {
+ return;
+ }
+ long remaining = status.getLongOrDefault("remainingMs", 1000L);
+ long wait = Math.min(Math.max(remaining, 500L), Math.max(1L, deadline - System.currentTimeMillis()));
try {
- Thread.sleep(3000);
+ TimeUnit.MILLISECONDS.sleep(wait);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ToolCallException("Interrupted while waiting for recording", null);
}
- JsonObject status = runtimeService.executeAction(pid, "jfr-memory-leak", root -> {
- root.put("command", "status");
- });
- if (status != null && !"recording".equals(status.getString("status"))) {
- break;
- }
}
}
@Tool(annotations = @Tool.Annotations(readOnlyHint = true, destructiveHint = false, openWorldHint = false),
description = """
- Get the message history trace of the last completed exchange. \
- This is always captured (no need to enable tracing) and shows the single most recent exchange \
- with its route path, processors visited, headers, body, and timing.""")
+ Get the message history trace of the last completed exchange, with its route path, processors \
+ visited, headers, body, and timing. Recorded when message history is on and the tracer is \
+ enabled or on standby: the default of camel run (dev profile); otherwise set \
+ camel.main.message-history=true and camel.main.tracing-standby=true.""")
public JsonObject camel_runtime_history(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid) {
return delegateToRegistry("get_history", nameOrPid, Map.of());
}
- @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = false, openWorldHint = false),
+ @Tool(annotations = @Tool.Annotations(readOnlyHint = false, destructiveHint = true, openWorldHint = false),
description = """
- Receive (poll) a message from a Camel endpoint in the running application. \
- This is the complement to camel_runtime_send — it consumes one message from the endpoint.""")
+ Receive (consume) a message from an endpoint of the running application, the complement of \
+ camel_runtime_send: starts a consumer on the endpoint, waits for a message, returns it and stops \
+ the consumer again. The consumer competes with the routes that consume the endpoint, so the \
+ message it takes does not reach them (a queue or topic message is gone). \
+ To look at queued messages without taking them use camel_runtime_browse.""")
public JsonObject camel_runtime_receive(
@ToolArg(description = NAME_OR_PID_DESC, required = false) String nameOrPid,
- @ToolArg(description = "Endpoint URI to receive from") String endpoint) {
+ @ToolArg(description = "Endpoint URI to receive from, or a pattern matching an endpoint the application "
+ + "sends to, e.g. seda:orders or kafka*") String endpoint,
+ @ToolArg(description = "How long to wait for a message in seconds (default 10, at most 60)",
+ required = false) Integer timeoutSeconds) {
if (endpoint == null || endpoint.isBlank()) {
throw new ToolCallException("endpoint is required", null);
}
- // receive is MCP-only (no ToolRegistry equivalent) — call RuntimeService directly
+ int timeout = timeoutSeconds == null || timeoutSeconds <= 0
+ ? RECEIVE_DEFAULT_TIMEOUT : Math.min(timeoutSeconds, RECEIVE_MAX_TIMEOUT);
RuntimeService.ProcessInfo p = runtimeService.findSingleProcess(nameOrPid);
- return runtimeService.executeAction(p.pid(), "receive", root -> {
+ return receive(p.pid(), endpoint, timeout * 1000L);
+ }
+
+ /**
+ * Enables the receive console of the process for the endpoint, waits for the messages the CLI connector writes to
+ * the receive file, and disables it again whatever happens.
+ */
+ JsonObject receive(long pid, String endpoint, long timeoutMs) {
+ JsonObject state = runtimeService.readStatusSection(pid, "receive");
+ Collection<?> active = state.getCollection("endpoints");
+ if (Boolean.TRUE.equals(state.getBoolean("enabled")) && active != null && !active.isEmpty()) {
+ // disabling would stop those consumers too
+ throw new ToolCallException(
+ "The process is already receiving from " + active
+ + " (camel receive); stop that first with: camel receive --action=stop",
+ null);
+ }
+ long offset = runtimeService.receiveFileSize(pid);
+ JsonObject started = runtimeService.executeAction(pid, "receive", root -> {
root.put("enabled", "true");
root.put("endpoint", endpoint);
});
+ try {
+ if (started.getString("error") != null) {
+ throw new ToolCallException("Cannot receive from " + endpoint + ": " + started.getString("error"), null);
+ }
+ String uri = started.getString("url");
+ if (uri == null) {
+ throw new ToolCallException(
+ "No endpoint matches " + endpoint
+ + " (a pattern matches the endpoints the application sends to; "
+ + "camel_runtime_endpoints lists them)",
+ null);
+ }
+ JsonObject answer = new JsonObject();
+ answer.put("endpoint", uri);
+ StopWatch watch = new StopWatch();
+ while (true) {
+ List<JsonObject> messages = runtimeService.readReceivedMessages(pid, offset);
+ if (!messages.isEmpty()) {
+ answer.put("received", messages.size());
+ answer.put("messages", messages);
+ return answer;
+ }
+ if (watch.taken() >= timeoutMs) {
+ answer.put("received", 0);
+ answer.put("note", "No message arrived within " + (timeoutMs / 1000) + " seconds");
+ return answer;
+ }
+ try {
+ TimeUnit.MILLISECONDS.sleep(RECEIVE_POLL_MS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new ToolCallException("Interrupted while waiting for a message", null);
+ }
+ }
+ } finally {
+ // an action without an endpoint stops the consumers of the receive console
+ runtimeService.executeAction(pid, "receive", null);
Review Comment:
Done in 6676883e9f13: the `finally` is gone; the wait is `awaitMessages` and the stop is `stopReceiving`. When the stop fails after messages arrived, they are returned with a `warning` that names `camel cmd receive --action=stop`; when the receive itself failed and the stop fails too, the error says the consumer could not be stopped and names the command. Tests `receiveReturnsTheMessageWithAWarningWhenTheConsumerCannotBeStopped` and `receiveNamesTheStopCommandWhenItFailsAndCannotStopTheConsumer`.
_Claude Code on behalf of Croway_
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@camel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org