Skip to content

Commit 5539dec

Browse files
committed
Remove aggregate exception from JSONRPCErrorResponse, log instead
Signed-off-by: Daniel Garnier-Moiroux <git@garnier.wf>
1 parent 52df971 commit 5539dec

5 files changed

Lines changed: 80 additions & 64 deletions

File tree

‎mcp-core/src/main/java/io/modelcontextprotocol/spec/McpClientSession.java‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -153,10 +153,17 @@ else if (message instanceof McpSchema.JSONRPCRequest request) {
153153
logger.debug("Received request: {}", request);
154154
handleIncomingRequest(request).onErrorResume(error -> {
155155

156-
McpSchema.JSONRPCResponse.JSONRPCError jsonRpcError = (error instanceof McpError mcpError
157-
&& mcpError.getJsonRpcError() != null) ? mcpError.getJsonRpcError()
158-
: new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,
159-
error.getMessage(), McpError.aggregateExceptionMessages(error));
156+
McpSchema.JSONRPCResponse.JSONRPCError jsonRpcError;
157+
if (error instanceof McpError mcpError && mcpError.getJsonRpcError() != null) {
158+
jsonRpcError = mcpError.getJsonRpcError();
159+
}
160+
else {
161+
// The cause chain may contain internal details: log it, but only send
162+
// the message to the server
163+
logger.warn("Error handling request {} [{}]", request.id(), request.method(), error);
164+
jsonRpcError = new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,
165+
error.getMessage(), null);
166+
}
160167

161168
var errorResponse = McpSchema.JSONRPCResponse.error(request.id(), jsonRpcError);
162169
return Mono.just(errorResponse);

‎mcp-core/src/main/java/io/modelcontextprotocol/spec/McpServerSession.java‎

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -242,10 +242,7 @@ public Mono<Void> handle(McpSchema.JSONRPCMessage message) {
242242
else if (message instanceof McpSchema.JSONRPCRequest request) {
243243
logger.debug("Received request: {}", request);
244244
return handleIncomingRequest(request, transportContext).onErrorResume(error -> {
245-
McpSchema.JSONRPCResponse.JSONRPCError jsonRpcError = (error instanceof McpError mcpError
246-
&& mcpError.getJsonRpcError() != null) ? mcpError.getJsonRpcError()
247-
: new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,
248-
error.getMessage(), McpError.aggregateExceptionMessages(error));
245+
McpSchema.JSONRPCResponse.JSONRPCError jsonRpcError = toJsonRpcError(request, error);
249246
var errorResponse = McpSchema.JSONRPCResponse.error(request.id(), jsonRpcError);
250247
// TODO: Should the error go to SSE or back as POST return?
251248
return this.transport.sendMessage(errorResponse).then(Mono.empty());
@@ -301,16 +298,28 @@ private Mono<McpSchema.JSONRPCResponse> handleIncomingRequest(McpSchema.JSONRPCR
301298
.flatMap(exchange -> handler.handle(copyExchange(exchange, transportContext), request.params()));
302299
}
303300
return resultMono.map(result -> McpSchema.JSONRPCResponse.result(request.id(), result))
304-
.onErrorResume(error -> {
305-
McpSchema.JSONRPCResponse.JSONRPCError jsonRpcError = (error instanceof McpError mcpError
306-
&& mcpError.getJsonRpcError() != null) ? mcpError.getJsonRpcError()
307-
: new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,
308-
error.getMessage(), McpError.aggregateExceptionMessages(error));
309-
return Mono.just(McpSchema.JSONRPCResponse.error(request.id(), jsonRpcError));
310-
});
301+
.onErrorResume(error -> Mono
302+
.just(McpSchema.JSONRPCResponse.error(request.id(), toJsonRpcError(request, error))));
311303
});
312304
}
313305

