Mar 09, 2026
14 min read

Best practices for securing credentials in MCP servers

Best practices for securing credentials in MCP servers

Developers are building advanced autonomous systems in 2026, but still using 1996 plaintext file patterns to secure them. It's almost comical when said out loud.

Nearly half of all model context protocol (MCP) servers in production aggregate multiple API keys, database passwords, and OAuth tokens into a single unencrypted file. For others, developers go further by hardcoding credentials directly into source code, which are later forgotten and published to public repositories or npm packages.

Attackers are no longer guessing where to look. They know these files exist and actively scan for them. One leaked configuration file is enough to grant access to GitHub repositories, sensitive data, and critical production systems. This fragile pattern, with which the majority of MCP servers are operated, should not be acceptable.

TLDR

This guide provides actionable best practices for securing MCP server credentials and reducing significant security risks, from eliminating .env files to implementing runtime secret injection, automated rotation, and enterprise-grade access control.

Best practice 1: Replace .env files with runtime secret injection

Instead of storing your secrets in a .env file that could persist to disk:

Inject them only when your MCP server starts running or executing. Use tools that support runtime injection. Doppler, for example, can inject your secrets directly into an application's process memory using process.env in Node.js or os.environ in Python:

In practice, you can add doppler run to a ChatGPT or Claude desktop config to ensure runtime injection:

Using this approach enables automated rotation, prevents unsafe token passthrough between processes, and provides an audit trail of how secrets are accessed and updated over time. It is also suitable for production MCP deployments, even for a single MCP server.

Best practice 2: Implement least privilege with per-server credentials

Another dangerous pattern is exposing a single highly privileged credential to multiple MCP servers. When one credential is reused everywhere, a single compromise becomes a system-wide incident.

This matters in real incidents. Of the 492 exposed MCP servers identified by Trend Micro, some had admin-privileged access, including management permissions on cloud service provider resources. They were actively transmitting these privileges to AI clients that sync with them.

Scope credentials access on each MCP server and limit permissions to only what the server needs. A GitHub MCP server, for example, should not have access to internal databases or unrelated services. In the event of a compromised MCP server, the damage should stop there.

On Doppler, this maps cleanly to a per-project model, where each MCP server can have its own project containing only the secrets it requires. Compromising one project does not grant access to others.

Best practice 3: Implement automated credential rotation

The main reason secrets rotation is such a problem in MCP deployments, and why Astrix found that about 53% of them rely on long-lived static client credentials, often comes back to plaintext .env files and hardcoded secrets.

Rotation in those setup situations means manually changing the token, updating the config, and then restarting all servers. Left this way, inconsistent rotation schedules creep in, until engineers reactively rotate credentials, often after a breach.

Change the storage model and implement automated credential rotation. If secrets are stored in a vault, teams can rotate tokens at scheduled intervals, and the MCP servers can fetch new tokens without manual config edits.

Below is a code example showing how automated rotation could flow to your MCP server:

Here, when Doppler rotates a secret, it triggers a webhook. That webhook event is pushed to a server manager, which verifies the signature and restarts the MCP server. On restart, the MCP process receives the newly active secret.

In production, most MCP servers are deployed with a rolling update configuration and at least two replicas to avoid downtime from restarts. But there is still a possibility of downtime due to 401 unauthorized errors when requests hit replicas with outdated secrets.

For higher-risk workloads that are less tolerant to downtimes, use a dual-credential phase. Here, both the old and new credentials remain valid during the transition window, then the old credential is retired after the entire system has moved over.

Doppler supports this via its two secret strategy: one secret instance is active, and the other is kept valid but not returned; they switch as rotation progresses.

In summary, the secret rotation practices you should adhere to include:

  • Rotate credentials every 30–90 days minimum.
  • Use dual secret rotation for zero downtime.
  • Do not rotate manually or on impulse. Use a schedule.

Best practice 4: Use OAuth 2.1 for client authentication and authorization

It was discovered that only about 8.5% of MCPs use a modern, secure authentication model, which should be a concern for any team serious about AI security in their autonomous systems. The MCP spec, updated and released on June 18, 2025, classified MCP servers as OAuth 2.1 resource servers. It also mandated that MCP clients must bind tokens to the intended MCP server by using resource indicators.

