Skip to content

Commit 3b232c0

Browse files
authored
Remove aggregate exception from JSONRPCErrorResponse, log instead (#1184)
Backport #1182 (cherry picked from commit 7aa05da) Signed-off-by: Daniel Garnier-Moiroux <git@garnier.wf>
1 parent 6e82adb commit 3b232c0

7 files changed

Lines changed: 162 additions & 47 deletions

File tree

‎mcp-core/src/main/java/io/modelcontextprotocol/server/DefaultMcpStatelessServerHandler.java‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import reactor.core.publisher.Mono;
1313

1414
import java.util.Map;
15+
import java.util.Objects;
1516

1617
class DefaultMcpStatelessServerHandler implements McpStatelessServerHandler {
1718

@@ -44,8 +45,11 @@ public Mono<McpSchema.JSONRPCResponse> handleRequest(McpTransportContext transpo
4445
error = mcpError.getJsonRpcError();
4546
}
4647
else {
48+
// The cause chain may contain internal details: log it, but only send
49+
// the message to the client
50+
logger.warn("Error handling request {} [{}]", request.id(), request.method(), t);
4751
error = new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,
48-
t.getMessage(), null);
52+
Objects.requireNonNullElse(t.getMessage(), "Internal error"), null);
4953
}
5054
return Mono.just(new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, request.id(), null, error));
5155
});

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

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
import java.time.Duration;
1616
import java.util.Map;
17+
import java.util.Objects;
1718
import java.util.UUID;
1819
import java.util.concurrent.ConcurrentHashMap;
1920
import java.util.concurrent.atomic.AtomicLong;
@@ -167,11 +168,17 @@ else if (message instanceof McpSchema.JSONRPCRequest request) {
167168
logger.debug("Received request: {}", request);
168169
handleIncomingRequest(request).onErrorResume(error -> {
169170

170-
McpSchema.JSONRPCResponse.JSONRPCError jsonRpcError = (error instanceof McpError mcpError
171-
&& mcpError.getJsonRpcError() != null) ? mcpError.getJsonRpcError()
172-
// TODO: add error message through the data field
173-
: new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,
174-
error.getMessage(), McpError.aggregateExceptionMessages(error));
171+
McpSchema.JSONRPCResponse.JSONRPCError jsonRpcError;
172+
if (error instanceof McpError mcpError && mcpError.getJsonRpcError() != null) {
173+
jsonRpcError = mcpError.getJsonRpcError();
174+
}
175+
else {
176+
// The cause chain may contain internal details: log it, but only send
177+
// the message to the server
178+
logger.warn("Error handling request {} [{}]", request.id(), request.method(), error);
179+
jsonRpcError = new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,
180+
Objects.requireNonNullElse(error.getMessage(), "Internal error"), null);
181+
}
175182

176183
var errorResponse = new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, request.id(), null,
177184
jsonRpcError);

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

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
import java.time.Duration;
88
import java.util.Map;
9+
import java.util.Objects;
910
import java.util.concurrent.ConcurrentHashMap;
1011
import java.util.concurrent.atomic.AtomicInteger;
1112
import java.util.concurrent.atomic.AtomicLong;
@@ -224,10 +225,7 @@ public Mono<Void> handle(McpSchema.JSONRPCMessage message) {
224225
else if (message instanceof McpSchema.JSONRPCRequest request) {
225226
logger.debug("Received request: {}", request);
226227
return handleIncomingRequest(request, transportContext).onErrorResume(error -> {
227-
McpSchema.JSONRPCResponse.JSONRPCError jsonRpcError = (error instanceof McpError mcpError
228-
&& mcpError.getJsonRpcError() != null) ? mcpError.getJsonRpcError()
229-
: new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,
230-
error.getMessage(), McpError.aggregateExceptionMessages(error));
228+
McpSchema.JSONRPCResponse.JSONRPCError jsonRpcError = toJsonRpcError(request, error);
231229
var errorResponse = new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, request.id(), null,
232230
jsonRpcError);
233231
// TODO: Should the error go to SSE or back as POST return?
@@ -285,18 +283,28 @@ private Mono<McpSchema.JSONRPCResponse> handleIncomingRequest(McpSchema.JSONRPCR
285283
}
286284
return resultMono
287285
.map(result -> new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, request.id(), result, null))
288-
.onErrorResume(error -> {
289-
McpSchema.JSONRPCResponse.JSONRPCError jsonRpcError = (error instanceof McpError mcpError
290-
&& mcpError.getJsonRpcError() != null) ? mcpError.getJsonRpcError()
291-
// TODO: add error message through the data field
292-
: new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,
293-
error.getMessage(), McpError.aggregateExceptionMessages(error));
294-
return Mono.just(
295-
new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, request.id(), null, jsonRpcError));
296-
});
286+
.onErrorResume(error -> Mono.just(new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, request.id(),
287+
null, toJsonRpcError(request, error))));
297288
});
298289
}
299290

