Gas price is calculated on ethgasstation and metamask by looking at the average gas price of previous blocks. You can't query the blockchain for gas price, it's not something the blockchain manages or has control over.
Here's a link to the ethgasstation-api github repo: https://github.com/ethgasstation/ethgasstation-api