Madara was sealed away in a shrine until Natsume accidentally released him. After being trapped in spiritual limbo for so long, Madara got stuck taking the form of a maneki neko—a lucky cat figurine. This is why Natsume calls him Nyanko-sensei, and since people can actually see him in this shape, Natsume had to convince his guardians to let him keep the cat around as a pet.
As a spirit, Madara's genuinely powerful and acts as Natsume's protector, occasionally teaching him spells. The deal is simple: in exchange, Natsume has to promise him the Book of Friends when he dies. Their relationship is rocky though—they bicker constantly, and it's not uncommon for Natsume to literally punch Madara in the face hard enough to knock him out. Madara insists he's not actually a cat, yet he can't help playing with cat toys anyway.
The character design came from a lucky cat statue that creator Midorikawa received as a kid. In the anime adaptation, Natsume treats him with noticeably more respect than he does in the manga.
Content compiled by AnimeList.moe from publicly available sources.