WP-CLI with theme: Uncaught Error: Class ‘WP_CLI’ not found

You’ll need to wrap your statement within a class_exists() check:

function foo_command( $args ) {
    WP_CLI::success( $args[0] );
}
if ( class_exists( 'WP_CLI' ) ) {
    WP_CLI::add_command( 'foo', 'foo_command' );
}

This way, the command is only registered when the WP_CLI class exists — because the WP_CLI class will only exist when WP-CLI is running.