This means servers should not store or pass long-lived secrets to AI agents or large language models, nor use any MCP authorization code logic. Instead, they should rely on externalized authorization via providers such as Okta or Auth. So, as long as your MCP servers interact with AI that accesses user data, or are deployed as publicly accessible integrations, such as Stripe MCP or GitHub MCP, you should handle authentication using OAuth 2.1.

OAuth removes the dependence on long-lived secrets by issuing short-lived access tokens. These tokens typically expire within minutes to an hour and are the ones that should be passed. MCP proxy clients never see or use any static client credentials. Tokens are scoped to permitted actions and can be revoked if an agent attempts to access workflows beyond their authorization.

Below is an example of how OAuth can be implemented on an MCP server to control which agents can execute tools.

The MCP server requests validation for bearer access tokens issued by an authorization server or provider, enforces audience restriction (RFC 8707), scopes permissions, applies input validation, and then serves MCP routes:

Best practice 5: Enable comprehensive audit logging

From the case of the exposed MCP servers, it is clear that there is a dysfunction in how access and activity data are collected. MCP ecosystem security seems mostly reactive, but for servers that interact with autonomous systems, a proactive security posture should be non-negotiable.

Implement a fully functional monitoring system and audit logs in your MCP workflow. Consolidate logs for every secret, mcp proxy server, application, third-party API, and workflow into a centralized dashboard. Add integrations from your secrets manager to LLM security vendors or SIEM systems, such as Datadog or Splunk.

The code example below shows how Doppler audit events can be forwarded into a SIEM:

Here, Doppler webhook events are forwarded to Datadog logs. Monitor and set up alerts for metrics such as:

  • Unusual access times: Track when agents query your data sources or access your workflows, and alert when requests occur outside regular operating hours.
  • Failed authentication: Track repeated 401 or 403 responses. It might indicate bad actors probing your workflow or exploiting missing request validation.
  • Excessive API calls: Track bursts of API calls from a single signature or within a short window. This can be a signal of unauthorized data transfer.
  • New MCP servers: Flag unknown MCP servers trying to connect to your systems or request access. Verify signatures before granting access.
  • Credential changes: Track credential rotation events and unexpected secret updates. Ensure authorized systems are carrying them out.

With proper monitoring and audit logs in place, incident response becomes faster and more reliable. A step-by-step response after a breach is discovered includes:

  1. Kill the MCP server process from which the breach occurred.
  2. Rotate secrets immediately and expire old ones.
  3. Use SIEM logs to identify what access was used for, which systems were accessed, and what could have been taken.
  4. Before restarting, check your mcp_config.json for any backdoor servers added by the attacker.
  5. Deploy a fresh instance with new rotated credentials injected at runtime or via OAuth 2.1.

Best practice 6: Secure deployment patterns for production

You can't claim to have a secure MCP deployment if you use unsafe deployment practices. Important actions need to be carried out. First, ensure secrets are separated across development, staging, and production environments. Each environment should use different credentials with no overlap.

Use Doppler to isolate secrets across environments by storing them in separate configs within a project. This prevents accidental access to production secrets during development and limits blast radius if a lower environment is compromised.

Doppler’s environment and config separation
Doppler’s environment and config separation

Depending on operational requirements, MCP servers may be deployed using Docker, Kubernetes, CI/CD pipelines, or similar infrastructure patterns. Each deployment model has specific security considerations and appropriate security controls that must be addressed. Let's explore them.

Docker

Do not bake secrets into Docker images. If an image gets leaked or reused outside its intended environment, embedded secrets are immediately exposed. This also makes credential rotation and ephemeral workflows difficult.

Instead, inject secrets at runtime.

Run container with Doppler runtime injection:

doppler run --project github-mcp --config prd -- docker run --rm github-mcp-image

With this approach, secrets exist only in the container's process environment at runtime and are never persisted in the image.

Kubernetes

Avoid storing secrets directly in Kubernetes manifests. Plain YAML secrets are often committed to repositories or copied across environments.

