# MCP (Model Context Protocol) Security Cheat Sheet

## Introduction

The **Model Context Protocol (MCP)**, introduced by Anthropic in November 2024, standardizes how AI applications (LLM clients) connect to external tools, data sources, and services.

Think of MCP as a **"USB-C port for AI"** — a universal interface that replaces fragmented, custom integrations with a single protocol.

However, MCP introduces a fundamentally new attack surface: AI agents dynamically executing tools based on natural language, often with access to sensitive systems.

Unlike traditional APIs, where developers control every call, MCP allows LLMs to decide:

- Which tools to invoke.
- When to invoke them.
- What parameters to provide.

This creates unique security risks involving prompt injection, supply chain attacks, and confused deputy problems.

This cheat sheet covers best practices for securing MCP deployments and minimizing attack surfaces across clients, servers, and their connections.

---

## 1\. MCP Architecture Overview

```text
User
  ↕
MCP Host (AI Application)
  ↕
MCP Client
  ↕
MCP Server(s)
  ↕
Tools / Data / APIs
```

### Core Components

| Component | Description |
| --- | --- |
| MCP Host | The AI application (e.g., Claude Desktop, Cursor, IDE plugins). |
| MCP Client | Connects to one or more MCP servers and passes tool definitions to the LLM. |
| MCP Server | A lightweight program exposing tools, resources, and prompts through the protocol. |
| Transport | Communication mechanism: stdio (local) or Streamable HTTP (remote). |

**Important:** The older HTTP+SSE transport is deprecated. Streamable HTTP is the recommended remote transport.

The LLM sees tool descriptions from all connected servers in its context. This is critical when understanding cross-server attacks.

---

## 2\. Key MCP Security Risks

| Attack / Risk | Description |
| --- | --- |
| Tool Poisoning | Malicious instructions hidden in tool descriptions, parameter schemas, or return values manipulate LLM behavior. |
| Rug Pull Attacks | A server changes its tool definitions after initial user approval, turning a trusted tool malicious. |
| Tool Shadowing / Cross-Origin Escalation | A malicious server manipulates how an agent interacts with tools from other trusted servers. |
| Confused Deputy Problem | An MCP server executes actions using its own broad privileges rather than the requesting user's permissions. |
| Data Exfiltration | Prompt injection encodes sensitive information into seemingly normal tool calls, such as search queries or email subjects. |
| Excessive Permissions | MCP servers request unnecessarily broad OAuth scopes, creating aggregation risks. |
| Supply Chain Attacks | Untrusted or compromised MCP packages are installed from public registries without review. |
| Message Tampering and Replay | JSON-RPC messages are modified after TLS termination or captured and replayed to duplicate actions. |
| Sandbox Escapes | Local MCP servers with excessive host access can enable filesystem traversal, credential theft, or arbitrary code execution. |

---

## 3\. MCP Security Best Practices

### 3.1 Principle of Least Privilege

- Grant each MCP server only the minimum permissions required.
- Use scoped, per-server credentials.
- Never share tokens across multiple MCP servers.
- Request narrow OAuth scopes (e.g., `mail.readonly` instead of `mail.modify`).
- Prefer ephemeral, short-lived tokens over long-lived Personal Access Tokens (PATs).

### 3.2 Tool Description & Schema Integrity

- Inspect tool descriptions, parameter names, types, and return schemas before approval.
- Treat the entire tool schema as a potential injection surface.
- Pin reviewed tool definitions using cryptographic hashes.
- Require review whenever tool definitions change.
- Hash the complete tool definition, including:
  - `inputSchema`
  - `outputSchema`
  - `annotations`
- Remember that metadata changes can affect approval behavior without changing visible descriptions.
- Use tools such as `mcp-scan` to detect poisoned descriptions and cross-server shadowing.
- Use strict JSON Schema validation:
  - Set `additionalProperties: false`.
  - Use `pattern` or equivalent validation for string fields.

**Important:** Hashing detects metadata changes, not changes to server code or behavior behind an unchanged definition. Tool annotations are hints, not enforcement mechanisms.

### 3.3 Sandbox and Isolate MCP Servers

- Run local MCP servers in sandboxes with minimal privileges.
- Restrict filesystem access to required directories only.
- Disable network access unless explicitly needed.
- Use `stdio` for local MCP communication through the launched process's standard streams.
- Separate sensitive servers (payments, authentication, PII) from general-purpose servers.

**Security note:** Using `stdio` avoids exposing a listening MCP endpoint, but it does not restrict the server process's filesystem, network, or credential access. A bare `chroot` is not a process sandbox.

### 3.4 Human-in-the-Loop for Sensitive Actions

