本セクションの内容:
Preventing Path Traversal Vulnerabilities in MCP Server Function Handlers
The Model Context Protocol (MCP) is gaining traction as a standardized way for AI assistants to interact with external tools and data sources. As MCP adoption grows, so too does the importance of securing MCP servers against potential vulnerabilities. Recent MCP security research by Raul Onitza-Klugman from the Snyk Security Research team has highlighted the risks associated with vulnerable MCP servers, emphasizing the need for robust security measures.
Understanding MCP and its security implications
At its core, MCP is an open protocol designed to connect external tools, services, or data sources to large language models (LLMs). It acts as a bridge between AI applications and the resources they need to access, such as local databases, APIs, or command-line tools.
MCP servers expose three primary capabilities: resources, tools, and prompts. Resources are readable data blobs or files that LLMs can inspect, while tools are functions or commands that LLMs can execute.
The security of MCP servers is crucial because they often run locally on a developer's machine, which can contain sensitive information like API keys, credentials, and intellectual property. A vulnerable MCP server can become an attack vector, potentially leading to data leaks, code execution, or other malicious activities.
Evidently, Raul's research topic, mentioned above, describes how attackers exploited an AWS MCP Server and a Markdown MCP Server to exfiltrate data and run arbitrary commands using indirect prompt injection techniques. This demonstrates how a weak link in the chain, the MCP Server code, can be a pitfall leading to significant data breaches and security risks.
Insecurely sharing resources in MCP servers
MCP server resources enable the exposure of data as read-only information that LLMs can use as context. For instance, an MCP server can define database records, application status, or other forms of text or binary data content as resources. These resources are identified by unique URIs and often contain custom protocol schemes. A prior write-up on building Node.js MCP servers that share resources provides a comprehensive guide on implementing resources in MCP servers.
Insecure code in MCP server resource definition
Insecure coding practices in MCP server resource definitions can lead to path traversal vulnerabilities. A path traversal vulnerability occurs when an attacker can manipulate the file path to access sensitive files or data outside the intended directory.
This can happen when user-supplied input is not properly sanitized or validated, and can easily manifest in MCP Server resources that implement access to files on disk for the contents they want to return from the function handler of a given MCP server resource.
Consider the following vulnerable Node.js code example:
server.resource(
"pipeline-workflows",
new ResourceTemplate("pipeline-workflows://{name}", { list: undefined }),
async (uri, { name }) => {
const decodedName = decodeURIComponent(name);
let filePath = path.resolve(process.cwd(), '.github/workflows/', `${decodedName}.yaml`);
// check if filepath exists
if (!accessSync(filePath)) {
// then try without the .yaml suffix incase the user provided the full filename
filePath = path.resolve(process.cwd(), '.github/workflows/', decodedName);
}
if (accessSync(filePath)) {
let fileContents = '';
try {
fileContents = readFileSync(filePath, 'utf-8');
} catch (e) {
writeFileSync('/tmp/mcp_log.log', `ERROR READING FILE: ${e}\n`, { flag: 'a' });
}
return {
contents: [{
uri: uri.href,
text: fileContents
}]
};
}
}
);
const transport = new StdioServerTransport();
await server.connect(transport);
In this example, the filePath
is constructed using user-supplied input (decodedName
). If an attacker can manipulate the name parameter, they may be able to access files outside the intended directory, potentially leading to sensitive data exposure.
Security risks of path traversal vulnerabilities in MCP servers
The impact of a path traversal vulnerability in an MCP server can be significant. An attacker could potentially access sensitive files, such as configuration files, SSH keys, or other confidential data. This could lead to further exploitation, such as code execution or data exfiltration.
Detecting and fixing path traversal vulnerabilities
Snyk Code is a Static Application Security Testing (SAST) tool that can help detect and fix path traversal vulnerabilities in MCP server code.
Once you install the Snyk VS Code extension, it will act as a static code analysis plugin similar to ESLint. The scan times are incredibly fast, so every time you save a file's contents, Snyk will analyze it for potential security vulnerabilities in the code.
The following screenshot shows how the MCP Server code handles the function implementation for the server.resource()
(from the TypeScript Model Context Protocol SDK) is now highlighted by Snyk on line 140, clearly showing a code path that would be vulnerable to a path traversal attack if such dangerous input were to flow into this function.

Snyk accelerates security mitigation by bringing this kind of productivity boost to developers right at their IDE workflows.
Even better, Snyk can also fix this security issue! You might have noticed the line annotation of “Fix this issue: Path Traversal” and indeed, here is how Snyk auto-fix looks in practice:

How to get started using Snyk Code
Get your Snyk IDE plugin, it's free!
Snyk Code uses advanced AI-powered analysis (known as Symbolic AI) to identify potential security issues in code, including path traversal vulnerabilities. By integrating Snyk Code into your development workflow, you can proactively identify and remediate security vulnerabilities before they become a problem.
This tool works by analyzing your MCP Server code (or any other code you or the LLM generates) for potential security issues, providing detailed reports and recommendations for remediation. It can be integrated into your IDE or CI/CD pipeline, enabling you to catch security issues early in the development process.
Best practices for securing MCP servers
To prevent path traversal vulnerabilities in MCP servers, follow best practices for secure coding:
Validate and sanitize user-supplied input to prevent malicious data from being used to construct file paths.
Correctly generate paths using safe and secure path conventions to avoid path traversal attacks (you can learn from prior CVEs like files-bucket-server and static-dev-server).
Use secure coding practices when defining MCP server resources, such as using whitelisting and proper error handling.
Integrate a SAST tool like Snyk Code into your development workflow to detect and fix potential security vulnerabilities.
What's next for MCP security?
As MCP continues to evolve, it's essential to stay informed about potential security risks and best practices for securing MCP servers. For further reading, consider the following resources:
Snyk Learn course on Path Traversal
Don't underestimate prompt injection attacks. I highly encourage you to read how prompt injection can exploit PDF text and bypass LLM as a judge technique.
By prioritizing security and following best practices, you can ensure the integrity of your MCP servers and protect against potential vulnerabilities.
Interested in learning more about MCP scanning? Explore Snyk Labs today or access the MCP Scan incubation from Snyk & Invariant Labs.
Discover Snyk Labs
Your hub for the latest in AI security research and experiments.