Sometimes actors want to have a say in the words they're given; sometimes they want to stretch their artistic muscles; sometimes they look at the scripts they have to do and think, "I could do better than this!" When this happens, and the producers are on their side (or the network is), you have something written by a cast member.
Much less prevalent than Directed by Cast Member, particularly in [...] [tvtropes.org]