AI Hints
Home›MCP Tutorial›Limiting Damage
MCP · Lesson 95 of 120

Secrets

Keys stay out of code.

⏱ 2 min read▶ Video at 1:25:05🎓 Free
Watch this lesson in the MCP courseWatch on YouTube ↗Full MCP course

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.

Secrets
From the video: Secrets
  • 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.

PlaceSecrets?
Environment variablesyes
Secrets manageryes
Code or gitnever
Tool results or logsnever

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