- Require explicit user confirmation for destructive, financial, or data-sharing operations.
- Display complete tool-call parameters before execution.
- Never automatically approve tool calls, especially in multi-server environments.
- Ensure confirmation interfaces cannot be bypassed by LLM-generated responses.
- Do not assume that tool availability means the user has consented to its execution.
- Assess authorization requirements based on the possible effects of an operation, including sensitive reads, writes, disclosures, and irreversible actions.

Use risk-appropriate controls such as:

- Explicit user confirmation.
- Narrowly scoped authorization.
- Runtime policy enforcement.

#### Additional Protection for Paid Tool Calls

For paid MCP integrations:

- Show payment amount, asset, network, and recipient to the user.
- Bind payment approval to the exact tool arguments and payment terms.
- Do not pay if the terms differ from what was approved.
- Enforce per-payment spending limits.
- Set aggregate spending limits across all servers and time periods.
- Account for pending payments when calculating spending limits.
- Reserve maximum authorized amounts atomically to prevent race conditions.

### 3.5 Input and Output Validation

- Validate every input received by MCP server tools.
- Treat LLM-generated parameters as untrusted.
- Sanitize inputs against:
  - SQL injection.
  - OS command injection.
  - Path traversal.
- Validate and sanitize tool outputs before returning them to the LLM context.
- Never pass raw shell commands or unsanitized file paths.
- Protect against Server-Side Request Forgery (SSRF).

**Important:** Never fetch arbitrary URLs supplied by an LLM without strict allowlist validation. Prompt injection could manipulate tools into accessing internal services, including cloud metadata endpoints.

### 3.6 Authentication, Authorization & Transport Security

- Require authentication for remote endpoints exposing non-public tools or data.
- Follow the MCP OAuth 2.1 profile when using OAuth over HTTP.
- Identify the intended MCP server using the `resource` parameter.
- Validate that access tokens were issued for the intended MCP server audience.
- Reject invalid tokens.
- Never pass MCP access tokens directly to upstream APIs.
- Validate authorization on every protected request.
- Use TLS for remote Streamable HTTP connections.
- Verify remote server identity through certificate pinning or cryptographic server verification.
- Apply rate limits, quotas, and timeouts per session or tenant.
- Store OAuth tokens securely using OS-native credential storage.

Examples:

- macOS Keychain.
- Windows Credential Manager.
- Linux Secret Service.

**Never store OAuth access or refresh tokens in plaintext configuration files or application settings.**

#### Streamable HTTP Security

- Bind local Streamable HTTP servers to `localhost` unless network access is explicitly required.
- Validate incoming `Origin` headers.
- Reject present but invalid origins with HTTP `403`.
- Do not reject non-browser clients solely because they omit the `Origin` header.
- Validate incoming `Host` headers and reject unexpected hostnames.

**Note:** The current Streamable HTTP transport has no protocol-level sessions. If supporting older session-based revisions, use random session IDs bound to authenticated users. Never treat a session ID as authentication.

### 3.7 Optional Message-Level Integrity

TLS protects messages while they are in transit. However, a compromised component after TLS termination could still modify messages.

- Consider message-level signing when your threat model requires integrity after TLS termination.
- Use a reviewed mechanism supported by both endpoints.
- Define:
  - How signing keys are trusted.
  - Which messages are signed.
  - How replay attacks are prevented.
  - What happens when verification fails.

**Important:** The MCPS Internet-Draft proposes a separate signing and replay-protection layer. It is an individual work in progress, not an adopted MCP standard.

Message-level signing is optional, not a requirement for ordinary MCP deployments.

### 3.8 Multi-Server Isolation & Cross-Origin Protection

Treat each MCP server as an independent and potentially untrusted security domain.

- Prevent tool descriptions from one server from influencing tools on another server.
- Monitor cross-server data flows.
- Detect credentials from one server appearing in calls to another.
- Use an MCP proxy or gateway to enforce isolation policies between servers.

### 3.9 Supply Chain Security

- Install MCP servers only from trusted and verified sources.
- Review source code and tool definitions before installation.
- Verify package integrity using checksums or code signing.
- Scan dependencies for known vulnerabilities.
- Monitor changes to tool descriptions after installation.
- Verify package names carefully to prevent typosquatting attacks.

Example of a potentially malicious package name:

```text
mcp-server-filesystem
mcp-server-filesytem
```

Use tools such as `mcp-scan` to analyze and monitor installed MCP servers.

### 3.10 Monitoring, Logging & Auditing

