Skip to content

Commit 6a70ae1

Browse files
author
Mark Pollack
committed
Log a peer's error by its code above DEBUG, not its message and data
An error answer's message and data are the peer's own text. Three WARN lines carried them: a peer's error report for a message it could not read (PendingResponses), a notification handler that failed with the peer's AcpError (InboundMessages), and a failed terminal/release of a cancelled execute (DefaultPromptContext). Each now logs the code and the SDK's name for it; the peer's message and data are logged at DEBUG.
1 parent cc6414d commit 6a70ae1

7 files changed

Lines changed: 165 additions & 4 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
5656
when the connect failed; a token in the query string (`?token=...`) or a password in the URI
5757
reached the log. It now logs scheme, host, port and path.
5858

59+
- **A peer's error message and data are no longer logged above DEBUG.** An error answer is the
60+
peer's own text. Three log lines at WARN carried it: a peer's error report for a message it could
61+
not read (`PendingResponses`), a notification handler that failed with the peer's `AcpError`, and
62+
a failed `terminal/release` of a cancelled `execute`. Each now logs the error code and the SDK's
63+
name for it (`-32603 Internal error`); the peer's message and data are logged at DEBUG.
64+
5965
- **A handler's unexpected exception no longer sends its message to the peer.** A request handler
6066
that failed with an exception other than `AcpProtocolException` was answered `-32603` with the
6167
exception's message, which can carry paths, SQL, URLs with credentials or tokens. It is now

‎acp-core/src/main/java/com/agentclientprotocol/sdk/agent/DefaultPromptContext.java‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import java.util.function.BooleanSupplier;
1313

1414
import com.agentclientprotocol.sdk.capabilities.NegotiatedCapabilities;
15+
import com.agentclientprotocol.sdk.error.AcpErrorCodes;
1516
import com.agentclientprotocol.sdk.spec.AcpError;
1617
import com.agentclientprotocol.sdk.spec.AcpSchema;
1718
import com.agentclientprotocol.sdk.spec.AcpSchema.AgentMessageChunk;
@@ -263,9 +264,23 @@ public Mono<CommandResult> execute(Command command) {
263264
.onErrorResume(error -> release.then(Mono.error(error)))
264265
// Cancelled: nobody waits for the release any more, so send it on its own
265266
.doOnCancel(() -> release.subscribe(v -> {
266-
}, error -> logger.warn("Could not release terminal {} of a cancelled command: {}",
267-
terminalId, error.getMessage())));
267+
}, error -> logReleaseFailure(terminalId, error)));
268268
});
269269
}
270270

271+
/**
272+
* A client's error answer is logged at WARN by its code and the SDK's description of it:
273+
* the client's message and data are its own text, logged at DEBUG only.
274+
*/
275+
private static void logReleaseFailure(String terminalId, Throwable error) {
276+
if (error instanceof AcpError clientError) {
277+
logger.warn("Could not release terminal {} of a cancelled command: the client answered {} {}", terminalId,
278+
clientError.getCode(), AcpErrorCodes.getDescription(clientError.getCode()));
279+
logger.debug("Could not release terminal {}: {}", terminalId, clientError.toString());
280+
}
281+
else {
282+
logger.warn("Could not release terminal {} of a cancelled command: {}", terminalId, error.getMessage());
283+
}
284+
}
285+
271286
}

‎acp-core/src/main/java/com/agentclientprotocol/sdk/spec/InboundMessages.java‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,13 @@ static <H> Mono<Void> deliver(Logger logger, AcpSchema.JSONRPCNotification notif
7272
LOGGER.error("Notification {} handler failed with an error and was skipped",
7373
notification.method(), failure.getCause());
7474
}
75+
else if (error instanceof AcpError peerError) {
76+
// The peer's answer to a call the handler made: its message and data are the
77+
// peer's text, logged at DEBUG only.
78+
logger.warn("Notification {} failed and was skipped: the peer answered {} {}",
79+
notification.method(), peerError.getCode(), AcpErrorCodes.getDescription(peerError.getCode()));
80+
logger.debug("Notification {} failed: {}", notification.method(), peerError.toString());
81+
}
7582
else {
7683
logger.warn("Notification {} failed and was skipped: {}", notification.method(), error.toString());
7784
}

‎acp-core/src/main/java/com/agentclientprotocol/sdk/spec/PendingResponses.java‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import java.util.function.Supplier;
1515