306+
/**
307+
* Converts a request handler failure into the JSON-RPC error sent to the client.
308+
* Errors other than {@link McpError} are logged, and only their message is sent:
309+
* their cause chain may contain internal details that must not reach the client.
310+
* @param request the request that failed
311+
* @param error the failure
312+
* @return the JSON-RPC error to send to the client
313+
*/
314+
private McpSchema.JSONRPCResponse.JSONRPCError toJsonRpcError(McpSchema.JSONRPCRequest request, Throwable error) {
315+
if (error instanceof McpError mcpError && mcpError.getJsonRpcError() != null) {
316+
return mcpError.getJsonRpcError();
317+
}
318+
logger.warn("Error handling request {} [{}]", request.id(), request.method(), error);
319+
return new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR, error.getMessage(),
320+
null);
321+
}
322+
314323
/**
315324
* Handles an incoming JSON-RPC notification by routing it to the appropriate handler.
316325
* @param notification The incoming JSON-RPC notification

‎mcp-core/src/main/java/io/modelcontextprotocol/spec/McpStreamableServerSession.java‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -530,12 +530,18 @@ public Mono<Void> handle(McpSchema.JSONRPCRequest jsonrpcRequest) {
530530
McpStreamableServerSession.this.jsonSchemaValidator), jsonrpcRequest.params())
531531
.map(result -> McpSchema.JSONRPCResponse.result(jsonrpcRequest.id(), result))
532532
.onErrorResume(e -> {
533-
McpSchema.JSONRPCResponse.JSONRPCError jsonRpcError = (e instanceof McpError mcpError
534-
&& mcpError.getJsonRpcError() != null)
535-
? mcpError.getJsonRpcError()
536-
: new McpSchema.JSONRPCResponse.JSONRPCError(
537-
McpSchema.ErrorCodes.INTERNAL_ERROR, e.getMessage(),
538-
McpError.aggregateExceptionMessages(e));
533+
McpSchema.JSONRPCResponse.JSONRPCError jsonRpcError;
534+
if (e instanceof McpError mcpError && mcpError.getJsonRpcError() != null) {
535+
jsonRpcError = mcpError.getJsonRpcError();
536+
}
537+
else {
538+
// The cause chain may contain internal details: log it,
539+
// but only send the message to the client
540+
logger.warn("Error handling request {} [{}]", jsonrpcRequest.id(), jsonrpcRequest.method(),
541+
e);
542+
jsonRpcError = new McpSchema.JSONRPCResponse.JSONRPCError(
543+
McpSchema.ErrorCodes.INTERNAL_ERROR, e.getMessage(), null);
544+
}
539545

540546
var errorResponse = McpSchema.JSONRPCResponse.error(jsonrpcRequest.id(), jsonRpcError);
541547
return Mono.just(errorResponse);

‎mcp-core/src/test/java/io/modelcontextprotocol/spec/McpClientSessionTests.java‎

Lines changed: 2 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -240,55 +240,14 @@ void testRequestHandlerThrowsGenericException() {
240240
McpSchema.JSONRPCRequest request = new McpSchema.JSONRPCRequest(testMethod, "test-id");
241241
transport.simulateIncomingMessage(request);
242242

243-
// Verify: The response should contain INTERNAL_ERROR with aggregated exception
244-
// messages in data field
243+
// Verify: The response should contain INTERNAL_ERROR with the exception message
245244
McpSchema.JSONRPCMessage sentMessage = transport.getLastSentMessage();
246245
assertThat(sentMessage).isInstanceOf(McpSchema.JSONRPCResponse.class);
247246
McpSchema.JSONRPCResponse response = (McpSchema.JSONRPCResponse) sentMessage;
248247
assertThat(response.error()).isNotNull();
249248
assertThat(response.error().code()).isEqualTo(McpSchema.ErrorCodes.INTERNAL_ERROR);
250249
assertThat(response.error().message()).isEqualTo("Something went wrong");
251-
// Verify data field contains aggregated exception messages
252-
assertThat(response.error().data()).isNotNull();
253-
assertThat(response.error().data().toString()).contains("RuntimeException");
254-
assertThat(response.error().data().toString()).contains("Something went wrong");
255-
256-
session.close();
257-
}
258-
259-
@Test
260-
void testRequestHandlerThrowsExceptionWithCause() {
261-
// Setup: Create a request handler that throws an exception with a cause chain
262-
String testMethod = "test.chainedError";
263-
RuntimeException rootCause = new IllegalArgumentException("Root cause message");
264-
RuntimeException middleCause = new IllegalStateException("Middle cause message", rootCause);
265-
RuntimeException topException = new RuntimeException("Top level message", middleCause);
266-
McpClientSession.RequestHandler<?> failingHandler = params -> Mono.error(topException);
267-
268-
var transport = new MockMcpClientTransport();
269-
var session = new McpClientSession(TIMEOUT, transport, Map.of(testMethod, failingHandler), Map.of(),
270-
Function.identity());
271-
272-
// Simulate incoming request that will trigger the error
273-
McpSchema.JSONRPCRequest request = new McpSchema.JSONRPCRequest(testMethod, "test-id");
274-
transport.simulateIncomingMessage(request);
275-
276-
// Verify: The response should contain INTERNAL_ERROR with full exception chain
277-
// in data field
278-
McpSchema.JSONRPCMessage sentMessage = transport.getLastSentMessage();
279-
assertThat(sentMessage).isInstanceOf(McpSchema.JSONRPCResponse.class);
280-
McpSchema.JSONRPCResponse response = (McpSchema.JSONRPCResponse) sentMessage;
281-
assertThat(response.error()).isNotNull();
282-
assertThat(response.error().code()).isEqualTo(McpSchema.ErrorCodes.INTERNAL_ERROR);
283-
assertThat(response.error().message()).isEqualTo("Top level message");
284-
// Verify data field contains the full exception chain
285-
String dataString = response.error().data().toString();
286-
assertThat(dataString).contains("RuntimeException");
287-
assertThat(dataString).contains("Top level message");
288-
assertThat(dataString).contains("IllegalStateException");
289-
assertThat(dataString).contains("Middle cause message");
290-
assertThat(dataString).contains("IllegalArgumentException");
291-
assertThat(dataString).contains("Root cause message");
250+
assertThat(response.error().data()).isNull();
292251

293252
session.close();
294253
}

‎mcp-test/src/main/java/io/modelcontextprotocol/AbstractMcpClientServerIntegrationTests.java‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1066,6 +1066,41 @@ void testElicitationRequiredError(String clientType) throws InterruptedException
10661066
}
10671067
}
10681068

1069+
@ParameterizedTest(name = "{0} : {displayName} ")
1070+
@MethodSource("clientsForTesting")
1071+
void testToolErrorDoesNotSendCauseChain(String clientType) {
1072+
1073+
var clientBuilder = clientBuilders.get(clientType);
1074+
1075+
McpServerFeatures.AsyncToolSpecification tool = McpServerFeatures.AsyncToolSpecification.builder()
1076+
.tool(Tool.builder("tool1", EMPTY_JSON_SCHEMA).description("tool1 description").build())
1077+
.callHandler((exchange,
1078+
request) -> Mono.error(new IllegalStateException("Tool failed",
1079+
new IllegalArgumentException("connect to db.internal:5432 failed"))))
1080+
.build();
1081+
1082+
var mcpServer = prepareAsyncServerBuilder().serverInfo("test-server", "1.0.0").tools(tool).build();
1083+
1084+
try (var mcpClient = clientBuilder
1085+
.clientInfo(McpSchema.Implementation.builder("Sample client", "0.0.0").build())
1086+
.build()) {
1087+
1088+
assertThatThrownBy(
1089+
() -> mcpClient.callTool(McpSchema.CallToolRequest.builder("tool1").arguments(Map.of()).build()))
1090+
.isInstanceOf(McpError.class)
1091+
.extracting("jsonRpcError")
1092+
.asInstanceOf(type(McpSchema.JSONRPCResponse.JSONRPCError.class))
1093+
.satisfies(error -> {
1094+
assertThat(error.code()).isEqualTo(McpSchema.ErrorCodes.INTERNAL_ERROR);
1095+
assertThat(error.message()).isEqualTo("Tool failed");
1096+
assertThat(error.data()).isNull();
1097+
});
1098+
}
1099+
finally {
1100+
mcpServer.closeGracefully().block();
1101+
}
1102+
}
1103+
10691104
// ---------------------------------------
10701105
// Roots Tests
10711106
// ---------------------------------------

0 commit comments

Comments
 (0)