- Log all MCP tool invocations.
- Record full parameters, user context, and timestamps.
- Integrate MCP logs with a Security Information and Event Management (SIEM) system.
- Alert on unusual patterns, including:
  - Unexpected tool invocations.
  - Admin-level queries.
  - Abnormal call frequency.
  - Suspicious cross-server activity.
- Redact secrets and Personally Identifiable Information (PII) from logs.
- Conduct regular security audits and simulated attacks.

### 3.11 Consent & Installation Security

- Display a clear consent dialog before connecting a new MCP server.
- Show the exact command that will execute for local servers.
- Never truncate execution commands in consent interfaces.
- Clearly identify the MCP server's source and publisher.
- Request consent again whenever tool definitions change.
- Never allow web content or untrusted data to trigger MCP server installation.

### 3.12 Prompt Injection via Tool Return Values

Treat every tool response as untrusted data, including responses from approved servers.

Best practices:

- Clearly separate and label tool data in the model context.
- Instruct the model to treat tool responses as data, not instructions.
- Use tag stripping and instruction-pattern detection only as additional filtering or alerting measures.
- Enforce authorization and validate subsequent tool calls in trusted application code.
- Apply least privilege and human approval for sensitive actions.
- For web scraping and retrieval tools, extract required structured data instead of passing raw HTML into the model context.

**Important:** Structured fields are also untrusted. Text inside JSON or other structured formats can still contain prompt injection.

---

## 4\. MCP Security Do's and Don'ts

### Do's

- Enforce least privilege per MCP server and per tool.
- Inspect and pin all tool descriptions and schemas.
- Sandbox local MCP servers using containers or restricted environments.
- Require human approval for sensitive or destructive tool calls.
- Apply risk-appropriate authorization and enforce it at execution time.
- Validate all inputs and outputs at the MCP server layer.
- Use `mcp-scan` or equivalent tools to detect poisoned tools.
- Log and monitor all tool invocations centrally.
- Verify MCP server sources and scan dependencies.
- Validate the `Origin` of Streamable HTTP requests.
- Validate the audience of OAuth access tokens.
- Pin tool definitions using cryptographic hashes and verify them before execution.

### Don'ts

- Don't automatically approve tool calls without showing full parameters.
- Don't blindly trust tool descriptions.
- Don't share OAuth tokens or credentials across MCP servers.
- Don't run MCP servers with unrestricted host access or wildcard permissions.
- Don't install MCP servers from unverified public registries without review.
- Don't assume an approved tool today will remain unchanged tomorrow.
- Don't ignore cross-server interactions.
- Don't store secrets in source code, plaintext configuration files, or logs.
- Don't treat optional message signing as a core MCP requirement.
- Don't accept server public keys from unverified first-contact responses (TOFU without pinning).

---

## 5\. References & Further Reading

1. [MCP: Security Best Practices](https://modelcontextprotocol.io/specification/latest/basic/security_best_practices)
2. [MCP: Authorization](https://modelcontextprotocol.io/specification/latest/basic/authorization)
3. [MCP: Streamable HTTP](https://modelcontextprotocol.io/specification/latest/basic/transports)

---

## Frequently Asked Questions

### What is MCP security?

MCP security refers to protecting Model Context Protocol clients, servers, tools, and data from threats such as prompt injection, unauthorized access, and malicious tool execution.

### What are the biggest security risks in MCP?

The major risks include tool poisoning, rug pull attacks, prompt injection, excessive permissions, data exfiltration, supply chain attacks, and sandbox escapes.

### How do you secure an MCP server?

Use least-privilege permissions, strict input validation, authentication, sandboxing, secure credential storage, server isolation, and continuous monitoring.

### What is a tool poisoning attack in MCP?

A tool poisoning attack occurs when malicious instructions are embedded in an MCP tool description, schema, or response to manipulate an AI agent's behavior.

### Why is human approval important in MCP?

Human approval prevents AI agents from independently executing sensitive operations such as financial transactions, destructive actions, or unauthorized data sharing.

### Can MCP servers access sensitive system resources?

Yes. Depending on their permissions and configuration, MCP servers may access files, APIs, databases, and other sensitive resources. Proper isolation and access controls are essential.

---

## Final Takeaway

Securing an MCP deployment is not just about protecting APIs or validating tool inputs.

It requires securing the entire execution chain:

**User → AI Host → MCP Client → MCP Server → External Tools → Data Sources**

The most important principles are:

1. Least privilege.
2. Tool schema integrity.
3. Server isolation.
4. Human approval for sensitive actions.
5. Strict input and output validation.
6. Secure authentication and transport.
7. Continuous monitoring and auditing.

**Never treat an AI agent, its tool descriptions, or its tool outputs as inherently trustworthy. Security enforcement must remain in trusted application code, independent of the model's decisions.**