1616
import com.agentclientprotocol.sdk.error.AcpConnectionException;
17+
import com.agentclientprotocol.sdk.error.AcpErrorCodes;
1718
import org.jspecify.annotations.Nullable;
1819
import org.slf4j.Logger;
1920
import org.slf4j.LoggerFactory;
@@ -141,9 +142,11 @@ void complete(AcpSchema.JSONRPCResponse response) {
141142
logger.debug("Received response for id {}", response.id());
142143
AcpSchema.JSONRPCError error = response.error();
143144
if (response.id() == null && error != null) {
144-
// JSON-RPC 2.0: the answer to a message whose id could not be read.
145+
// JSON-RPC 2.0: the answer to a message whose id could not be read. The peer's
146+
// message and data are its own text: logged at DEBUG only.
145147
logger.warn("The {} reported an error for a message it could not read: {} {}", this.peer, error.code(),
146-
error.message());
148+
AcpErrorCodes.getDescription(error.code()));
149+
logger.debug("The {}'s error: {} {}", this.peer, error.message(), error.data());
147150
return;
148151
}
149152
if (response.id() == null) {

‎acp-core/src/test/java/com/agentclientprotocol/sdk/agent/PromptContextHelpersTest.java‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import java.util.concurrent.TimeUnit;
1313
import java.util.concurrent.atomic.AtomicReference;
1414

15+
import com.agentclientprotocol.sdk.CapturedLogs;
1516
import com.agentclientprotocol.sdk.client.AcpAsyncClient;
1617
import com.agentclientprotocol.sdk.client.AcpClient;
1718
import com.agentclientprotocol.sdk.error.AcpProtocolException;
@@ -110,6 +111,66 @@ void executeCancelledWhileWaitingForExitReleasesTheTerminal_terminalsMdxMustRele
110111
agent.closeGracefully().block(TIMEOUT);
111112
}
112113

