MCP · Lesson 95 of 120
Secrets
Keys stay out of code.
Servers often need secrets, like API keys and database passwords. A secret in your code ends up in git, in screenshots, and in other people's hands.

- Servers need secrets
- Code leaks
- Keep them out
northwind.py
Read the key from the environment, and stop with a clear message if it's missing. Use it inside the tool. But never return it, and never write it to logs.
northwind.pypython
import os, sys
from mcp.server.mcpserver import MCPServer
API_KEY = os.environ.get("NORTHWIND_API_KEY")
if not API_KEY:
sys.exit("Set NORTHWIND_API_KEY first")
mcp = MCPServer("northwind")
@mcp.tool()
def order_status(order_id: int) -> str:
"""Look up an order in Northwind's order system."""
# use API_KEY here to call the real system
# never return it, and never log it
return "shipped"Where secrets belong
Keep secrets in environment variables, or a secrets manager. The host config passes them in, through env. Never put them in code, in tool results, or in descriptions.
| Place | Secrets? |
|---|---|
| Environment variables | yes |
| Secrets manager | yes |
| Code or git | never |
| Tool results or logs | never |
Summary
Read secrets from the environment, use them, and never return or log them. Next, confirming before acting.
Key takeaways- Environment
- Never return
- Never log
Next up: Confirm Before Acting — humans approve