What's the formula for getting 3-stars in a cup?
The two prominent things that have stood out to me in races:
Points
Probably kind of obvious, but for 150cc you need to have 40 points (10 per race) at the end of a Grand Prix -- or in other words, you need to come in first every race. Lower tiers may lax the point requirement a bit, but I haven't spent too much time there as compared to 150cc.
Low Overall Time
Your overall time as compared to the other drivers needs to be noticeably lower -- you need to be in first for the majority of these races to get three stars. It isn't essential to be in first the entire time (you can make some mistakes, and the game offers some allowance for you to recover from attacks by other players) but your star count will drop if you aren't outperforming all other drivers.
Being in first place and staying in first place seems to really be the only requirement for getting three stars. I'll offer a few points below to try getting there.
Coins
Coins haven't been present since Mario Kart: Super Circuit, but they're back for Mario Kart 7 and can make a huge difference. You can collect 10 coins throughout the course of a level, and each coin offers a passive speed boost to the player. Other drivers can also collect coins, so the player will be at a disadvantage if they do not maintain a high coin count.
Having 10 coins throughout the race isn't a requirement to get three stars, but remember what I said about having a lower overall time than the other drivers? Drivers having a passive speed boost that the player does not will close that gap, making it more difficult to achieve the three star rating.
Defensive Items
The first place driver will typically get fairly useless items compared to the powerful offensive items that the back of the pack receives. Bananas and turtle shells, while not ideal in most positions, are actually of value to the first place player because they can hold them behind the cart to act as a defensive buffer from attack. Sets of 3 bananas seem to be the most useful in my experience, because they will follow behind the cart without much effort.
Defensive Driving
If you find yourself without items to defend yourself, there are things you can do to keep an attack from putting you too far behind. Some levels have objects in the environment that will impede incoming turtle shells if you swerve your cart between them and the approaching object.
There are other circumstances where you probably can't avoid getting hit (an approaching blue turtle shell), but you can mitigate your losses by decelerating enough to be near enemy drivers when the shell explodes. -If you have a mushroom you can use it right when the blue shell is overhead and it will miss you. Drivers in 2nd or 3rd place tend to be in those positions for most of a Grand Prix, and (if you recover from the turtle shell well enough) disrupting their patterns may give you an advantage in overall time elapsed.