Instead, use a central secrets manager and synchronize secrets into Kubernetes using an operator, such as External Secrets Operator (ESO) or a native secrets manager operator, such as the Doppler Kubernetes Operator.

Option 1: Doppler Kubernetes operator

Create a Kubernetes secret that holds your Doppler Service Token:

Apply the DopplerSecret:

Enable automatic rollout on rotation by adding this annotation to your Deployment:

Option 2: External secrets operator

To use the external secrets operator option, set the SecretStore:

Then pull the secrets into the Kubernetes operator:

The operator fetches secrets from Doppler and keeps them synchronized. When secrets rotate, Kubernetes workloads can be restarted or rolled automatically depending on your deployment strategy.

CI/CD

Secrets should never be committed to pipeline configuration files. Instead, pull secrets from a secrets manager during pipeline execution.

This ensures secrets are available only for the duration of the pipeline run and are never written to disk.

Best practice 7: Verify MCP server integrity and supply chain

A December 2025 paper from Clutch Security highlighted that about 38% of MCP servers are from unofficial sources. Another 3% were found to contain hardcoded credentials that bait developers into connecting production keys. MCP security risks are shifting away from exploiting existing weaknesses toward attackers intentionally creating the weaknesses.

Some of these malicious servers contain trojanized logic designed to exfiltrate credentials once developers connect to them. A few others are made to appear safe initially, and then later update with malicious code that enables session hijacking. In more advanced cases, attackers publish compromised sub-libraries of otherwise legitimate MCP servers, leading to remote code execution(RCE) during startup.

There is also a growing trend of typosquatting, where malicious MCP servers are published under names that closely resemble official ones, such as github-mcp-svr instead of github-mcp-server. AI hallucinations introduce an additional risk known as slopsquatting, where attackers register names of hallucinated MCPs in anticipation that developers or agents may attempt to use them.

These trends introduce potential security risks, making supply chain verification non-negotiable for modern MCP implementations. Never connect a new or third-party MCP server directly to your local machine or production systems without explicit user approval. Always evaluate it in sandboxed environments with restricted access, using external tools to observe network calls, filesystem behavior, and startup activity.

The example code below shows a Dockerfile that can act as a sandbox environment for an MCP server:

Then the MCP server can be run in the restricted container:

This blocks off access to host credentials, filesystem writes, or privileged system calls. Only after the server passes sandbox testing should it be granted scoped credentials and allowed MCP server interactions with other production or local MCP servers.

Ensure you use a verification checklist before trusting an MCP server in any environment. Here is what to add to the list:

  • Verify the maintainer: Confirm that the repository is owned by a verified organization or a reputable developer with an established history.
  • Inspect the source code: Review startup logic for unexpected network calls to malicious links, filesystem access, or obfuscated code.
  • Check dependencies: Run tools like npm audit or Snyk to identify known vulnerabilities in dependencies.
  • Review credential handling: Search for process.env or os.environ. Confirm the MCP supports runtime injection rather than requiring hardcoded credentials.
  • Sandbox deployment: Always test MCP servers in a sandboxed environment before connecting them to local or production systems.

Next steps: Implementing MCP security

We have discussed seven standard MCP security best practices, including runtime injection, scoping, rotation, OAuth, logging, deployment, and supply chain security. These research-backed approaches are informed by findings from sources such as Trend Micro, Astrix, and Clutch.

If your systems possess any of the security weaknesses highlighted, here is what to do:

  • Immediately: Replace .env files with runtime injection. A secrets management platform such as Doppler can securely store secrets and inject them into workflows at runtime.
  • By week 1: Implement per-server credential scoping. Ensure development and staging secrets are never mixed with production credentials.
  • Within weeks 2–3: Set up automated credential rotation and adopt a realistic rotation schedule of 30–90 days.
  • By the end of week 4: Ensure audit logging and the production deployment patterns discussed are fully implemented.

.env files are a security incident waiting to happen. With 48% of MCP servers still relying on them, and threat actors actively hunting for exposed credentials, this is a when-not-if scenario. The tools to do better already exist. You can implement runtime injection in minutes to remove this entire class of risk.

Enjoying this content? Stay up to date and get our latest blogs, guides, and tutorials.

Related Content

Explore More