mcp-server-security
Secure Model Context Protocol (MCP) servers with transport encryption, tool authorization, input validation, and audit logging for safe AI agent integrations.
Install / Use
npx skills add BagelHole/DevOps-Security-Agent-Skills --skill mcp-server-securityInstalls into whichever agent you are using.
SKILL.md
Installable skill definition
Quality Score
Category
SecuritySupported Platforms
Our assessment of mcp-server-security
mcp-server-security scores 88/100 on our quality scale, 624th of 1,108 Security skills we index.
Its SKILL.md is 30 KB long, well organised into 49 sections with 27 code examples: a thorough specification that gives an agent plenty to work with.
With 1,113 GitHub stars, it is one of the more widely adopted skills in the catalogue.
Maintenance, license and trust
- The repository was last updated about 6 months ago. That is recent enough to be usable, but agent tooling moves fast, so check the instructions against your agent's current version.
- Our last check on 2026-11-01 found the source still online.
- It is released under the MIT license, a permissive license that allows use, modification and commercial use with attribution.
- Its trust signals score 98/100, with no cautions. These come from repository metadata, not a code audit — read the skill file before letting an agent act on it.
Safety scan
No issues foundOur scan of the whole file found no instruction hijacking, hidden characters, credential access, data exfiltration or destructive commands. An AI review of the same text found nothing harmful.
AI review by kimi-k2.7-code on 2026-10-07. Automated pattern scan on 2026-10-07. It catches known dangerous patterns, not every risk — read a skill before letting an agent act on it.
mcp-server-security compared with similar skills
All 4 of these similar skills score higher than mcp-server-security; compare them before choosing.
| Skill | Score | Stars | Updated | Format |
|---|---|---|---|---|
| mcp-server-security (this skill)by BagelHole | 88 | 1.1k | 6mo ago | SKILL.md |
| Agent-Reachby Panniantong | 100 | 112.3k | 8d ago | CLAUDE.md |
| rufloby ruvnet | 100 | 81.9k | today | CLAUDE.md |
| headroomby headroomlabs-ai | 100 | 79.8k | today | CLAUDE.md |
| CowAgentby zhayujie | 100 | 48.0k | today | CLAUDE.md |
Frequently asked questions
- How do I install mcp-server-security?
- Run
npx skills add BagelHole/DevOps-Security-Agent-Skills --skill mcp-server-security. The install tabs above show the steps for each supported agent. - Which AI agents does mcp-server-security work with?
- It is written for Universal, as a SKILL.md file. Other agents that read the same format can often use it too.
- Is mcp-server-security safe to use?
- Our scan of the whole file found no instruction hijacking, hidden characters, credential access, data exfiltration or destructive commands. An AI review of the same text found nothing harmful. It is MIT-licensed and scores 98/100 on trust signals. Skills are instructions an agent will follow, so read the file before installing it and do not approve commands you do not understand.
- Is mcp-server-security still maintained?
- The repository was last updated about 6 months ago. That is recent enough to be usable, but agent tooling moves fast, so check the instructions against your agent's current version.
Skill content
View source on GitHubname: mcp-server-security description: Secure Model Context Protocol (MCP) servers with transport encryption, tool authorization, input validation, and audit logging for safe AI agent integrations. license: MIT metadata: author: devops-skills version: "1.0"
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:
# /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 90
3.3 Securing stdio Transport
For local stdio-based servers, the attack surface is the process boundary itself:
// 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.
// 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 = auth…[redacted](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:
// 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: string[];
}
const config = parse(readFileSync("config/tool-policy.yaml", "utf-8"));
const policies: ToolPolicy[] = config.policies;
export function isToolAllowed(userRole: string, toolName: string): boolean {
const policy = policies.find((p) => p.role === userRole);
if (!policy) return false;
// Explicit deny takes precedence
if (policy.denied_tools.includes(toolName)) return false;
if (policy.denied_tools.includes("*") && !policy.allowed_tools.includes(toolName)) return false;
// Check allow
if (policy.allowed_tools.includes("*")) return true;
if (policy.allowed_tools.includes(toolName)) return true;
return false;
}
// MCP server integration: wrap the tool handler
export function authorizedToolHandler(server: any) {
const originalCallTool = server.callTool.bind(server);
server.callTool = async (request: any, context: any) => {
const userRole = context.session?.userRole || "readonly-agent";
const toolName = request.params.name;
if (!isToolAllowed(userRole, toolName)) {
return {
content: [{ type: "text", text: `Access denied: tool "${toolName}" is not permitted for role "${userRole}".` }],
isError: true,
};
}
return originalCallTool(request, context);
};
}
6. Input Validation
6.1 JSON Schema for Tool Parameters
Define strict schemas for every tool's input. Reject anything that does not conform.
// src/validation.ts
import Ajv from "ajv";
import addFormats from "ajv-formats";
const ajv = new Ajv({ allErrors: true, removeAdditional: true });
addFormats(ajv);
// Schema registry keyed by tool name
const toolSchemas: Record<string, object> = {
read_file: {
type: "object",
properties: {
path: {
type: "string",
pattern: "^[a-zA-Z0-9_/\\-.]+$", // No path traversal chars
maxLength: 256,
},
},
required: ["path"],
additionalProperties: false,
},
query_database: {
type: "object",
properties: {
query: { type: "string", maxLength: 2048 },
database: { type: "string", enum: ["analytics", "public_catalog"] },
parameters: {
type: "array",
items: { type: ["string", "number", "boolean"] },
maxItems: 20,
},
},
required: ["query", "database"],
additionalProperties: false,
},
};
export function validateToolInput(toolName: string, params: unknown): { valid: boolean; errors?: string } {
const schema = toolSchemas[toolName];
if (!schema) return { valid: false, errors: `No schema registered for tool: ${toolName}` };
const validate = ajv.compile(schema);
if (validate(params)) return { valid: true };
const errorMsg = validate.errors?.map((e) => `${e.instancePath} ${e.message}`).join("; ");
return { valid: false, errors: errorMsg };
}
6.2 SQL Injection Prevention
Never pass raw agent-supplied strings into queries. Use parameterized queries and statement-level restrictions.
// src/safeSql.ts
const FORBIDDE
Truncated for display — read the full file on GitHub.
Related Skills
Agent-Reach
112.3kGive your AI agent eyes to see the entire internet. Read & search Twitter, Reddit, YouTube, GitHub, Bilibili, XiaoHongShu — one CLI, zero API fees.
ruflo
81.9k🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
headroom
79.8kCompress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
CowAgent
48.0kOpen-source personal AI assistant & Agent Harness. Plans tasks, runs tools and skills, self-evolves with memory and knowledge. Multi-agent, multi-model, multi-channel. Lightweight, extensible, one-line install.
Languages
Trust signals
From repository metadata: license, adoption, age and documentation. Not a code audit — see the Safety scan above for what the skill file itself contains.
