mcp-server-security – Agents & Automation skill for AI agents
Secure Model Context Protocol (MCP) servers with transport encryption, tool authorization, input validation, and audit logging for safe AI agent integrations.
Install the mcp-server-security skill with one command
Pick the tool you use, copy the command and paste it in your terminal. The skill lands in that tool's skills folder and is ready in your next session.
Claude Code
mkdir -p ~/.claude/skills && curl -fsSL https://skill.dn1nguoi.com/z/mcp-server-security-98243.tgz | tar xz -C ~/.claude/skills
Call it in Claude Code: /mcp-server-security – then describe the task you want done.
Codex
mkdir -p ~/.codex/skills && curl -fsSL https://skill.dn1nguoi.com/z/mcp-server-security-98243.tgz | tar xz -C ~/.codex/skills
Call it in Codex: $mcp-server-security – then describe the task you want done.
Hermes Agent
mkdir -p ~/.hermes/skills && curl -fsSL https://skill.dn1nguoi.com/z/mcp-server-security-98243.tgz | tar xz -C ~/.hermes/skills
Call it in Hermes Agent: /mcp-server-security – then describe the task you want done.
DeepSeek
mkdir -p ~/.deepcode/skills && curl -fsSL https://skill.dn1nguoi.com/z/mcp-server-security-98243.tgz | tar xz -C ~/.deepcode/skills
Call it in DeepSeek: /mcp-server-security – then describe the task you want done.
SKILL.md content
MCP Server Security
Comprehensive hardening guide for Model Context Protocol (MCP) servers. MCP is the open
standard for connecting AI agents to external tools, data sources, and services. Because
MCP servers execute real actions on real infrastructure, they are a high-value attack
surface. This skill covers every layer of defense you need before exposing an MCP server
to agents in production.
---
2. MCP Threat Model
Before hardening, understand what you are defending against.
| Threat | Vector | Impact |
|-------------------------------|---------------------------------------------------------------|-------------------------------------|
| Unauthorized tool access | Agent calls tools the user should not have access to | Privilege escalation, data breach |
| Prompt injection via resources| Malicious content in MCP resources influences agent behavior | Arbitrary tool execution |
| Data exfiltration via results | Tool results leak sensitive data back to an untrusted agent | Data loss, compliance violation |
| SSRF via MCP tools | Agent tricks a tool into making internal network requests | Internal service compromise |
| Credential theft | API keys or tokens stored insecurely on the MCP server | Full account takeover |
| Denial of service | Agent floods server with tool calls or huge payloads | Service unavailability |
| Man-in-the-middle | Unencrypted transport between agent and MCP server | Eavesdropping, request tampering |
| Supply chain compromise | Malicious MCP server package or plugin | Arbitrary code execution |
---
3. Transport Security
3.1 TLS for Streamable HTTP and SSE Transports
Every MCP server exposed over HTTP must terminate TLS. Never run plain HTTP in
production.
Nginx reverse proxy with TLS termination for an MCP server:
# /etc/nginx/sites-enabled/mcp-server.conf
server {
listen 443 ssl http2;
server_name mcp.internal.example.com;
ssl_certificate /etc/ssl/certs/mcp-server.crt;
ssl_certificate_key /etc/ssl/private/mcp-server.key;
ssl_protocols TLSv1.3;
ssl_ciphers TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256;
ssl_prefer_server_ciphers on;
ssl_session_timeout 1d;
ssl_session_tickets off;
# HSTS header
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
location / {
proxy_pass http://127.0.0.1:3001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
# SSE-specific: disable buffering so events stream immediately
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 86400s;
}
}3.2 mTLS Between Agent and Server
For high-security environments, require the agent (client) to present a certificate.
# Add to the server block above
ssl_client_certificate /etc/ssl/certs/agent-ca.crt;
ssl_verify_client on;
ssl_verify_depth 2;Generate a client certificate for an agent:
# Create CA (one-time)
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 \
-days 365 -noenc -keyout ca-key.pem -out ca-cert.pem \
-subj "/CN=MCP Agent CA"
# Create agent client cert signed by the CA
openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 \
-noenc -keyout agent-key.pem -out agent-csr.pem \
-subj "/CN=agent-orchestrator-01"
openssl x509 -req -in agent-csr.pem -CA ca-cert.pem -CAkey ca-key.pem \
-CAcreateserial -out agent-cert.pem -days 903.3 Securing stdio Transport
For local stdio-based servers, the attack surface is the process boundary itself:
Use an already reviewed, version-pinned local server entrypoint and a separately enforced sandbox. Do not launch a moving npx -y package or describe Node flags as a complete host-permission boundary. The server needs runtime/module access in addition to its data root; network, process creation, links and writes need explicit platform controls. A configuration example is not permission to create or replace a user's host entry.
{
"mcpServers": {
"reviewed-filesystem": {
"command": "/absolute/path/to/node",
"args": ["/absolute/path/to/reviewed-server/index.js", "/absolute/path/to/approved-data"]
}
}
}Replace every path with an existing reviewed runtime, bind its content/version, and test actual denied reads/writes/egress in isolation before enabling it.
---
4. Authentication and Authorization
4.1 OAuth 2.1 Integration
MCP's Streamable HTTP transport supports OAuth 2.1 for client authentication. Configure
your server to validate bearer tokens on every request.
// src/auth.ts - OAuth 2.1 token validation middleware for an MCP server
import express from "express";
import jwt from "jsonwebtoken";
// Middleware only: supply a verified issuer/key/resource binding, revocation policy,
// MCP transport/session wiring and authorization before exposing any endpoint.
const app = express();
// OAuth 2.1 token validation middleware
function validateBearerToken(req: express.Request, res: express.Response, next: express.NextFunction) {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith("Bearer ")) {
return res.status(401).json({ error: "missing_token" });
}
const token = authHeader.slice(7);
try {
const payload = jwt.verify(token, process.env.OAUTH_PUBLIC_KEY!, {
algorithms: ["RS256"],
issuer: "https://auth.example.com",
audience: "mcp-server",
});
if (typeof payload !== "object" || typeof payload.sub !== "string" || !payload.sub ||
typeof payload.exp !== "number" || !Number.isFinite(payload.exp) || !Number.isInteger(payload.exp)) {
return res.status(403).json({ error: "invalid_token" });
}
// Attach scopes for downstream authorization
(req as any).tokenScopes = typeof payload.scope === "string" ? payload.scope.split(" ") : [];
(req as any).userId = (payload as any).sub;
next();
} catch {
return res.status(403).json({ error: "invalid_token" });
}
}
app.use("/mcp", validateBearerToken);Require expiry and a nonempty subject in addition to the verified signature, issuer and resource audience. Session IDs are not authentication. Derive roles/scopes from verified server policy, never caller-supplied role names; wildcard admin examples do not grant blanket execution permission. Validate key revocation/rotation and per-tool resource authorization separately.
4.2 API Key Management
For simpler deployments, use hashed API keys stored server-side:
// src/apikeys.ts
import { createHash, timingSafeEqual } from "crypto";
interface ApiKeyRecord {
hashedKey: string;
userId: string;
allowedTools: string[];
rateLimit: number; // requests per minute
expiresAt: Date;
}
// Store hashed keys, never plaintext
const apiKeyStore: Map<string, ApiKeyRecord> = new Map();
export function registerApiKey(plainKey: string, record: Omit<ApiKeyRecord, "hashedKey">) {
const hashed = createHash("sha256").update(plainKey).digest("hex");
apiKeyStore.set(hashed, { ...record, hashedKey: hashed });
}
export function validateApiKey(plainKey: string): ApiKeyRecord | null {
const hashed = createHash("sha256").update(plainKey).digest("hex");
const record = apiKeyStore.get(hashed);
if (!record) return null;
if (new Date() > record.expiresAt) {
apiKeyStore.delete(hashed);
return null;
}
return record;
}---
5. Tool Authorization
5.1 Allowlist Patterns
Never expose every tool to every user. Define an explicit allowlist:
# config/tool-policy.yaml
policies:
- role: developer
allowed_tools:
- "read_file"
- "search_code"
- "run_tests"
denied_tools:
- "execute_command"
- "write_file"
- "delete_file"
- role: admin
allowed_tools: ["*"]
denied_tools: []
- role: readonly-agent
allowed_tools:
- "read_file"
- "list_directory"
- "query_database:SELECT"
denied_tools: ["*"]
dangerous_tools:
- name: "execute_command"
risk: critical
requires_approval: true
max_executions_per_session: 5
- name: "write_file"
risk: high
requires_approval: true
- name: "query_database"
risk: medium
allowed_operations: ["SELECT"]5.2 Per-User Tool Access Enforcement
// src/toolAuth.ts
import { readFileSync } from "fs";
import { parse } from "yaml";
interface ToolPolicy {
role: string;
allowed_tools: string[];
denied_tools:… (full content is in the download package)
Related skills
- memory-handoff – Portable session handoff across agent CLIs: read a project's handoff file at session…
- memory-safety-patterns – Cross-language patterns for memory-safe programming including RAII, ownership, smart…
- memory-systems – Design short-term, long-term, and graph-based memory architectures. Use when building…
- mercury-mcp – Cheatsheet for the Mercury (proton) MCP tools. Use when connected to the Mercury MCP…
- mesh-memory – Self-hosted semantic memory for AI agents via MCP. Save worklogs, decisions, and notes…
- microsoft-teams-automation – Automate Microsoft Teams tasks via Rube MCP (Composio): send messages, manage channels…
- miro-automation – Automate Miro tasks via Rube MCP (Composio): boards, items, sticky notes, frames…
- mixpanel-automation – Automate Mixpanel tasks via Rube MCP (Composio): events, segmentation, funnels, cohorts…