MCP Library updated 14 min read

MCP Security Best Practices: Protecting Your AI Integrations

Security guide for MCP servers. Learn to secure credentials, manage permissions, and protect sensitive data in AI workflows.

Rajesh Praharaj

· Updated

Contents 13 sections
  1. TL;DR - Security Essentials
  2. Security Model Overview
  3. Credential Management
  4. Principle of Least Privilege
  5. Token Scoping Strategies
  6. Audit and Monitoring
  7. Secure Configuration Patterns
  8. Common Security Mistakes
  9. Emergency Procedures
  10. Enterprise Security Considerations
  11. Security Checklist
  12. Summary
  13. Frequently Asked Questions

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 inputSchema descriptions or silently mutate tool schemas after initial approval. Pin cryptographic SHA-256 hashes of tools/list definitions 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 (aud claim 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 in mcp-server-git), always run local stdio MCP servers inside rootless Docker containers (--cap-drop=ALL --read-only) with explicit directory mounts.

The Golden Rules:

  1. Least Privilege: Grant minimal required permissions
  2. Scoped Tokens: Use service-specific API keys
  3. Secure Storage: Never commit credentials
  4. Audit Logs: Monitor access regularly
  5. 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 monthly

Security 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 BoundarySource ComponentTarget ComponentPrimary Security Mechanism
Layer 1: Host-to-ServerAI Host (Claude, Cursor, VS Code)Local Stdio or Remote HTTP MCP ServerExplicit user approval, container sandboxing, and SHA-256 tool schema pinning
Layer 2: Server IdentityMCP Client / OAuth 2.1 FlowMCP Resource ServerOAuth 2.1 with PKCE, RFC 9728 metadata discovery, and RFC 8707 audience-bound tokens
Layer 3: Upstream ResourceMCP Server Execution ContextCloud API / Database (GitHub, AWS, Postgres)Scoped read-only IAM roles, fine-grained PATs, and IP allowlisting

Three Layers of Protection

LayerWhat It ProtectsYou Control
1. User ControlWhich MCP servers runConfig file
2. Token PermissionsWhat each server can doAPI token scopes
3. Service AccessWhat resources are accessibleService-side policies

2025 Security Enhancements

FeatureDescription
OAuth 2.1 + PKCEAuthorization Code flow with Proof Key
RFC 9700IETF best practices for OAuth security
Resource IndicatorsExplicit target resource specification
No Token PassthroughMCP servers don’t pass tokens upstream
Zero TrustBehavioral 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

PlatformConfig LocationSecure?
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

ServiceMinimum RequiredAvoid
GitHubrepo:read, specific reposadmin:org, all repos
AWSRead-only, specific resourcesAdministratorAccess
SlackSpecific channels, read-onlyWorkspace admin
FilesystemSpecific directoriesHome directory
DatabaseRead-only, specific tablesDBA privileges

GitHub Token Permissions

For Code Review (Read-Only):

☑️ repo (read only)
☑️ read:org
☐ write:packages
☐ admin:org
☐ delete_repo

For PR Creation (Limited Write):

☑️ repo (read & write)
☑️ read:org
☐ admin:org
☐ delete_repo

AWS 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 needed

Audit and Monitoring

Enable Service-Side Logging

ServiceHow to EnableWhat’s Logged
GitHubSettings → Audit logAPI calls, repos accessed
AWSCloudTrailAll API calls
SlackWorkspace AnalyticsMessages, channels
CloudflareAudit LogsZone changes, API calls
SentryAPI LogsIssues 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 errors

Monthly 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 needed

For 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 clarity

Mistake 3: Forgetting File Access

❌ Granting home directory to Filesystem MCP
✅ Grant only specific project folders

Mistake 4: Committing Config Files

❌ Pushing claude_desktop_config.json to GitHub
✅ Add to .gitignore, use environment variables

Mistake 5: Never Rotating Keys

❌ Using the same token for years
✅ Rotate quarterly or after any security event

Emergency Procedures

If a Token is Compromised

Immediate Actions (within minutes):

  1. Revoke the token at the service
  2. Create new token with same permissions
  3. Update MCP config with new token
  4. Review audit logs for unauthorized access

Follow-up (within hours):

  1. Assess impact - what was accessed?
  2. Notify stakeholders if sensitive data involved
  3. Review how compromise occurred
  4. Implement preventive measures

Service-Specific Revocation

ServiceHow to Revoke
GitHubSettings → Developer settings → Tokens → Revoke
AWSIAM → Users → Security credentials → Deactivate
SlackWorkspace settings → Apps → Revoke
CloudflareProfile → 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

PracticeImplementation
Shared service accountsCreate MCP-specific service accounts
Centralized secretsUse secret managers (Vault, AWS SM)
Access reviewsMonthly review of MCP permissions
OffboardingInclude MCP token revocation in process

Compliance

RequirementMCP Consideration
SOC 2Document MCP access, enable audit logs
GDPREnsure no personal data via Filesystem
HIPAAAvoid healthcare data in MCP-accessible systems
PCINever 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 tags

Ongoing 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 workstations

Before 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 minutes

Summary

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:

PracticeWhy
Least privilegeLimit blast radius
Scoped tokensClear audit trail
Secure storagePrevent exposure
Regular auditsCatch issues early
Key rotationLimit 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.

Frequently Asked Questions

Is it safe to give AI access to my tools and data?

Yes, when configured properly. MCP's 2025 security model includes OAuth 2.1 with PKCE, explicit user consent, scoped tokens, and resource indicators for enhanced protection.

Where are MCP credentials stored?

Credentials are stored in your local MCP configuration file. This file should never be committed to version control or shared.

Can AI access things I didn't authorize?

No. MCP servers can only access what their specific API token permits. AI cannot escape to unauthorized systems or elevate permissions.

How do I audit what AI accessed?

Most services (GitHub, AWS, Slack, etc.) provide API access logs. Enable these logs and review them periodically to ensure appropriate usage.

What if an API key is compromised?

Immediately revoke the compromised key and create a new one. Because MCP uses scoped tokens, the impact is limited to that specific service.

Should I use production credentials with AI?

Start with read-only access to production. For write operations, consider using staging environments first or implementing approval workflows.

How do I limit which files AI can access?

Use the Filesystem MCP's directory restrictions. Only grant access to specific folders, never your entire home directory.

Can different AI tools share the same credentials?

You can, but it's better to create separate credentials for each tool for better audit trails and easier revocation if needed.

Written by Rajesh Praharaj

Product Leader & AI Builder

Product leader and AI builder focused on practical LLM systems, Model Context Protocol (MCP) integrations, agentic workflows, and free browser-based tools for product & engineering teams.

Was this page helpful?

Let us know if you found what you were looking for.