How to authenticate MCP server requests
Quick answer
Authenticate
MCP server requests by validating API keys or tokens sent in request headers or environment variables. Use secure transport (e.g., TLS) and verify credentials on each request to ensure authorized access to the MCP server.PREREQUISITES
Python 3.8+pip install mcpBasic knowledge of HTTP headers and environment variables
Setup
Install the official mcp Python package and set your API key as an environment variable for secure authentication.
- Run
pip install mcpto install the SDK. - Set your API key in your environment:
export MCP_API_KEY='your_api_key_here'(Linux/macOS) orset MCP_API_KEY=your_api_key_here(Windows).
pip install mcp Step by step
Use the mcp SDK to create a server that authenticates incoming requests by checking the Authorization header against your API key stored in environment variables.
import os
from mcp.server import Server
from mcp.server.stdio import stdio_server
API_KEY = os.environ.get("MCP_API_KEY")
class AuthenticatedServer(Server):
def authenticate(self, headers):
# Extract the Authorization header
auth_header = headers.get("Authorization")
if not auth_header:
return False
# Expected format: 'Bearer <token>'
parts = auth_header.split()
if len(parts) != 2 or parts[0].lower() != "bearer":
return False
token = parts[1]
# Validate token against environment variable
return token == API_KEY
def handle_request(self, request):
# Example request handling logic
return {"response": "Request authenticated and processed."}
if __name__ == "__main__":
server = AuthenticatedServer()
stdio_server(server) # Runs the MCP server over stdio with authentication Common variations
You can implement authentication using different methods depending on your deployment:
- Use environment variables or secure vaults to store API keys.
- Support token rotation by validating against a list of valid tokens.
- Implement async request handling if your server supports it.
- Use TLS or other transport layer security when running MCP over network sockets.
import os
import asyncio
from mcp.server import Server
from mcp.server.stdio import stdio_server
API_KEY = os.environ.get("MCP_API_KEY")
class AsyncAuthenticatedServer(Server):
async def authenticate(self, headers):
auth_header = headers.get("Authorization")
if not auth_header:
return False
parts = auth_header.split()
if len(parts) != 2 or parts[0].lower() != "bearer":
return False
token = parts[1]
return token == API_KEY
async def handle_request(self, request):
return {"response": "Async request authenticated and processed."}
if __name__ == "__main__":
server = AsyncAuthenticatedServer()
asyncio.run(stdio_server(server)) Troubleshooting
If authentication fails, verify that:
- Your
MCP_API_KEYenvironment variable is set correctly. - The client sends the
Authorizationheader in the formatBearer <token>. - There are no extra spaces or typos in the token.
- Your transport layer is secure to prevent token interception.
Check server logs for authentication errors and ensure your client and server clocks are synchronized if using time-based tokens.
Key Takeaways
- Always validate the Authorization header against a secure API key or token.
- Store API keys securely using environment variables or secret management tools.
- Use secure transport (TLS) to protect authentication tokens in transit.