Remote OpenClaw

Remote OpenClaw Blog

Securing Your MCP Server Connections

8 min read ·

MCP servers give your AI agent powerful access to databases, file systems, APIs, and infrastructure. That power demands strong security. A misconfigured MCP server can expose credentials, leak sensitive data, or give an agent more access than it should have. This guide covers the essential security patterns for MCP server connections: authentication, TLS setup, token rotation, access control, audit logging, and network isolation.

Why MCP Server Security Matters

When you connect an MCP server to your agent, you are creating a bridge between an AI model and your real infrastructure. The agent can read files, query databases, call APIs, and modify configurations. If that bridge is not secured, anyone who can interact with the agent — or anyone who compromises the agent's communication channel — can access those capabilities.

MCP server security is not optional. It is a baseline requirement for any production deployment. The patterns in this guide apply whether you are running MCP servers locally on your development machine or deploying them in a shared team environment.

Authentication Patterns

Authentication determines who or what is allowed to connect to your MCP server. There are three primary patterns, each suited to different deployment scenarios.

API Keys

API keys are the simplest authentication method. The MCP server expects a secret key in each request, and rejects any request that does not include a valid key. This works well for local development and single-user setups where the agent and server run on the same machine.

To configure API key authentication, set the key in your MCP server configuration:

{
  "mcpServers": {
    "database": {
      "command": "mcp-server-postgres",
      "env": {
        "MCP_API_KEY": "your-secret-key-here",
        "DATABASE_URL": "postgresql://user:pass@localhost:5432/mydb"
      }
    }
  }
}

Store the API key in a secret manager or environment variable — never commit it to version control. Rotate the key regularly and use a unique key for each MCP server instance.

When to use: Local development, single-user setups, or as a simple layer when combined with network-level security.

OAuth 2.0

OAuth 2.0 is the right choice when multiple users or services need to connect to an MCP server with different permission levels. OAuth supports scoped access tokens, refresh flows, and integration with existing identity providers like Okta, Auth0, or Azure AD.

An OAuth-secured MCP server validates the bearer token on each tool call, checks its scopes against the requested operation, and rejects unauthorized requests. This means you can give one user read-only access to a database while another user gets read-write access, all through the same MCP server.

The typical flow works like this:

  1. The client authenticates with the identity provider and obtains an access token.
  2. The client passes the token to the MCP server in the connection handshake.
  3. The MCP server validates the token with the identity provider on each tool call.
  4. If the token is expired, the client uses its refresh token to obtain a new access token.
{
  "mcpServers": {
    "database": {
      "command": "mcp-server-postgres",
      "env": {
        "OAUTH_ISSUER": "https://your-idp.com",
        "OAUTH_AUDIENCE": "mcp-database-server",
        "OAUTH_REQUIRED_SCOPE": "db:read db:write"
      }
    }
  }
}

When to use: Team environments, multi-user deployments, or any scenario where you need role-based access control.

Mutual TLS (mTLS)

Mutual TLS provides the strongest authentication guarantee. Both the client and server present certificates, and each side verifies the other's identity. This ensures that only authorized clients can connect to the MCP server, and the client can verify it is talking to the legitimate server.

mTLS is particularly valuable for remote MCP servers deployed in production environments. It prevents man-in-the-middle attacks, ensures connection authenticity, and integrates well with service mesh architectures like Istio or Linkerd.

Setting up mTLS requires generating a certificate authority, issuing client and server certificates, and configuring both sides to validate the certificate chain:

# Generate a certificate authority
openssl req -x509 -newkey rsa:4096 -keyout ca-key.pem -out ca-cert.pem -days 365 -nodes -subj "/CN=MCP CA"

# Generate server certificate
openssl req -newkey rsa:4096 -keyout server-key.pem -out server-csr.pem -nodes -subj "/CN=mcp-server"
openssl x509 -req -in server-csr.pem -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem -days 365

# Generate client certificate
openssl req -newkey rsa:4096 -keyout client-key.pem -out client-csr.pem -nodes -subj "/CN=mcp-client"
openssl x509 -req -in client-csr.pem -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -out client-cert.pem -days 365

Configure the MCP server to require client certificates:

{
  "mcpServers": {
    "database": {
      "command": "mcp-server-postgres",
      "env": {
        "TLS_CERT": "/path/to/server-cert.pem",
        "TLS_KEY": "/path/to/server-key.pem",
        "TLS_CA": "/path/to/ca-cert.pem",
        "TLS_REQUIRE_CLIENT_CERT": "true"
      }
    }
  }
}

When to use: Production deployments, remote MCP servers, environments with strict compliance requirements.

TLS Configuration

Every MCP server connection that crosses a network boundary must use TLS. Even if you are using API keys or OAuth for authentication, TLS protects the data in transit from eavesdropping and tampering.

For local MCP servers communicating over standard I/O or Unix sockets, TLS is not strictly necessary because the communication never leaves the machine. But for any TCP-based connection, enforce TLS 1.2 or higher.

