If a handler throws McpError, use its values for the RPC error

Handlers should be able to throw RPC errors and `McpError` is the
right exception for that.

Improve `DefaultMcpStatelessServerHandler` error handler to check if the
exception is `McpError` and, if so, use it to build the RPC error
result instead of re-writing as `INTERNAL_ERROR`.
This commit is contained in:
Jordan Zimmerman 2025-08-07 08:26:07 +01:00 • committed by Christian Tzolov
commit a14ef425d6

View file

@ -35,9 +35,17 @@ class DefaultMcpStatelessServerHandler implements McpStatelessServerHandler {
}
return requestHandler.handle(transportContext, request.params())
.map(result -> new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, request.id(), result, null))
.onErrorResume(t -> Mono.just(new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, request.id(), null,
new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR, t.getMessage(),
null))));
.onErrorResume(t -> {
McpSchema.JSONRPCResponse.JSONRPCError error;
if (t instanceof McpError mcpError && mcpError.getJsonRpcError() != null) {
error = mcpError.getJsonRpcError();
}
else {
error = new McpSchema.JSONRPCResponse.JSONRPCError(McpSchema.ErrorCodes.INTERNAL_ERROR,
t.getMessage(), null);
}
return Mono.just(new McpSchema.JSONRPCResponse(McpSchema.JSONRPC_VERSION, request.id(), null, error));
});
}
@Override