I've just finished reading one of Twain's final works entitled The Mysterious Stranger. It's so dark and riveting in many ways. Satan himself makes an appearance and the entire story is fraught with teachings and philosophies of Twain's late cynicism! I recommend it to anybody who enjoys Twain's work. But be warned, this is no Tom Sawyer or Huckleberry Finn. This is a much darker story.
I doubt that The Mysterious Stranger was the result of "flipp[ing] through a philosophy book or something". Twain was always a bit of a cynic, and this deepened, along with his atheism, in later years due to personal tragedy. OP, it's always been one of my favorites by Mark Twain. IIRC there are at least three different endings floating around.