mcp-server-security
Secure Model Context Protocol (MCP) servers with transport encryption, tool authorization, input validation, and audit logging for safe AI agent integrations.
What this skill does
# 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.
---
## 1. When to Use This Skill
Apply this skill whenever you are:
- Deploying an MCP server that exposes tools (filesystem, database, API) to AI agents.
- Connecting an agent runtime (Claude Desktop, Cursor, a custom orchestrator) to one or
more MCP servers over stdio, SSE, or Streamable HTTP transport.
- Building a multi-tenant platform where multiple users share the same MCP server.
- Passing sensitive data (PII, credentials, internal documents) through MCP resources.
- Operating in a regulated environment (SOC 2, HIPAA, PCI-DSS) where tool invocations
must be auditable.
If your MCP server only runs locally over stdio for a single developer with no network
exposure, you can relax some transport-layer controls -- but input validation and audit
logging still apply.
---
## 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:**
```nginx
# /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.
```nginx
# 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:**
```bash
# 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 90
```
### 3.3 Securing stdio Transport
For local stdio-based servers, the attack surface is the process boundary itself:
```jsonc
// claude_desktop_config.json - restrict stdio server permissions
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/safe-dir"],
"env": {
"NODE_OPTIONS": "--experimental-permission --allow-fs-read=/home/user/safe-dir --allow-fs-write=/home/user/safe-dir"
}
}
}
}
```
---
## 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.
```typescript
// src/auth.ts - OAuth 2.1 token validation middleware for an MCP server
import { createServer } from "@modelcontextprotocol/sdk/server/index.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import express from "express";
import jwt from "jsonwebtoken";
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",
});
// Attach scopes for downstream authorization
(req as any).tokenScopes = (payload as any).scope?.split(" ") || [];
(req as any).userId = (payload as any).sub;
next();
} catch {
return res.status(403).json({ error: "invalid_token" });
}
}
app.use("/mcp", validateBearerToken);
```
### 4.2 API Key Management
For simpler deployments, use hashed API keys stored server-side:
```typescript
// 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:
```yaml
# config/tool-policy.yaml
policies:
- role: developer
allowed_tools:
- "read_file"
- "search_code"
- "run_tests"
denied_tools:
- "execute_command"
- "write_file"
- "deletRelated in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.