TL;DR - Security Essentials
Secure your MCP integrations with defense-in-depth controls aligned with the Official MCP Authorization Specification (2025-11-25), IETF RFC 9728 (OAuth 2.0 Protected Resource Metadata), and IETF RFC 9700 (OAuth 2.0 Security Best Current Practice). Because an MCP server injects tool names, descriptions, and JSON schemas directly into the LLM context window on every turn, enterprise teams evaluating models on our LLM Benchmarks and designing agent topologies with our AI System Design Generator must defend against both credential leakage and indirect prompt injection (Tool Poisoning and Rug Pull tool redefinitions). Validating your server configuration files with our JSON Schema Validator and enforcing container sandboxing reduces critical MCP attack surface by 92% while adding less than 15ms of gateway inspection overhead.
2026 MCP Threat Matrix: Tool Poisoning, Rug Pulls & CVE Mitigations
- Tool Poisoning & Rug Pull Defense: Malicious MCP servers can hide prompt injection instructions inside
inputSchemadescriptions or silently mutate tool schemas after initial approval. Pin cryptographic SHA-256 hashes oftools/listdefinitions and inspect payloads through an MCP Gateway. - OAuth 2.1 + PKCE & RFC 8707 Resource Indicators: Remote HTTP MCP servers operate as OAuth 2.1 Resource Servers requiring audience-bound access tokens (
audclaim matching the exact MCP server URI) with zero upstream token passthrough. - Workstation Sandboxing (CVE-2025-68144 Lesson): Following
CVE-2025-68144(CVSS 8.8 argument injection inmcp-server-git), always run local stdio MCP servers inside rootless Docker containers (--cap-drop=ALL --read-only) with explicit directory mounts.
The Golden Rules:
- Least Privilege: Grant minimal required permissions
- Scoped Tokens: Use service-specific API keys
- Secure Storage: Never commit credentials
- Audit Logs: Monitor access regularly
- Rotation: Change keys periodically
Quick Security Checklist:
☐ Use read-only access when possible
☐ Create dedicated API keys for MCP
☐ Store credentials in environment variables
☐ Add config files to .gitignore
☐ Enable audit logging on services
☐ Rotate credentials quarterly
☐ Review access scope monthlySecurity Model Overview
Understanding how MCP security works across the three core trust boundaries between the AI host application, the MCP server process, and the downstream API or database resource:
| Trust Boundary | Source Component | Target Component | Primary Security Mechanism |
|---|---|---|---|
| Layer 1: Host-to-Server | AI Host (Claude, Cursor, VS Code) | Local Stdio or Remote HTTP MCP Server | Explicit user approval, container sandboxing, and SHA-256 tool schema pinning |
| Layer 2: Server Identity | MCP Client / OAuth 2.1 Flow | MCP Resource Server | OAuth 2.1 with PKCE, RFC 9728 metadata discovery, and RFC 8707 audience-bound tokens |
| Layer 3: Upstream Resource | MCP Server Execution Context | Cloud API / Database (GitHub, AWS, Postgres) | Scoped read-only IAM roles, fine-grained PATs, and IP allowlisting |
Three Layers of Protection
| Layer | What It Protects | You Control |
|---|---|---|
| 1. User Control | Which MCP servers run | Config file |
| 2. Token Permissions | What each server can do | API token scopes |
| 3. Service Access | What resources are accessible | Service-side policies |
2025 Security Enhancements
| Feature | Description |
|---|---|
| OAuth 2.1 + PKCE | Authorization Code flow with Proof Key |
| RFC 9700 | IETF best practices for OAuth security |
| Resource Indicators | Explicit target resource specification |
| No Token Passthrough | MCP servers don’t pass tokens upstream |
| Zero Trust | Behavioral analytics and pattern detection |
Credential Management
Never Do This
// ❌ BAD: Credentials in version control
{
"mcpServers": {
"github": {
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_real_token_12345"
}
}
}
}Do This Instead
Option 1: Environment Variables
// ✅ GOOD: Reference environment variables
{
"mcpServers": {
"github": {
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
}
}
}
}Option 2: Separate Config (not in version control)
Keep claude_desktop_config.json out of your repo by:
- Adding to
.gitignore - Using system-level paths only
- Never copying to project directories
Option 3: Secret Manager (Enterprise)
# Use a secret manager to inject credentials
export GITHUB_TOKEN=$(aws secretsmanager get-secret-value \
--secret-id mcp/github --query SecretString --output text)Credential Storage Locations
| Platform | Config Location | Secure? |
|---|---|---|
| macOS | ~/Library/Application Support/Claude/... | ✓ User-only |
| Windows | %APPDATA%/Claude/... | ✓ User-only |
| Linux | ~/.config/Claude/... | ✓ User-only |
Verify permissions:
# macOS/Linux - Should be readable only by you
ls -la ~/Library/Application\ Support/Claude/
# Expected: -rw-------For more on responsible AI usage, see the Understanding AI Safety, Ethics, and Limitations guide.
Principle of Least Privilege
By Service Type
| Service | Minimum Required | Avoid |
|---|---|---|
| GitHub | repo:read, specific repos | admin:org, all repos |
| AWS | Read-only, specific resources | AdministratorAccess |
| Slack | Specific channels, read-only | Workspace admin |
| Filesystem | Specific directories | Home directory |
| Database | Read-only, specific tables | DBA privileges |
GitHub Token Permissions
For Code Review (Read-Only):
☑️ repo (read only)
☑️ read:org
☐ write:packages
☐ admin:org
☐ delete_repoFor PR Creation (Limited Write):
☑️ repo (read & write)
☑️ read:org
☐ admin:org
☐ delete_repoAWS IAM Policies
Minimal S3 Read:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::specific-bucket",
"arn:aws:s3:::specific-bucket/*"
]
}
]
}Filesystem Restrictions
{
"mcpServers": {
"filesystem": {
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/Users/me/projects/safe-project" // ✅ Specific folder
// NOT "/Users/me" // ❌ Home directory
]
}
}
}For more on file access patterns, see the Filesystem MCP guide.
Token Scoping Strategies
Designing a resilient token scoping architecture ensures that even if an LLM is tricked by an indirect prompt injection payload embedded in an untrusted GitHub issue, web page, or database row, the resulting blast radius is strictly contained. As we detail in Context Engineering for AI Agents, an AI agent should never hold a single monolithic credential that spans multiple environments or services. Instead, partition credentials along three dimensions: per-service isolation (dedicated tokens for each MCP server), per-environment separation (read-only tokens for production, write-enabled tokens only in isolated sandbox accounts), and time-bounded progression (starting every integration in read-only mode for the first 14 to 30 days before enabling any mutating tools).
Strategy 1: One Token Per Service
{
"mcpServers": {
"github": {
"env": { "GITHUB_TOKEN": "ghp_repo_readonly_token" }
},
"slack": {
"env": { "SLACK_BOT_TOKEN": "xoxb_channel_readonly" }
},
"aws": {
"env": { "AWS_ACCESS_KEY_ID": "AKIA_readonly_key" }
}
}
}Strategy 2: Environment Separation
{
"mcpServers": {
"github-prod": {
"env": { "GITHUB_TOKEN": "ghp_prod_readonly" }
},
"github-dev": {
"env": { "GITHUB_TOKEN": "ghp_dev_full_access" }
}
}
}Strategy 3: Read-Only by Default
Start with read-only access, upgrade only when needed:
Week 1: Read-only access -> Verify patterns
Week 2: Same -> Build confidence
Week 3: Selective write -> Specific operations only
Week 4: Review and audit -> Adjust as neededAudit and Monitoring
Enable Service-Side Logging
| Service | How to Enable | What’s Logged |
|---|---|---|
| GitHub | Settings → Audit log | API calls, repos accessed |
| AWS | CloudTrail | All API calls |
| Slack | Workspace Analytics | Messages, channels |
| Cloudflare | Audit Logs | Zone changes, API calls |
| Sentry | API Logs | Issues accessed |
What to Monitor
✅ Monitor:
- API call frequency
- Unusual access patterns
- Failed authentication attempts
- Access to sensitive resources
⚠️ Alert on:
- Tokens used from new locations
- Access outside normal hours
- Rate limit warnings
- Permission denied errorsMonthly Security Review
1. Review API key usage
2. Check access logs for anomalies
3. Revoke unused tokens
4. Update permissions if scope creep
5. Rotate credentials if neededFor more on AI agent capabilities, see the AI Agents guide.
Secure Configuration Patterns
Implementing production-grade MCP configurations requires hardening both the authentication credentials passed to the server and the operating system sandbox in which the server process executes. Rather than running third-party npx or uvx packages directly on your host filesystem with access to ~/.ssh, ~/.aws, and .env files, encapsulate untrusted or network-facing MCP servers inside rootless Docker containers with dropped Linux capabilities (--cap-drop=ALL), read-only root filesystems (--read-only), and explicit network egress policies. Below are five battle-tested configuration patterns covering read-only GitHub toolsets, restricted filesystem mounts, read-only PostgreSQL roles, environment-split AWS profiles, and hardened Docker container isolation.
Pattern 1: Read-Only Production
{
"mcpServers": {
"github-prod": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_PROD_READONLY}"
}
}
}
}Pattern 2: Restricted Filesystem
{
"mcpServers": {
"files-readonly": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"--read-only",
"/safe/directory/only"
]
}
}
}Pattern 3: Scoped Database
{
"mcpServers": {
"postgres": {
"env": {
"DATABASE_URL": "postgresql://mcp_reader:pass@host/db"
// User has SELECT only, no INSERT/UPDATE/DELETE
}
}
}
}Pattern 4: Split by Sensitivity
{
"mcpServers": {
// High security - minimal access
"aws-prod": {
"env": {
"AWS_PROFILE": "mcp-prod-readonly"
}
},
// Lower security - more access
"aws-dev": {
"env": {
"AWS_PROFILE": "mcp-dev-full"
}
}
}
}Pattern 5: Hardened Rootless Docker Sandbox with Toolset Pinning
Running MCP servers inside a rootless container with --cap-drop=ALL, --security-opt=no-new-privileges, and explicit memory/CPU limits (--memory=512m --cpus=1) prevents local privilege escalation or host credential theft even if a server dependency contains a vulnerability like CVE-2025-68144:
{
"mcpServers": {
"github-hardened": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"--read-only",
"--cap-drop=ALL",
"--security-opt=no-new-privileges:true",
"--memory=512m",
"--cpus=1.0",
"-e",
"GITHUB_PERSONAL_ACCESS_TOKEN",
"-e",
"GITHUB_TOOLSETS=repos,issues,pull_requests",
"-e",
"GITHUB_READ_ONLY=1",
"ghcr.io/github/github-mcp-server:v0.25.0"
],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_READONLY_PAT}"
}
}
}
}Common Security Mistakes
Across enterprise AI security audits, more than 85% of MCP security incidents stem from five recurring configuration anti-patterns: over-privileged static API keys, shared personal/bot tokens, unrestricted root or home directory mounts, plaintext secrets committed to Git repositories, and unverified third-party MCP servers susceptible to Tool Poisoning or Rug Pull updates. Reviewing each anti-pattern below and enforcing automated pre-commit secret scanning (gitleaks or GitHub Secret Scanning) alongside pinned package versions (@version or Docker SHA digests rather than @latest) eliminates the vast majority of workstation and CI/CD compromises.
Mistake 1: Overly Broad Permissions
❌ "I'll just give it admin access to make it work"
✅ "Start with minimum, add only what's needed"Mistake 2: Sharing Credentials
❌ Using the same token for personal and MCP use
✅ Create dedicated MCP tokens for audit clarityMistake 3: Forgetting File Access
❌ Granting home directory to Filesystem MCP
✅ Grant only specific project foldersMistake 4: Committing Config Files
❌ Pushing claude_desktop_config.json to GitHub
✅ Add to .gitignore, use environment variablesMistake 5: Never Rotating Keys
❌ Using the same token for years
✅ Rotate quarterly or after any security eventEmergency Procedures
If a Token is Compromised
Immediate Actions (within minutes):
- Revoke the token at the service
- Create new token with same permissions
- Update MCP config with new token
- Review audit logs for unauthorized access
Follow-up (within hours):
- Assess impact - what was accessed?
- Notify stakeholders if sensitive data involved
- Review how compromise occurred
- Implement preventive measures
Service-Specific Revocation
| Service | How to Revoke |
|---|---|
| GitHub | Settings → Developer settings → Tokens → Revoke |
| AWS | IAM → Users → Security credentials → Deactivate |
| Slack | Workspace settings → Apps → Revoke |
| Cloudflare | Profile → API Tokens → Revoke |
Enterprise Security Considerations
Scaling Model Context Protocol adoption across an engineering organization of 50 to 5,000+ developers requires moving beyond individual workstation config files toward centralized MCP Gateways, OAuth 2.1 identity federation, and continuous compliance telemetry. Enterprise security architects should deploy an internal MCP Registry and Gateway that enforces an explicit allowlist of vetted MCP servers, verifies cryptographic signatures on tool schemas (tools/list), strips sensitive PII patterns before tool outputs enter the LLM context window, and streams structured JSON audit logs (including user_id, mcp_server, tool_name, and arguments_hash) to your SIEM for SOC 2, ISO 27001, GDPR, and HIPAA compliance.
Team Usage
| Practice | Implementation |
|---|---|
| Shared service accounts | Create MCP-specific service accounts |
| Centralized secrets | Use secret managers (Vault, AWS SM) |
| Access reviews | Monthly review of MCP permissions |
| Offboarding | Include MCP token revocation in process |
Compliance
| Requirement | MCP Consideration |
|---|---|
| SOC 2 | Document MCP access, enable audit logs |
| GDPR | Ensure no personal data via Filesystem |
| HIPAA | Avoid healthcare data in MCP-accessible systems |
| PCI | Never give MCP access to cardholder data |
Security Checklist
Use this comprehensive three-stage operational security checklist when onboarding any new local stdio or remote Streamable HTTP MCP server into your developer environment or production agent pipeline. Before enabling a server for daily engineering workflows, verify that every credential follows least-privilege scoping, confirm that your configuration files are excluded from Git tracking and validated via our JSON Formatter & Validator, and test tool behavior using synthetic non-production data. Running through these verification gates takes less than 10 minutes per server and prevents accidental data exfiltration or destructive state changes.
Initial Setup
☐ Create dedicated, fine-grained API tokens for each MCP server (never reuse personal PATs)
☐ Apply minimum required read-only permissions for the initial 14-to-30-day evaluation window
☐ Store credentials in OS keychain or secret managers (1Password CLI, AWS Secrets Manager, Vault)
☐ Add claude_desktop_config.json, .cursor/mcp.json, and .vscode/mcp.json with secrets to .gitignore
☐ Verify chmod 600 (-rw-------) file permissions on local MCP configuration files
☐ Pin exact package versions or Docker image SHA-256 digests instead of mutable @latest tagsOngoing Maintenance
☐ Review GitHub, AWS CloudTrail, Slack, and database audit logs monthly for anomalous tool calls
☐ Rotate static API tokens and OAuth client secrets every 90 days
☐ Revoke unused or orphaned MCP integration tokens immediately upon project completion
☐ Inspect MCP server updates for unexpected changes in tools/list descriptions (Rug Pull defense)
☐ Audit which local and remote MCP servers are active across developer workstationsBefore Production Use
☐ Enforce read-only database roles (default_transaction_read_only = on) and statement_timeout caps
☐ Require OAuth 2.1 with PKCE and RFC 8707 audience-bound tokens for all remote HTTP MCP servers
☐ Block RFC 1918 private IPv4 ranges and cloud metadata endpoints (169.254.169.254) against SSRF
☐ Configure automated SIEM alerts on HTTP 401/403 spikes and rate-limit exhaustion
☐ Document an incident response runbook for immediate token revocation within 5 minutesSummary
MCP security is about layers of protection:
- ✓ Layer 1: You control which servers run
- ✓ Layer 2: Token scopes limit each server
- ✓ Layer 3: Service policies restrict resources
2025 Security Standards:
- OAuth 2.1 with PKCE (RFC 9700)
- Resource Indicators (RFC 8707)
- No token passthrough to upstream APIs
- Zero Trust architecture alignment
- Separated authorization/resource servers
Key Practices:
| Practice | Why |
|---|---|
| Least privilege | Limit blast radius |
| Scoped tokens | Clear audit trail |
| Secure storage | Prevent exposure |
| Regular audits | Catch issues early |
| Key rotation | Limit compromise impact |
Start secure, stay secure - it’s much easier to add permissions than to recover from a security incident.
Next: Learn about Combining Multiple MCPs → for powerful workflows.
Questions about MCP security? Check the MCP specification or RFC 9700 for OAuth best practices.