114+
/**
115+
* A release that the client answers with an error is logged at WARN by its code and the
116+
* SDK's description of the code: the client's message and data are its own text and stay
117+
* at DEBUG.
118+
*/
119+
@Test
120+
void aFailedReleaseOfACancelledCommandIsLoggedWithoutTheClientsMessageOrData() throws Exception {
121+
CountDownLatch created = new CountDownLatch(1);
122+
123+
AcpAsyncAgent agent = AcpAgent.async(this.transportPair.agentTransport())
124+
.requestTimeout(TIMEOUT)
125+
.initializeHandler(req -> Mono.just(InitializeResponse.ok()))
126+
.newSessionHandler(req -> Mono.just(new NewSessionResponse("s1", null, null)))
127+
.promptHandler((request, context) -> context.execute("sleep", "600").thenReturn(PromptResponse.endTurn()))
128+
.build();
129+
130+
AcpAsyncClient client = AcpClient.async(this.transportPair.clientTransport())
131+
.requestTimeout(TIMEOUT)
132+
.clientCapabilities(new ClientCapabilities(null, true))
133+
.createTerminalHandler(req -> {
134+
created.countDown();
135+
return Mono.just(new CreateTerminalResponse("term-1"));
136+
})
137+
.waitForTerminalExitHandler(req -> Mono.never())
138+
.terminalOutputHandler(req -> Mono.never())
139+
.releaseTerminalHandler(req -> Mono.error(new AcpProtocolException(AcpErrorCodes.RESOURCE_NOT_FOUND,
140+
"MESSAGE-SECRET", Map.of("details", "DATA-SECRET"))))
141+
.killTerminalHandler(req -> Mono.just(new AcpSchema.KillTerminalCommandResponse()))
142+
.build();
143+
144+
try (CapturedLogs logs = CapturedLogs.open()) {
145+
agent.start().block(TIMEOUT);
146+
connect(client);
147+
148+
Disposable turn = client.prompt(prompt()).subscribe(r -> {
149+
}, e -> {
150+
});
151+
assertThat(created.await(5, TimeUnit.SECONDS)).as("terminal/create").isTrue();
152+
Thread.sleep(200);
153+
turn.dispose();
154+
155+
long deadline = System.nanoTime() + TIMEOUT.toNanos();
156+
while (logs.events()
157+
.stream()
158+
.noneMatch(e -> e.getFormattedMessage().contains("of a cancelled command"))
159+
&& System.nanoTime() < deadline) {
160+
Thread.sleep(20);
161+
}
162+
assertThat(logs.events()).filteredOn(e -> e.getLevel() == ch.qos.logback.classic.Level.WARN)
163+
.filteredOn(e -> e.getFormattedMessage().contains("Could not release terminal"))
164+
.singleElement()
165+
.satisfies(e -> assertThat(e.getFormattedMessage()).contains("-32002").contains("Resource not found"));
166+
logs.assertNoneAtInfoOrAboveContains("MESSAGE-SECRET");
167+
logs.assertNoneAtInfoOrAboveContains("DATA-SECRET");
168+
}
169+
170+
client.closeGracefully().block(TIMEOUT);
171+
agent.closeGracefully().block(TIMEOUT);
172+
}
173+
113174
/** The same for a sync handler: cancelling the prompt interrupts it in {@code execute}. */
114175
@Test
115176
void syncExecuteCancelledWhileWaitingForExitReleasesTheTerminal_terminalsMdxMustRelease() throws Exception {
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
* Copyright 2026-2026 the original author or authors.
3+
*/
4+
5+
package com.agentclientprotocol.sdk.spec;
6+
7+
import java.util.Map;
8+
import java.util.function.BiFunction;
9+
10+
import com.agentclientprotocol.sdk.CapturedLogs;
11+
import org.junit.jupiter.api.Test;
12+
import org.slf4j.LoggerFactory;
13+
import reactor.core.publisher.Mono;
14+
15+
import static org.assertj.core.api.Assertions.assertThat;
16+
17+
/**
18+
* How {@link InboundMessages} logs a notification whose handler failed.
19+
*/
20+
class InboundMessagesLogTest {
21+
22+
/**
23+
* A notification handler that called the peer and let its {@link AcpError} escape: the
24+
* error's message and data are the peer's text, so at INFO and above the failure is
25+
* logged by its code and the SDK's description of the code only.
26+
*/
27+
@Test
28+
void anEscapedAcpErrorIsLoggedWithoutThePeersMessageOrDataAboveDebug() {
29+
AcpError peerError = new AcpError(
30+
new AcpSchema.JSONRPCError(-32603, "MESSAGE-SECRET", Map.of("details", "DATA-SECRET")));
31+
BiFunction<String, Object, Mono<Void>> handle = (handler, params) -> Mono.error(peerError);
32+
33+
try (CapturedLogs logs = CapturedLogs.open()) {
34+
InboundMessages
35+
.deliver(LoggerFactory.getLogger(AcpClientSession.class),
36+
new AcpSchema.JSONRPCNotification("session/update", Map.of()), Map.of("session/update", "h"),
37+
handle)
38+
.block();
39+
40+
assertThat(logs.events()).anySatisfy(event -> assertThat(event.getFormattedMessage())
41+
.contains("session/update")
42+
.contains("-32603")
43+
.contains("Internal error"));
44+
logs.assertNoneAtInfoOrAboveContains("MESSAGE-SECRET");
45+
logs.assertNoneAtInfoOrAboveContains("DATA-SECRET");
46+
}
47+
}
48+
49+
}

‎acp-core/src/test/java/com/agentclientprotocol/sdk/spec/PendingResponsesLogTest.java‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,4 +79,24 @@ void aResponseWithoutAnIdIsLoggedAtWarn() {
7979
});
8080
}
8181

82+
/**
83+
* The peer's error message and data are its own text and can carry anything: at INFO and
84+
* above the error is logged by its code and the SDK's description of the code; the
85+
* message and data stay at DEBUG.
86+
*/
87+
@Test
88+
void aNullIdErrorIsLoggedWithoutThePeersMessageOrDataAboveDebug() {
89+
PendingResponses pending = new PendingResponses(() -> null, RuntimeException::new, "agent");
90+
91+
pending.complete(new AcpSchema.JSONRPCResponse(AcpSchema.JSONRPC_VERSION, null, null,
92+
new AcpSchema.JSONRPCError(-32600, "MESSAGE-SECRET", java.util.Map.of("details", "DATA-SECRET"))));
93+
94+
assertThat(this.appender.list).filteredOn(event -> event.getLevel().isGreaterOrEqual(Level.INFO))
95+
.singleElement()
96+
.satisfies(event -> assertThat(event.getFormattedMessage()).contains("-32600")
97+
.contains("Invalid request")
98+
.doesNotContain("MESSAGE-SECRET")
99+
.doesNotContain("DATA-SECRET"));
100+
}
101+
82102
}

0 commit comments

Comments
 (0)