291+
/**
292+
* Converts a request handler failure into the JSON-RPC error sent to the client.
293+
* Errors other than {@link McpError} are logged, and only their message is sent:
294+
* their cause chain may contain internal details that must not reach the client.
295+
* @param request the request that failed
296+
* @param error the failure
297+
* @return the JSON-RPC error to send to the client
298+
*/
299+
private McpSchema.JSONRPCResponse.JSONRPCError toJsonRpcError(McpSchema.JSONRPCRequest request, Throwable error) {
300+
if (error instanceof McpError mcpError && mcpError.getJsonRpcError() != null) {
301+
return mcpError.getJsonRpcError();
302+
}
303+
logger.warn("Error handling request {} [{}]", request.id(), request.method(), error);
304+
return new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,
305+
Objects.requireNonNullElse(error.getMessage(), "Internal error"), null);
306+
}
307+
300308
/**
301309
* Handles an incoming JSON-RPC notification by routing it to the appropriate handler.
302310
* @param notification The incoming JSON-RPC notification

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

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
import java.time.Duration;
88
import java.util.Map;
9+
import java.util.Objects;
910
import java.util.UUID;
1011
import java.util.concurrent.ConcurrentHashMap;
1112
import java.util.concurrent.atomic.AtomicLong;
@@ -179,10 +180,18 @@ public Mono<Void> responseStream(McpSchema.JSONRPCRequest jsonrpcRequest, McpStr
179180
.map(result -> new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, jsonrpcRequest.id(), result,
180181
null))
181182
.onErrorResume(e -> {
182-
McpSchema.JSONRPCResponse.JSONRPCError jsonRpcError = (e instanceof McpError mcpError
183-
&& mcpError.getJsonRpcError() != null) ? mcpError.getJsonRpcError()
184-
: new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,
185-
e.getMessage(), McpError.aggregateExceptionMessages(e));
183+
McpSchema.JSONRPCResponse.JSONRPCError jsonRpcError;
184+
if (e instanceof McpError mcpError && mcpError.getJsonRpcError() != null) {
185+
jsonRpcError = mcpError.getJsonRpcError();
186+
}
187+
else {
188+
// The cause chain may contain internal details: log it, but only
189+
// send
190+
// the message to the client
191+
logger.warn("Error handling request {} [{}]", jsonrpcRequest.id(), jsonrpcRequest.method(), e);
192+
jsonRpcError = new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,
193+
Objects.requireNonNullElse(e.getMessage(), "Internal error"), null);
194+
}
186195

187196
var errorResponse = new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, jsonrpcRequest.id(),
188197
null, jsonRpcError);

‎mcp-core/src/test/java/io/modelcontextprotocol/server/DefaultMcpStatelessServerHandlerTests.java‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@
77
import io.modelcontextprotocol.common.McpTransportContext;
88
import io.modelcontextprotocol.spec.McpSchema;
99
import org.junit.jupiter.api.Test;
10+
import reactor.core.publisher.Mono;
1011
import reactor.test.StepVerifier;
1112

1213
import java.util.Collections;
14+
import java.util.Map;
1315

1416
import static org.assertj.core.api.Assertions.assertThat;
1517

@@ -37,4 +39,42 @@ void testHandleRequestWithUnregisteredMethod() {
3739
}).verifyComplete();
3840
}
3941

42+
@Test
43+
void testHandleRequestWithFailingHandler() {
44+
McpStatelessRequestHandler<Object> failingHandler = (transportContext, params) -> Mono
45+
.error(new IllegalStateException("Tool failed",
46+
new IllegalArgumentException("connect to db.internal:5432 failed")));
47+
DefaultMcpStatelessServerHandler handler = new DefaultMcpStatelessServerHandler(
48+
Map.of("tools/call", failingHandler), Collections.emptyMap());
49+
50+
McpSchema.JSONRPCRequest request = new McpSchema.JSONRPCRequest(McpSchema.JSONRPC_VERSION, "tools/call",
51+
"test-id-123", null);
52+
53+
StepVerifier.create(handler.handleRequest(McpTransportContext.EMPTY, request)).assertNext(response -> {
54+
assertThat(response.id()).isEqualTo("test-id-123");
55+
assertThat(response.result()).isNull();
56+
assertThat(response.error()).isNotNull();
57+
assertThat(response.error().code()).isEqualTo(McpSchema.ErrorCodes.INTERNAL_ERROR);
58+
assertThat(response.error().message()).isEqualTo("Tool failed");
59+
assertThat(response.error().data()).isNull();
60+
}).verifyComplete();
61+
}
62+
63+
@Test
64+
void testHandleRequestWithFailingHandlerWithoutMessage() {
65+
McpStatelessRequestHandler<Object> failingHandler = (transportContext, params) -> Mono
66+
.error(new IllegalStateException());
67+
DefaultMcpStatelessServerHandler handler = new DefaultMcpStatelessServerHandler(
68+
Map.of("tools/call", failingHandler), Collections.emptyMap());
69+
70+
McpSchema.JSONRPCRequest request = new McpSchema.JSONRPCRequest(McpSchema.JSONRPC_VERSION, "tools/call",
71+
"test-id-123", null);
72+
73+
StepVerifier.create(handler.handleRequest(McpTransportContext.EMPTY, request)).assertNext(response -> {
74+
assertThat(response.error()).isNotNull();
75+
assertThat(response.error().code()).isEqualTo(McpSchema.ErrorCodes.INTERNAL_ERROR);
76+
assertThat(response.error().message()).isEqualTo("Internal error");
77+
}).verifyComplete();
78+
}
79+
4080
}

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

Lines changed: 8 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -246,30 +246,23 @@ void testRequestHandlerThrowsGenericException() {
246246
"test-id", null);
247247
transport.simulateIncomingMessage(request);
248248

249-
// Verify: The response should contain INTERNAL_ERROR with aggregated exception
250-
// messages in data field
249+
// Verify: The response should contain INTERNAL_ERROR with the exception message
251250
McpSchema.JSONRPCMessage sentMessage = transport.getLastSentMessage();
252251
assertThat(sentMessage).isInstanceOf(McpSchema.JSONRPCResponse.class);
253252
McpSchema.JSONRPCResponse response = (McpSchema.JSONRPCResponse) sentMessage;
254253
assertThat(response.error()).isNotNull();
255254
assertThat(response.error().code()).isEqualTo(McpSchema.ErrorCodes.INTERNAL_ERROR);
256255
assertThat(response.error().message()).isEqualTo("Something went wrong");
257-
// Verify data field contains aggregated exception messages
258-
assertThat(response.error().data()).isNotNull();
259-
assertThat(response.error().data().toString()).contains("RuntimeException");
260-
assertThat(response.error().data().toString()).contains("Something went wrong");
256+
assertThat(response.error().data()).isNull();
261257

262258
session.close();
263259
}
264260

265261
@Test
266-
void testRequestHandlerThrowsExceptionWithCause() {
267-
// Setup: Create a request handler that throws an exception with a cause chain
268-
String testMethod = "test.chainedError";
269-
RuntimeException rootCause = new IllegalArgumentException("Root cause message");
270-
RuntimeException middleCause = new IllegalStateException("Middle cause message", rootCause);
271-
RuntimeException topException = new RuntimeException("Top level message", middleCause);
272-
McpClientSession.RequestHandler<?> failingHandler = params -> Mono.error(topException);
262+
void testRequestHandlerThrowsExceptionWithoutMessage() {
263+
// Setup: Create a request handler that throws an exception with a null message
264+
String testMethod = "test.noMessageError";
265+
McpClientSession.RequestHandler<?> failingHandler = params -> Mono.error(new IllegalStateException());
273266

274267
var transport = new MockMcpClientTransport();
275268
var session = new McpClientSession(TIMEOUT, transport, Map.of(testMethod, failingHandler), Map.of(),
@@ -280,22 +273,13 @@ void testRequestHandlerThrowsExceptionWithCause() {
280273
"test-id", null);
281274
transport.simulateIncomingMessage(request);
282275

283-
// Verify: The response should contain INTERNAL_ERROR with full exception chain
284-
// in data field
276+
// Verify: An error response is still sent
285277
McpSchema.JSONRPCMessage sentMessage = transport.getLastSentMessage();
286278
assertThat(sentMessage).isInstanceOf(McpSchema.JSONRPCResponse.class);
287279
McpSchema.JSONRPCResponse response = (McpSchema.JSONRPCResponse) sentMessage;
288280
assertThat(response.error()).isNotNull();
289281
assertThat(response.error().code()).isEqualTo(McpSchema.ErrorCodes.INTERNAL_ERROR);
290-
assertThat(response.error().message()).isEqualTo("Top level message");
291-
// Verify data field contains the full exception chain
292-
String dataString = response.error().data().toString();
293-
assertThat(dataString).contains("RuntimeException");
294-
assertThat(dataString).contains("Top level message");
295-
assertThat(dataString).contains("IllegalStateException");
296-
assertThat(dataString).contains("Middle cause message");
297-
assertThat(dataString).contains("IllegalArgumentException");
298-
assertThat(dataString).contains("Root cause message");
282+
assertThat(response.error().message()).isEqualTo("Internal error");
299283

300284
session.close();
301285
}

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

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,9 @@
6060
import static net.javacrumbs.jsonunit.assertj.JsonAssertions.json;
6161
import static org.assertj.core.api.Assertions.assertThat;
6262
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
63+
import static org.assertj.core.api.Assertions.assertThatThrownBy;
6364
import static org.assertj.core.api.Assertions.assertWith;
65+
import static org.assertj.core.api.InstanceOfAssertFactories.type;
6466
import static org.awaitility.Awaitility.await;
6567
import static org.mockito.Mockito.mock;
6668

@@ -576,6 +578,67 @@ void testCreateElicitationWithRequestTimeoutFail(String clientType) {
576578
}
577579
}
578580

581+
@ParameterizedTest(name = "{0} : {displayName} ")
582+
@MethodSource("clientsForTesting")
583+
void testToolErrorDoesNotSendCauseChain(String clientType) {
584+
585+
var clientBuilder = clientBuilders.get(clientType);
586+
587+
McpServerFeatures.AsyncToolSpecification tool = McpServerFeatures.AsyncToolSpecification.builder()
588+
.tool(Tool.builder().name("tool1").description("tool1 description").inputSchema(EMPTY_JSON_SCHEMA).build())
589+
.callHandler((exchange,
590+
request) -> Mono.error(new IllegalStateException("Tool failed",
591+
new IllegalArgumentException("connect to db.internal:5432 failed"))))
592+
.build();
593+
594+
var mcpServer = prepareAsyncServerBuilder().serverInfo("test-server", "1.0.0").tools(tool).build();
595+
596+
try (var mcpClient = clientBuilder.clientInfo(new McpSchema.Implementation("Sample client", "0.0.0")).build()) {
597+
598+
assertThatThrownBy(() -> mcpClient.callTool(new McpSchema.CallToolRequest("tool1", Map.of())))
599+
.isInstanceOf(McpError.class)
600+
.extracting("jsonRpcError")
601+
.asInstanceOf(type(McpSchema.JSONRPCResponse.JSONRPCError.class))
602+
.satisfies(error -> {
603+
assertThat(error.code()).isEqualTo(McpSchema.ErrorCodes.INTERNAL_ERROR);
604+
assertThat(error.message()).isEqualTo("Tool failed");
605+
assertThat(error.data()).isNull();
606+
});
607+
}
608+
finally {
609+
mcpServer.closeGracefully().block();
610+
}
611+
}
612+
613+
@ParameterizedTest(name = "{0} : {displayName} ")
614+
@MethodSource("clientsForTesting")
615+
void testToolErrorWithoutMessage(String clientType) {
616+
617+
var clientBuilder = clientBuilders.get(clientType);
618+
619+
McpServerFeatures.AsyncToolSpecification tool = McpServerFeatures.AsyncToolSpecification.builder()
620+
.tool(Tool.builder().name("tool1").description("tool1 description").inputSchema(EMPTY_JSON_SCHEMA).build())
621+
.callHandler((exchange, request) -> Mono.error(new IllegalStateException()))
622+
.build();
623+
624+
var mcpServer = prepareAsyncServerBuilder().serverInfo("test-server", "1.0.0").tools(tool).build();
625+
626+
try (var mcpClient = clientBuilder.clientInfo(new McpSchema.Implementation("Sample client", "0.0.0")).build()) {
627+
628+
assertThatThrownBy(() -> mcpClient.callTool(new McpSchema.CallToolRequest("tool1", Map.of())))
629+
.isInstanceOf(McpError.class)
630+
.extracting("jsonRpcError")
631+
.asInstanceOf(type(McpSchema.JSONRPCResponse.JSONRPCError.class))
632+
.satisfies(error -> {
633+
assertThat(error.code()).isEqualTo(McpSchema.ErrorCodes.INTERNAL_ERROR);
634+
assertThat(error.message()).isEqualTo("Internal error");
635+
});
636+
}
637+
finally {
638+
mcpServer.closeGracefully().block();
639+
}
640+
}
641+
579642
// ---------------------------------------
580643
// Roots Tests
581644
// ---------------------------------------

0 commit comments

Comments
 (0)