Building Secure MCP Servers: A Developer's Guide to Avoiding Critical Vulnerabilities
The Model Context Protocol (MCP) has rapidly become the de facto standard for extending AI capabilities. Since Anthropic's announcement in November 2024, developers have rushed to build MCP servers that connect LLMs to databases, file systems, APIs, and command-line tools. However, in the race to unlock AI autonomy, security has often been an afterthought, with a growing awareness of the predictable security consequences.
The truth is stark: MCP servers are simply more code, and more code means more bugs, a larger attack surface, and increased security vulnerabilities. What makes MCP particularly dangerous is the context in which these servers operate. They run on developer machines containing API keys, credentials, and intellectual property. They're controlled by AI agents that can be manipulated through prompt injection (and indirect prompt injection). And they often ship with the same class of vulnerabilities that have plagued web applications for decades.
This guide examines the critical security vulnerabilities affecting MCP servers today, including command injection, path traversal, and SQL injection, through the lens of real-world CVEs and security research. You'll learn not just what these vulnerabilities look like, but how to build MCP servers that resist them from the ground up.

Command injection: the most prevalent MCP vulnerability
Command injection is one of the most commonly discovered vulnerabilities in MCP servers. The pattern is distressingly familiar: an MCP server spawns system commands such as npm, git, or lsof and incorporates user-controlled input without proper sanitization.
You can consider it from a prompt injection perspective, but it’s an adversarial prompt that ultimately leads to remote command execution.
Understanding the vulnerability
Consider a seemingly innocuous MCP server that looks up npm package information:
The vulnerability is subtle but severe. The packageName parameter flows directly into a shell command through string interpolation. When a user prompts their AI assistant with "What's the last release date of react; touch /tmp/pwned?", the command becomes:
The semicolon terminates the first command, and the shell happily executes touch /tmp/pwned as a separate command. An attacker controlling the prompt now has arbitrary command execution on the developer's machine.
Prompts turn into real-world CVE liability
This isn't theoretical. Multiple MCP servers have been found vulnerable to command injection:
The GitHub Kanban MCP Server (GHSA-6jx8-rcjx-vmwf) failed to sanitize user input, allowing arbitrary command execution through Git operations
The iOS Simulator MCP Server (GHSA-6f6r-m9pv-67jw) exposed similar vulnerabilities
The Create MCP Server STDIO package contained flawed tool definitions, exposing system monitoring to injection attacks

The security fix: use safe Node.js API execFile instead of exec
The Node.js exec function spawns a shell and executes commands within it, making shell metacharacters like ;, |, and $() dangerous. The execFile function executes files directly without shell interpretation:
Here's the secure implementation:
With execFile, the malicious input react; touch /tmp/pwned becomes a single argument passed to npm view, which fails gracefully rather than executing arbitrary commands.
Additional command injection mitigations
Validate input against allowlists: If expecting package names, validate against npm naming conventions
Separate commands from arguments: Use safe APIs for command injection, favoring
execFileoverexecEscape shell arguments: When shell execution is unavoidable, use libraries like
shell-quoteUse language-specific APIs: Instead of spawning
npm, use the npm registry API directlyApply input length limits: Unusually long inputs often indicate injection attempts

Path traversal: escaping the sandbox
MCP servers frequently expose file system operations, such as reading configuration files, accessing documentation, or serving static resources. Path traversal vulnerabilities occur when attackers manipulate file paths to access files outside the intended directory.
The vulnerability pattern in the MCP server code
A common pattern in MCP resource handlers:
An attacker can request pipeline-workflows://../../../../../../etc/passwd and the server will dutifully read /etc/passwd. On a developer's machine, more valuable targets include:
~/.ssh/id_rsa(SSH private keys)~/.aws/credentials(AWS access keys).envfiles (application secrets)~/.npmrc(npm authentication tokens)
Case-study: Mastra AI framework found vulnerable to path traversal
The @mastra/mcp-docs-server package contained a subtle path traversal vulnerability. While the code included a security check, the logic continued execution even after detecting traversal:
The findNearestDirectory function operated on the unvalidated path, leaking directory listings outside the intended scope.
Secure path handling for MCP server resources
Implement defense-in-depth for file operations:
Path traversal prevention checklist
Always resolve paths: Use
path.resolve()to convert relative paths to absoluteValidate the result: Ensure resolved paths start with the intended base directory
Reject immediately: Never continue processing after detecting traversal attempts
Use allowlists: When possible, restrict access to explicitly permitted files
Avoid user-controlled extensions: Don't let users specify file extensions

