Skip to content

Commit fe7567a

Browse files
author
Mark Pollack
committed
Validate JSON-RPC requests and params as JSON-RPC 2.0 says
A request whose method is not a string was answered -32601; one whose id is an object, or whose jsonrpc is not "2.0", was executed. All three are now -32600 Invalid Request (sections 4 and 5.1), answered with the request's id when it can be read. Over Streamable HTTP such a JSON object is answered on the connection stream, and the HTTP client now answers an SSE event that is no JSON-RPC message, as the stdio and WebSocket transports do. Params the method cannot read (a wrong JSON type, a required field missing) are -32602 Invalid params instead of -32603, on the agent and the client: the new AcpTransport.unmarshalParams checks them, and the default mappers no longer coerce scalars. A notification whose handler fails is logged and skipped; on the agent it used to end the inbound stream. A stray response without an id is logged at WARN, not ERROR. The raw conformance expectations for these cases are removed; the unknown-session SSE stream entry stays (the server keeps the provisional stream, see the routing commit).
1 parent 55e2931 commit fe7567a

24 files changed

Lines changed: 590 additions & 128 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
268268
constructor `StdioAcpAgentTransport(AcpJsonMapper, InputStream, OutputStream, Duration)`; a request
269269
still unanswered then is answered with `-32800` (request cancelled) and the transport terminates
270270
without it. `closeGracefully()` now also completes `awaitTermination()`.
271+
- **JSON-RPC request validation (JSON-RPC 2.0 sections 4 and 5.1), on both sides and every
272+
transport.** A request whose `method` is not a string was answered `-32601` (method not found);
273+
one whose `id` is not a string, number or null (an object, say), or whose `jsonrpc` is not exactly
274+
`"2.0"`, was executed. All three are now answered `-32600` Invalid Request, with the request's id
275+
when it can be read and `null` otherwise (section 5); `AcpSchema.deserializeJsonRpcMessage` refuses
276+
them, and `unreadableMessageResponse` answers them. Over Streamable HTTP a JSON object posted on a
277+
connection that is no valid request is answered on the connection stream with `202`, as the
278+
TypeScript server does; a body that is not a JSON object is still refused with `400`. Params the
279+
method cannot read are now `-32602` Invalid params, message `Invalid params`, with the reason as
280+
`data`, instead of `-32603`, and the handler is not called: a value of the wrong JSON type, and a
281+
required field (a schema record component without `@Nullable`, the schema's `required` list)
282+
that is missing, such as `session/new` without `cwd`. The new `AcpTransport.unmarshalParams`
283+
does this for both the agent's and the client's handlers. A notification whose handler fails
284+
(such params, say) is now logged at WARN and skipped; on the agent the failure used to end the
285+
session's inbound stream, so the connection stopped answering. The Streamable HTTP client now
286+
answers an SSE event that is no JSON-RPC message, in the scope of its stream, as the stdio and
287+
WebSocket transports do; it used to skip it, and the agent waited for an answer.
288+
- **Behaviour change: the default JSON mappers no longer coerce scalars.** `JacksonAcpJsonMapper`
289+
and `Jackson3AcpJsonMapper` read `"cwd": 42` as the string `"42"`, and a string as a number or
290+
boolean; they now refuse a scalar of the wrong JSON type (`ALLOW_COERCION_OF_SCALARS` off, and no
291+
number or boolean to string), so such params are `-32602`.
292+
- **A stray response without an id was logged at ERROR as a bug in this SDK.** A response with no
293+
id and no error answers no request this side sent; it is now logged at WARN.
271294
- **A JSON-RPC error's wire `message` carried the code.** An `AcpProtocolException` thrown by a
272295
handler was answered with the exception's log form as the message, for example
273296
`"message": "[-32602] unknown directive: #nope"`; JSON-RPC 2.0 (section 5.1) keeps the number in

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,15 +89,15 @@ public Mono<Void> start() {
8989
/** Reads the params as the registered request type, then calls the registered handler. */
9090
private <T> AcpAgentSession.RequestHandler<Object> sessionHandler(AgentHandlers.Request<T> registration) {
9191
return params -> {
92-
T request = transport.unmarshalFrom(params, registration.requestType());
92+
T request = transport.unmarshalParams(params, registration.requestType());
9393
recordClientCapabilities(request);
9494
return registration.handler().handle(request, this).cast(Object.class);
9595
};
9696
}
9797

9898
private <T> AcpAgentSession.NotificationHandler sessionHandler(AgentHandlers.Notification<T> registration) {
9999
return params -> registration.handler()
100-
.apply(transport.unmarshalFrom(params, registration.notificationType()));
100+
.apply(transport.unmarshalParams(params, registration.notificationType()));
101101
}
102102

103103
/**

‎acp-core/src/main/java/com/agentclientprotocol/sdk/client/AcpClient.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -479,7 +479,7 @@ public AsyncSpec notificationHandler(String method, AcpClientSession.Notificatio
479479
/** Reads the params as the request type, then calls the handler. */
480480
private <Q, R> AsyncSpec request(String method, TypeRef<Q> requestType, Function<Q, Mono<R>> handler) {
481481
AcpClientSession.RequestHandler<R> rawHandler = params -> handler
482-
.apply(transport.unmarshalFrom(params, requestType));
482+
.apply(transport.unmarshalParams(params, requestType));
483483
this.requestHandlers.put(method, rawHandler);
484484
return this;
485485
}
@@ -493,7 +493,7 @@ public AcpAsyncClient build() {
493493
// Set up session update notification handler
494494
if (!sessionUpdateConsumers.isEmpty()) {
495495
notificationHandlers.put(AcpSchema.METHOD_SESSION_UPDATE, params -> {
496-
AcpSchema.SessionNotification notification = transport.unmarshalFrom(params,
496+
AcpSchema.SessionNotification notification = transport.unmarshalParams(params,
497497
new TypeRef<AcpSchema.SessionNotification>() {
498498
});
499499
logger.debug("Received session update for session: {}", notification.sessionId());

‎acp-core/src/main/java/com/agentclientprotocol/sdk/client/transport/SseStream.java‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,13 @@ interface Listener {
3939
/** Delivers a message read from the stream of {@code scope}. */
4040
Mono<Void> onMessage(RouteScope scope, JSONRPCMessage message);
4141

42-
/** An event that is not a JSON-RPC message was skipped. */
43-
void onUnreadable(Throwable error);
42+
/**
43+
* An event that is not a JSON-RPC message was skipped.
44+
* @param scope the stream it came on
45+
* @param error why it could not be read
46+
* @param data the event's data
47+
*/
48+
void onUnreadable(RouteScope scope, Throwable error, String data);
4449

4550
/** The stream ended, or failed, without having been closed. */
4651
void onUnexpectedClose(SseStream stream, Throwable error);
@@ -179,7 +184,7 @@ private void dispatchEvent(StringBuilder dataBuffer) {
179184
catch (Exception e) {
180185
if (isLive()) {
181186
logger.warn("Skipped an SSE event from {} that is not a JSON-RPC message", scope, e);
182-
listener.onUnreadable(e);
187+
listener.onUnreadable(scope, e, dataBuffer.toString());
183188
}
184189
}
185190
}

‎acp-core/src/main/java/com/agentclientprotocol/sdk/client/transport/StreamableHttpAcpClientTransport.java‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ private StreamableHttpAcpClientTransport(URI endpointUri, AcpJsonMapper jsonMapp
141141
this.routes = new StreamableHttpRoutes(jsonMapper);
142142
this.streams = new StreamableHttpStreams(requests, routes, jsonMapper, options.maxSseStreams(),
143143
new StreamableHttpStreams.Owner(this::processInbound, closing::get, this::terminateAfterSseFailure,
144-
error -> this.exceptionHandler.accept(error)));
144+
error -> this.exceptionHandler.accept(error), this::answerUnreadable));
145145
this.inbound = new StreamableHttpInbound(routes, streams, jsonMapper);
146146
}
147147

@@ -256,6 +256,20 @@ private Mono<Void> post(JSONRPCMessage message, RouteScope scope) {
256256
return requests.postAccepted(scope, json);
257257
}
258258

259+
/**
260+
* Answers an SSE event that is no JSON-RPC message, as JSON-RPC 2.0 says (-32700 or
261+
* -32600, with the request's id when it can be read) and as the stdio and WebSocket
262+
* transports do, in the scope of the stream it came on. The answer names no routed
263+
* request, so it is posted directly.
264+
*/
265+
private void answerUnreadable(RouteScope scope, String data) {
266+
if (closing.get()) {
267+
return;
268+
}
269+
post(AcpSchema.unreadableMessageResponse(jsonMapper, data), scope).subscribe(ignored -> {
270+
}, error -> logger.debug("Could not answer an unreadable SSE event: {}", error.getMessage()));
271+
}
272+
259273
private Mono<Void> processInbound(RouteScope actualScope, JSONRPCMessage message) {
260274
return inbound.process(actualScope, message);
261275
}

‎acp-core/src/main/java/com/agentclientprotocol/sdk/client/transport/StreamableHttpStreams.java‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import java.util.concurrent.ThreadPoolExecutor;
1414
import java.util.concurrent.TimeUnit;
1515
import java.util.concurrent.atomic.AtomicReference;
16+
import java.util.function.BiConsumer;
1617
import java.util.function.BiFunction;
1718
import java.util.function.BooleanSupplier;
1819
import java.util.function.Consumer;
@@ -69,9 +70,11 @@ final class StreamableHttpStreams {
6970
* @param closing whether the transport is closing
7071
* @param onFailure ends the transport after a stream failure it cannot recover from
7172
* @param onError reports an error the streams recover from, such as a skipped event
73+
* @param answerUnreadable answers a skipped event, posted in the scope of its stream
7274
*/
7375
record Owner(BiFunction<RouteScope, JSONRPCMessage, Mono<Void>> inbound, BooleanSupplier closing,
74-
Consumer<Throwable> onFailure, Consumer<Throwable> onError) {
76+
Consumer<Throwable> onFailure, Consumer<Throwable> onError,
77+
BiConsumer<RouteScope, String> answerUnreadable) {
7578
}
7679

7780
StreamableHttpStreams(StreamableHttpRequests requests, StreamableHttpRoutes routes, AcpJsonMapper jsonMapper,
@@ -92,8 +95,9 @@ public Mono<Void> onMessage(RouteScope scope, JSONRPCMessage message) {
9295
}
9396

9497
@Override
95-
public void onUnreadable(Throwable error) {
98+
public void onUnreadable(RouteScope scope, Throwable error, String data) {
9699
owner.onError().accept(error);
100+
owner.answerUnreadable().accept(scope, data);
97101
}
98102

99103
@Override

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

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,49 @@ public static JSONRPCResponse unreadableMessageResponse(AcpJsonMapper jsonMapper
160160
}
161161
JSONRPCError error = isJson ? new JSONRPCError(AcpErrorCodes.INVALID_REQUEST, "Invalid Request", null)
162162
: new JSONRPCError(AcpErrorCodes.PARSE_ERROR, "Parse error", null);
163-
return new JSONRPCResponse(JSONRPC_VERSION, null, null, error);
163+
return new JSONRPCResponse(JSONRPC_VERSION, isJson ? readableRequestId(jsonMapper, jsonText) : null, null,
164+
error);
165+
}
166+
167+
/**
168+
* The id of an invalid request, when it can be read: JSON-RPC 2.0 section 5 answers with
169+
* null only when the id could not be detected. Only a message with a method is a request;
170+
* an unreadable response is never answered with its own id.
171+
*/
172+
private static @Nullable Object readableRequestId(AcpJsonMapper jsonMapper, String jsonText) {
173+
try {
174+
Map<String, Object> map = jsonMapper.readValue(jsonText, MAP_TYPE_REF);
175+
if (map == null || !map.containsKey("method")) {
176+
return null;
177+
}
178+
Object id = map.get("id");
179+
return isValidId(id) ? id : null;
180+
}
181+
catch (IOException | RuntimeException e) {
182+
return null;
183+
}
184+
}
185+
186+
/** JSON-RPC 2.0 section 4: an id is a string, a number or null. */
187+
private static boolean isValidId(@Nullable Object id) {
188+
return id == null || id instanceof String || id instanceof Number;
189+
}
190+
191+
/**
192+
* Refuses a request or notification that JSON-RPC 2.0 section 4 does not allow:
193+
* {@code jsonrpc} other than "2.0", a method that is not a string, or an id that is not a
194+
* string, number or null. Its answer is -32600 Invalid Request.
195+
*/
196+
private static void validateRequest(Map<String, Object> message, String jsonText) {
197+
if (!JSONRPC_VERSION.equals(message.get("jsonrpc"))) {
198+
throw new IllegalArgumentException("Invalid Request: jsonrpc must be \"2.0\": " + jsonText);
199+
}
200+
if (!(message.get("method") instanceof String)) {
201+
throw new IllegalArgumentException("Invalid Request: method must be a string: " + jsonText);
202+
}
203+
if (!isValidId(message.get("id"))) {
204+
throw new IllegalArgumentException("Invalid Request: id must be a string, number or null: " + jsonText);
205+
}
164206
}
165207

166208
/**
@@ -171,7 +213,9 @@ public static JSONRPCResponse unreadableMessageResponse(AcpJsonMapper jsonMapper
171213
* @return The deserialized JSON-RPC message
172214
* @throws IOException If deserialization fails
173215
* @throws IllegalArgumentException If the JSON structure doesn't match any known
174-
* message type
216+
* message type, or is a request JSON-RPC 2.0 does not allow (section 4: {@code jsonrpc}
217+
* other than "2.0", a method that is not a string, an id that is not a string, number or
218+
* null)
175219
*/
176220
public static JSONRPCMessage deserializeJsonRpcMessage(AcpJsonMapper jsonMapper, String jsonText)
177221
throws IOException {
@@ -190,6 +234,9 @@ public static JSONRPCMessage deserializeJsonRpcMessage(AcpJsonMapper jsonMapper,
190234
throw new IllegalArgumentException(
191235
"Cannot deserialize JSONRPCMessage: a JSON object with no method, id, result or error");
192236
}
237+
if (messageType != JSONRPCResponse.class) {
238+
validateRequest(map, jsonText);
239+
}
193240
return jsonMapper.convertValue(map, messageType);
194241
}
195242

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

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,11 @@
66

77
import java.util.List;
88

9+
import com.agentclientprotocol.sdk.error.AcpErrorCodes;
10+
import com.agentclientprotocol.sdk.error.AcpProtocolException;
911
import com.agentclientprotocol.sdk.spec.AcpSchema.JSONRPCMessage;
1012
import com.agentclientprotocol.sdk.json.TypeRef;
13+
import org.jspecify.annotations.Nullable;
1114
import reactor.core.publisher.Mono;
1215

1316
/**
@@ -79,6 +82,41 @@ default void close() {
7982
*/
8083
<T> T unmarshalFrom(Object data, TypeRef<T> typeRef);
8184

85+
/**
86+
* Reads the params of an inbound request or notification as the method's type. Params
87+
* the type cannot be read from (a value of the wrong JSON type, a required field
88+
* missing) are a JSON-RPC 2.0 -32602 Invalid params error (section 5.1), not an
89+
* internal error.
90+
* @param <T> the params type
91+
* @param params the params as received
92+
* @param typeRef the method's params type
93+
* @return the params as that type
94+
* @throws AcpProtocolException with code -32602 when they cannot be read as it
95+
*/
96+
default <T> T unmarshalParams(Object params, TypeRef<T> typeRef) {
97+
T value;
98+
try {
99+
value = unmarshalFrom(params, typeRef);
100+
}
101+
catch (IllegalArgumentException e) {
102+
throw new AcpProtocolException(AcpErrorCodes.INVALID_PARAMS, "Invalid params", firstLine(e.getMessage()));
103+
}
104+
String missing = RequiredFields.firstMissing(value);
105+
if (missing != null) {
106+
throw new AcpProtocolException(AcpErrorCodes.INVALID_PARAMS, "Invalid params",
107+
"missing required field: " + missing);
108+
}
109+
return value;
110+
}
111+
112+
private static @Nullable String firstLine(@Nullable String message) {
113+
if (message == null) {
114+
return null;
115+
}
116+
int end = message.indexOf('\n');
117+
return end < 0 ? message : message.substring(0, end);
118+
}
119+
82120
/**
83121
* Returns the list of protocol versions supported by this transport.
84122
* @return list of supported protocol versions

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

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,9 @@ static Object paramsOrEmpty(@Nullable Object params) {
3232
}
3333

3434
/**
35-
* Passes a notification to the handler registered for its method. One without a handler
36-
* is ignored with a warning that names its method only: its params can carry personal
35+
* Passes a notification to the handler registered for its method; a handler that fails
36+
* (params it cannot read, say) is logged and skipped. One without a handler is ignored
37+
* with a warning that names its method only: its params can carry personal
3738
* data (agents send {@code _auth/status_update}, whose params carry the account's email
3839
* address).
3940
*/
@@ -44,7 +45,13 @@ static <H> Mono<Void> deliver(Logger logger, AcpSchema.JSONRPCNotification notif
4445
logger.warn("No handler registered for notification method: {}", notification.method());
4546
return Mono.empty();
4647
}
47-
return handle.apply(handler, paramsOrEmpty(notification.params()));
48+
// A notification has no answer to carry a failure: it is logged (method and error
49+
// only) and the session reads on. A failure must not end the inbound stream.
50+
return Mono.defer(() -> handle.apply(handler, paramsOrEmpty(notification.params())))
51+
.onErrorResume(error -> {
52+
logger.warn("Notification {} failed and was skipped: {}", notification.method(), error.toString());
53+
return Mono.empty();
54+
});
4855
}
4956

5057
/** A request always gets a response: a handler that completes empty is answered with an error. */

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

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,9 +89,8 @@ void complete(AcpSchema.JSONRPCResponse response) {
8989
return;
9090
}
9191
if (response.id() == null) {
92-
logger.error("Discarded ACP request response without session id. "
93-
+ "This is an indication of a bug in the request sender code that can lead to memory "
94-
+ "leaks as pending requests will never be completed.");
92+
// A stray response: it names no request, so it answers nothing this side sent.
93+
logger.warn("Discarded a response from the {} without an id: it answers no request", this.peer);
9594
return;
9695
}
9796
MonoSink<AcpSchema.JSONRPCResponse> sink = this.pending.remove(response.id());

0 commit comments

Comments
 (0)