Security Best Practices
- Authentication — Always require API keys or JWT tokens for remote MCP servers
- Rate Limiting — Prevent abuse with request limits per client
- Input Validation — Validate all tool arguments before executing
- Read-Only by Default — Start with read-only tools; add write access carefully
- Audit Logging — Log every tool call with client identity and arguments
- Network Security — Use HTTPS in production, restrict access via security groups
# Example: Adding authentication middleware
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import Response
class AuthMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
if request.url.path == "/health":
return await call_next(request)
token = request.headers.get("Authorization", "").replace("Bearer ", "")
if token != os.environ["MCP_AUTH_TOKEN"]:
return Response("Unauthorized", status_code=401)
return await call_next(request)
app = Starlette(
routes=[...],
middleware=[Middleware(AuthMiddleware)]
)