Key TLS configuration practices:

  • Minimum version: Set TLS 1.2 as the minimum. TLS 1.3 is preferred when both sides support it.
  • Cipher suites: Restrict to strong cipher suites. Disable older algorithms like RC4, 3DES, and SHA-1.
  • Certificate validation: Always validate the server certificate chain. Do not disable certificate verification in production.
  • HSTS headers: If your MCP server exposes an HTTP management interface, enable HTTP Strict Transport Security.

Marketplace

Free skills and AI personas for OpenClaw — browse the marketplace.

Browse the Marketplace →

Token Rotation

Static credentials are a liability. API keys that never change accumulate risk over time — every day they exist is another day they could be leaked. Implement token rotation to limit the blast radius of a compromised credential.

Automatic Rotation Strategies

Time-based rotation: Rotate API keys on a fixed schedule, such as every 30 or 90 days. Use a secret manager like AWS Secrets Manager, HashiCorp Vault, or 1Password to automate the rotation and update the MCP server configuration.

Event-based rotation: Rotate immediately when a team member leaves, when a credential might have been exposed, or after a security incident.

Short-lived tokens: Use OAuth access tokens with short expiration times (15 minutes to 1 hour) combined with refresh tokens. The MCP server validates token expiration on every call, and the client transparently refreshes expired tokens.

# Example: rotating an API key with Vault
vault kv put secret/mcp-server/database api_key="$(openssl rand -hex 32)"

After rotating a key, verify that the MCP server picks up the new credential. Most servers require a restart or a configuration reload signal.

Access Control

Authentication answers "who are you?" — access control answers "what are you allowed to do?" Even after a client authenticates successfully, you should restrict which tools and operations they can access.

Principle of Least Privilege

Configure each MCP server to expose only the tools that the agent actually needs. If your workflow only requires reading from a database, do not expose write operations. If the agent only needs to access a specific directory, restrict file system access to that directory.

{
  "mcpServers": {
    "database": {
      "command": "mcp-server-postgres",
      "env": {
        "DATABASE_URL": "postgresql://readonly_user:pass@localhost:5432/mydb",
        "ALLOWED_OPERATIONS": "query,describe_table,list_tables"
      }
    }
  }
}

Role-Based Access Control

For team environments, define roles with specific permission sets. A developer might have read-write access to staging databases, while a CI pipeline has read-only access to production. Map these roles to OAuth scopes or client certificates.

Tool-Level Permissions

Some MCP servers support tool-level permissions where you can enable or disable specific tools per client. This lets you expose a broad set of capabilities from one server while restricting individual clients to their required subset.

Audit Logging

You cannot secure what you cannot observe. Every MCP server should log tool calls, authentication events, and access control decisions.

Essential audit log entries include:

  • Timestamp of each tool call.
  • Client identity — who made the request.
  • Tool name and parameters — what was requested.
  • Result status — success or failure.
  • Error details — why a request was rejected.

Ship these logs to a centralized logging system like Elasticsearch, Datadog, or CloudWatch. Set up alerts for anomalous patterns: unexpected tool calls, repeated authentication failures, or access from unusual IP addresses.

{
  "mcpServers": {
    "database": {
      "command": "mcp-server-postgres",
      "env": {
        "AUDIT_LOG_ENABLED": "true",
        "AUDIT_LOG_DESTINATION": "/var/log/mcp/database-audit.log",
        "AUDIT_LOG_LEVEL": "info"
      }
    }
  }
}

Review audit logs regularly. They are your primary source of truth for understanding how agents interact with your infrastructure.

Network Isolation

Network isolation is your last line of defense. Even if authentication and access control fail, network boundaries prevent unauthorized access to your MCP servers.

Local-Only Binding

For development MCP servers, bind to localhost only. This ensures that only processes on the same machine can connect.

Private Networks

For team deployments, run MCP servers in a private network segment that is not accessible from the public internet. Use a VPN or bastion host for remote access.

Firewall Rules

Configure firewall rules to allow connections only from known client IP addresses or CIDR ranges. Block all other traffic to the MCP server ports.

Container Isolation

If you run MCP servers in containers, use network policies to restrict which pods or services can communicate with the MCP server. Kubernetes NetworkPolicies or Docker network configurations provide this isolation.

Security Checklist

Before deploying an MCP server to a shared or production environment, verify these items:

  • Authentication is configured and tested.
  • TLS is enabled for all network connections.
  • Credentials are stored in a secret manager, not in configuration files.
  • Token rotation is automated on a defined schedule.
  • Access control restricts the agent to the minimum required operations.
  • Audit logging is enabled and logs are shipped to a centralized system.
  • Network isolation prevents unauthorized access to MCP server ports.
  • Client certificates or keys are rotated when team members change.

Conclusion

Securing MCP server connections is not a one-time task — it is an ongoing practice. Start with authentication and TLS as your baseline, then layer on access control, audit logging, and network isolation. Automate token rotation so credentials do not become stale. Review audit logs to catch anomalies early. The investment in security pays off every time you avoid a credential leak, an unauthorized access, or a compliance finding.


Browse the Skills Directory

Find the right skill for your workflow. The OpenClaw Bazaar skills directory has over 2,300 community-rated skills — searchable, sortable, and free to install.

Browse Skills →

Personas Include MCP Servers

OpenClaw personas come with pre-configured MCP server connections — no manual setup needed. Pick a persona and the right servers are already wired in. Compare personas →