SQL injection: the "read-only" illusion
As MCP servers expand into database connectivity, SQL injection vulnerabilities have emerged as a critical concern. More insidiously, many MCP database servers implement a flawed "read-only" mode that provides a false sense of security.
The naive read-only check
Multiple MCP database servers attempt to enforce read-only access by checking if queries start with SELECT:
This approach fails catastrophically against PostgreSQL's extensive built-in functions.
How to bypass insecure MCP server read-only restrictions
PostgreSQL exposes administrative functions callable within SELECT statements:

Case-study: real-world MCP vulnerabilities exploited through SQL Injection
Xata's MCP Server, not assigned an official CVE, the server's read-only transaction could be bypassed:
By terminating the read-only transaction with COMMIT, attackers could execute write operations.
ExecuteAutomation Database Server (CVE-2025-59333): Similar flawed access controls allowed query chaining:
How to implement secure database access for MCP servers?
Enforce single-query execution:
Use database-level permissions:
Implement query allowlisting:
Block dangerous functions:
Leverage MCP Resources for structured access:

Securing third-party dependencies
MCP servers rely on npm packages for database drivers, HTTP clients, and utility functions. Each dependency represents a potential supply chain risk:
Vulnerable dependencies: Known CVEs in packages like
pg,axios, orlodashMalicious packages: Typosquatting attacks targeting MCP server developers
Transitive vulnerabilities: Security flaws in dependencies of dependencies
Mitigation Strategies
Continuous scanning: Integrate Snyk or similar tools into your CI/CD pipeline to detect vulnerable dependencies before deployment
Pin dependency versions: Use lockfiles (
package-lock.json) and verify integrityRegular updates: Monitor for security advisories and patch promptly
Minimize dependencies: Each package is an attack surface; evaluate the necessity of the package in your MCP Server.
Audit before adoption: Review package health scores on the Snyk Security Database
Recommended actions: building secure MCP servers

For MCP server developers
Validate all inputs: Never trust data from LLM-generated tool calls
Use safe APIs: Prefer
execFileoverexec, parameterized queries over string interpolationImplement defense-in-depth: Multiple validation layers, not single checks
Integrate SAST tools: Use Snyk Code or similar to catch vulnerabilities during development
Apply least privilege: Database users, file system access, and network permissions should be minimally scoped
Document security model: Be explicit about trust boundaries and assumptions
For MCP server users
Audit before installing: Review source code, especially tool handlers
Monitor behavior: Watch for unexpected file access, network requests, or command execution
Isolate environments: Run MCP servers in sandboxed environments
Keep updated: Apply security patches promptly
Report vulnerabilities: Practice responsible disclosure when you find issues
For organizations
Establish MCP policies: Define approved servers and security requirements
Implement scanning: Automatically scan the MCP server code before deployment
Train developers: Educate teams on secure MCP development patterns
Monitor and audit: Log MCP server activity for security review
The path forward
The Model Context Protocol represents a powerful paradigm for extending AI capabilities, but with power comes responsibility. The vulnerabilities we've examined - command injection, path traversal, and SQL injection are not novel. They're the same flaws that have plagued web applications for decades, now manifesting in a new context with potentially greater impact.
The irony is sharp: in our rush to make AI more capable, we've connected it to systems built on the same fragile foundations we've struggled to secure for years. An LLM with access to a vulnerable MCP server becomes an unwitting attack vector, its intelligence weaponized by simple string manipulation.

The path forward requires treating MCP server development with the same rigor we apply to any security-critical code. Validate inputs. Use safe APIs. Implement defense-in-depth. Scan for vulnerabilities. And remember that "read-only" is often a dangerous illusion.
The tools to build secure MCP servers exist. The question is whether we'll use them before the next wave of vulnerabilities makes headlines.
Looking to understand emerging MCP server attack paths–from tool poisoning to shadowing and toxic flows? Unpack real-world incidents to learn how to defend against attacks with practical, flow-aware strategies in the Securing The MCP Servers Ecosystem eBook.
Compete in Fetch the Flag 2026!
Test your skills, solve the challenges, and dominate the leaderboard. Join us from 12 PM ET Feb 12 to 12 PM ET Feb 13 for the ultimate CTF event.
