---
title: "Security Best Practices"
description: "Secure your mcp_use implementations and protect sensitive data"
icon: "shield"
---
Security is crucial when working with MCP servers and LLM agents. This guide covers best practices for protecting your applications, data, and infrastructure.
**Important**: MCP servers can have powerful capabilities including file system access, network requests, and code execution. Always follow security best practices to protect your systems.
## API Key Management
### Environment Variables
Never hardcode API keys in your source code. Use environment variables:
```python Python
import os
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Access API keys securely
openai_key = os.getenv("OPENAI_API_KEY")
anthropic_key = os.getenv("ANTHROPIC_API_KEY")
if not openai_key:
raise ValueError("OPENAI_API_KEY environment variable is required")
```
### .env File Security
Create a secure `.env` file:
```bash .env
# LLM Provider Keys
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GROQ_API_KEY=gsk_...
# MCP Server Configuration
FILESYSTEM_ROOT=/safe/workspace
DATABASE_URL=postgresql://user:pass@localhost/db
# Optional: Security settings
MCP_TIMEOUT=30
MAX_TOOL_CALLS=10
ALLOWED_DOMAINS=example.com,api.service.com
```
**Never commit .env files**: Add `.env` to your `.gitignore` file to prevent accidentally committing API keys to version control.
### Secrets Management
For production environments, use proper secrets management:
```python Python
import boto3
from botocore.exceptions import ClientError
def get_secret(secret_name, region_name="us-east-1"):
session = boto3.session.Session()
client = session.client('secretsmanager', region_name=region_name)
try:
response = client.get_secret_value(SecretId=secret_name)
return response['SecretString']
except ClientError as e:
raise e
# Usage
openai_key = get_secret("prod/mcp-use/openai-key")
```
```python Python
from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential
credential = DefaultAzureCredential()
client = SecretClient(
vault_url="https://vault-name.vault.azure.net/",
credential=credential
)
# Usage
openai_key = client.get_secret("openai-api-key").value
```
```python Python
import hvac
client = hvac.Client(url='https://vault.example.com')
client.token = os.getenv('VAULT_TOKEN')
# Read secret
response = client.secrets.kv.v2.read_secret_version(
path='mcp-use/api-keys'
)
openai_key = response['data']['data']['openai_key']
```
## MCP Server Security
### Filesystem Server Security
When using filesystem servers, restrict access to safe directories:
```json secure_filesystem_config.json
{
"mcpServers": {
"filesystem": {
"command": "mcp-server-filesystem",
"args": [
"/workspace/safe-directory",
"--readonly",
"--max-file-size", "10MB",
"--allowed-extensions", ".txt,.md,.json,.py"
],
"env": {
"FILESYSTEM_READONLY": "true",
"MAX_FILE_SIZE": "10485760"
}
}
}
}
```
### Network Access Restrictions
Limit network access for web-based MCP servers:
```json secure_network_config.json
{
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest"],
"env": {
"PLAYWRIGHT_HEADLESS": "true",
"ALLOWED_DOMAINS": "example.com,api.trusted-service.com",
"BLOCK_PRIVATE_IPS": "true",
"DISABLE_JAVASCRIPT": "false",
"TIMEOUT": "30000"
}
}
}
}
```
### Database Security
Secure database connections with proper credentials and restrictions:
```json secure_database_config.json
{
"mcpServers": {
"postgres": {
"command": "mcp-server-postgres",
"env": {
"DATABASE_URL": "${DATABASE_URL}",
"CONNECTION_TIMEOUT": "30",
"MAX_CONNECTIONS": "5",
"READONLY_MODE": "true",
"ALLOWED_SCHEMAS": "public,reporting",
"BLOCKED_TABLES": "users,passwords,secrets"
}
}
}
}
```
## Agent Security Configuration
### Restrict Tool Access
Limit which tools the agent can use:
```python secure_agent.py
from mcp_use import MCPAgent, MCPClient
from langchain_openai import ChatOpenAI
# Define allowed and disallowed tools
ALLOWED_TOOLS = [
"file_read",
"file_write",
"web_search",
"web_scrape"
]
DISALLOWED_TOOLS = [
"system_execute",
"network_request",
"database_write",
"file_delete"
]
async def create_secure_agent():
client = MCPClient.from_config_file("secure_config.json")
llm = ChatOpenAI(model="gpt-4")
agent = MCPAgent(
llm=llm,
client=client,
allowed_tools=ALLOWED_TOOLS,
disallowed_tools=DISALLOWED_TOOLS,
max_steps=20, # Limit execution steps
timeout=300, # 5-minute timeout
use_server_manager=True
)
return agent
```
### Input Validation
Validate user inputs before processing:
```python input_validation.py
import re
from typing import List, Optional
class InputValidator:
def __init__(self):
self.max_length = 1000
self.blocked_patterns = [
r'rm\s+-rf', # Dangerous commands
r'sudo', # Privilege escalation
r'chmod\s+777', # Permission changes
r'\.\./', # Path traversal
r'