Validate File Paths in MCP Servers: Preventing Directory Traversal Attacks

Validate File Paths in MCP Servers: Preventing Directory Traversal Attacks

AI agents frequently need to read and write files on behalf of users, but this convenience introduces serious security risks. When an MCP server accepts file paths from agent requests without proper validation, attackers can exploit path manipulation techniques to access sensitive files outside the intended scope. This article examines directory traversal vulnerabilities in MCP servers and provides concrete implementation strategies to protect your filesystem.

Understanding the Directory Traversal Threat

Directory traversal (also known as path traversal) is a vulnerability that allows attackers to access files and directories stored outside the intended web root folder. In the context of MCP servers, this occurs when user-supplied input is used to construct file paths without adequate sanitization. A request like ../secrets/config.json could potentially expose database credentials, API keys, or other sensitive configuration data.

The fundamental issue lies in how operating systems resolve relative paths. When a path containing .. segments is processed, the system navigates up the directory tree. Without proper constraints, an attacker can chain these sequences to reach any file on the filesystem that the server process has permission to read. This is particularly dangerous for MCP servers that run with elevated privileges or have broad filesystem access.

Modern attack patterns have evolved beyond simple traversal sequences. Attackers may use URL encoding (%2e%2e%2f), double encoding, null byte injection, or Unicode normalization tricks to bypass naive filters. A robust defense must account for these variations while maintaining legitimate functionality for authorized file operations.

Implementing Path Validation in MCP Tools

The foundation of secure file handling is canonicalization—converting the input path to its absolute, normalized form before any validation occurs. This eliminates ambiguity from relative references and symbolic links that could otherwise circumvent your security controls.

Here's an example implementation for an MCP server tool that safely handles file paths:

import os
from pathlib import Path
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("secure-file-server")

ALLOWED_BASE_DIR = Path("/var/mcp/uploads").resolve()

def validate_file_path(requested_path: str) -> Path:
    # Resolve to absolute path and normalize
    requested = Path(requested_path).resolve()

    # Ensure the resolved path is within allowed directory
    try:
        requested.relative_to(ALLOWED_BASE_DIR)
        return requested
    except ValueError:
        raise PermissionError(
            f"Access denied: path outside allowed directory"
        )

@mcp.tool()
async def read_file(filepath: str) -> str:
    safe_path = validate_file_path(filepath)

    if not safe_path.exists():
        raise FileNotFoundError(f"File not found: {filepath}")

    with open(safe_path, 'r') as f:
        return f.read()

This implementation uses Python's pathlib module to resolve symbolic links and normalize the path before validation. The relative_to check ensures that even after resolution, the final path remains within the designated safe zone. Note that resolve() is called on both the allowed base directory and the requested path to prevent symlink-based escapes.

Defense in Depth Strategies

Relying solely on path validation creates a single point of failure. A comprehensive security strategy incorporates multiple layers of protection that work together to minimize risk.

Operating System Level Controls

Run your MCP server with the principle of least privilege. Create a dedicated service account with filesystem permissions limited to only the directories it absolutely needs. Use containerization or chroot jails to create isolated environments where even successful traversal attacks cannot reach sensitive system files.

Input Validation Patterns

Implement allowlist-based validation rather than attempting to block known bad patterns:

  • Reject paths containing null bytes (\x00)
  • Normalize Unicode representations before validation
  • Validate filename characters against a strict allowlist
  • Consider implementing a virtual filesystem abstraction that maps logical names to physical paths

Monitoring and Alerting

Log all file access attempts, especially those that fail validation. Anomalous patterns—such as multiple traversal attempts in quick succession—should trigger alerts. This enables rapid response to potential attacks and provides forensic data for incident investigation.

Testing Your Defenses

Validate your path validation logic with comprehensive test cases that include edge cases and attack variations:

  • Simple traversal: ../../../etc/passwd
  • Encoded traversal: ..%2f..%2f..%2fetc/passwd
  • Double encoding: ..%252f..%252f..%252fetc/passwd
  • Null byte injection: file.txt%00.jpg
  • Symlink chains pointing outside allowed directories
  • Case variations and Unicode normalization

Automated security testing tools can help identify vulnerabilities, but manual code review remains essential for catching logic errors in custom validation implementations.

Conclusion

Directory traversal vulnerabilities in MCP servers represent a critical attack surface that demands careful attention during development. The combination of canonicalization, strict path validation, and defense-in-depth controls provides robust protection against these attacks. Review your MCP server implementations today—verify that every file operation validates paths against a defined safe zone before accessing the filesystem. Security is not a feature to add later; it must be built into the foundation of your agent infrastructure.

AgentGuard360

Built for agents and humans. Comprehensive threat scanning, device hardening, and runtime protection. All without data leaving your machine.

Coming Soon