How to Manage MCP Server Credentials and Secrets Securely: 8 Best Practices from the Awesome MCP Servers Repository
Store MCP server credentials in environment variables or external vaults, never commit them to source control, and implement BYOK patterns with regular rotation and least-privilege scopes to secure your AI agent infrastructure.
The Model Context Protocol (MCP) ecosystem connects AI agents to external tools and data sources, making managing MCP server credentials and secrets securely a critical foundation for production deployments. This guide extracts proven security patterns from the punkpeye/awesome-mcp-servers repository to help you protect API keys, tokens, and private keys while maintaining operational agility.
Never Hard-Code Secrets in Source Code
The first rule of MCP credential management is absolute: never embed secrets directly in your codebase. Every server in the awesome-mcp-servers catalog follows this principle by accepting sensitive configuration via external injection rather than hard-coded strings.
For example, the MindsDB MCP gateway (mindsdb/mindsdb) exposes configuration flags that reference environment variables like MINDSDB_API_KEY and DATABASE_URL rather than embedding credentials in the server implementation. As documented in the repository's security-focused entries, this pattern ensures that even if your source code is compromised, the credentials remain inaccessible.
Use Environment Variables and .env Files
Store secrets in a .env file that is explicitly excluded from version control, then load them at runtime using language-specific libraries. This approach keeps sensitive data out of your Git history while maintaining local development convenience.
Add .env to your .gitignore immediately:
echo ".env" >> .gitignore
Python Implementation
Use python-dotenv to load variables at runtime:
from dotenv import load_dotenv
import os
load_dotenv() # Reads .env into os.environ
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
Node.js Implementation
The dotenv package automatically loads environment variables:
require('dotenv').config();
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
Go Implementation
Use envconfig for struct-based configuration with validation:
type Config struct {
OpenAIKey string `env:"OPENAI_API_KEY,required"`
DBReadOnly string `env:"DB_READ_ONLY,default=true"`
}
func LoadConfig() (*Config, error) {
cfg := &Config{}
if err := envconfig.Process("", cfg); err != nil {
return nil, err
}
return cfg, nil
}
Implement Bring-Your-Own-Key (BYOK) Patterns
Many servers in the catalog support BYOK (Bring-Your-Own-Key) architecture, where the client supplies credentials at runtime rather than the server storing them. This design allows you to maintain credentials in your own vault (AWS Secrets Manager, HashiCorp Vault, Azure Key Vault) and inject them only when establishing the MCP connection.
The agentforge-trust-mcp server exemplifies this approach by checking trust scores before credential usage, enabling you to delegate validation logic while retaining control over the actual secrets. This pattern is particularly valuable for multi-tenant deployments where each user maintains their own API keys.
Rotate and Audit Secrets Regularly
Static credentials are a liability. Implement automated rotation schedules (e.g., every 30 days) for API keys and tokens, and maintain comprehensive audit logs of credential usage.
The mcp-shield server demonstrates this practice by logging every tool call and flagging potential secret leakage in real-time. When integrated into your MCP infrastructure, such audit trails help you detect anomalous access patterns and respond to credential compromise incidents immediately.
Apply Least-Privilege Scopes
When creating API keys for MCP servers, grant only the specific permissions required for the tool's function. A server that only reads from a datastore should receive a read-only token, never administrative privileges.
The postgres_mcp server entry in the repository explicitly notes that it operates "read-only by default," following the principle of least privilege. This constraint prevents accidental data modification if the credential is compromised and limits the blast radius of security incidents.
Secure CI/CD Pipelines
Prevent credential leakage in your development workflow by integrating secret-scanning tools into your continuous integration pipeline. The repository includes a GitHub Actions workflow at .github/workflows/check-glama.yml that performs static analysis on MCP manifests.
Extend this workflow with tools like TruffleHog or Gitleaks to detect accidentally committed credentials before they reach production:
# .github/workflows/check-glama.yml (extension)
steps:
- uses: actions/checkout@v3
- name: Scan for secrets
uses: trufflesecurity/trufflehog@v3
with:
path: .
base: ${{ github.ref }}
Encrypt Secrets at Rest
For long-running MCP agents that must persist credentials between sessions, implement strong encryption at rest. Do not store raw API keys in plaintext files or databases.
The agentforge-trust-mcp server uses AES-256-GCM encryption for its credential store, providing authenticated encryption that protects against both unauthorized access and tampering. When implementing persistent storage for MCP credentials, adopt similar symmetric encryption standards with secure key management hierarchies.
Leverage Secret-as-a-Service APIs
Delegate credential complexity to specialized services that provide service-level credential management. Some MCP servers expose APIs for per-user API key management with optional BYOK support.
The agent-bodega server implements this pattern by managing per-user API keys externally, allowing you to benefit from professional secret management without implementing vault logic yourself. This approach reduces your security surface area while ensuring credentials receive enterprise-grade protection.
Summary
- Never hard-code secrets: Configure MCP servers via environment variables like
MINDSDB_API_KEYandDATABASE_URLrather than embedding them in source code. - Use
.envfiles safely: Store local secrets in.envfiles excluded from Git, loading them withpython-dotenv, Node'sdotenv, or Go'senvconfig. - Implement BYOK: Let clients supply their own credentials from vaults like AWS Secrets Manager rather than storing keys server-side.
- Rotate and audit: Schedule 30-day rotation cycles and use tools like
mcp-shieldto log credential usage and detect leaks. - Apply least privilege: Grant read-only scopes by default, following the
postgres_mcppattern of restricted permissions. - Secure your pipeline: Extend
.github/workflows/check-glama.ymlwith TruffleHog scanning to prevent accidental commits. - Encrypt at rest: Use AES-256-GCM encryption for any persisted credentials, as demonstrated by
agentforge-trust-mcp.
Frequently Asked Questions
Should I use environment variables or a dedicated secret manager for MCP credentials?
Use environment variables for local development and short-lived containers, but migrate to dedicated secret managers (AWS Secrets Manager, HashiCorp Vault, Azure Key Vault) for production deployments. Environment variables work well for the BYOK pattern where clients inject secrets at runtime, while secret managers provide rotation, auditing, and access controls essential for long-running MCP agents.
How often should I rotate MCP server API keys?
Rotate API keys every 30 days as a baseline, or immediately if you suspect compromise. The mcp-shield server provides audit capabilities to track credential usage, enabling you to identify rotation triggers based on anomalous access patterns rather than relying solely on calendar schedules.
What is the BYOK pattern in MCP servers?
BYOK (Bring-Your-Own-Key) is an architecture where the client supplies their own credentials at runtime rather than the server storing them. This pattern, used by servers like agentforge-trust-mcp, allows organizations to maintain exclusive control over their secrets in their preferred vaults while still leveraging MCP tooling.
How do I prevent secrets from leaking in MCP CI/CD pipelines?
Integrate secret-scanning tools into your GitHub Actions workflow. The repository's .github/workflows/check-glama.yml provides a foundation for static analysis; extend it with TruffleHog or Gitleaks to scan commits for API keys before they reach your main branch, preventing accidental credential exposure in version control.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →