Command Injection in MCP Tools
Command injection occurs when an MCP server constructs and executes system commands, shell scripts, or code using untrusted input without proper validation or sanitization. Because MCP tools often wrap system utilities and run with elevated privileges, successful exploitation can lead to complete host compromise.
Severity: 8.0/10 (Critical)
The combination of high prevalence, high impact, and straightforward exploitability makes command injection one of the most critical MCP security risks.
Summary
Command injection occurs when an MCP server constructs and executes system commands, shell scripts, or code using untrusted input without proper validation or sanitization. Because MCP tools often wrap system utilities and run with elevated privileges, successful exploitation can lead to complete host compromise. This is not a theoretical risk: researchers analyzing MCP server implementations in March 2025 found that 43% contained command injection flaws, while 30% permitted unrestricted URL fetching.
What Is the Issue?
Command injection is a well-known vulnerability class, but MCP creates new conditions that make it more prevalent and more dangerous. Think of it this way: every MCP tool that touches the operating system is a potential entry point, and every parameter an attacker controls is exploitation waiting to happen.
How Command Injection Differs from Other MCP Injection Attacks
MCP environments face multiple injection attack types. Understanding the differences is critical for applying the right defenses:
Prompt Injection targets the AI model's reasoning. Attackers embed malicious instructions in data (i.e. documents, emails, tool responses, etc.) that the AI processes. The attack's goal is to manipulate what the AI decides to do. Defense focuses on the AI layer: input filtering, output validation, and model alignment.
SQL Injection targets database queries. When MCP tools construct SQL statements using unsanitized input, attackers can read, modify, or delete database contents. Defense focuses on parameterized queries and database access controls.
Command Injection targets the operating system. When MCP tools construct shell commands using unsanitized input, attackers can execute arbitrary code on the hosts. Defense focuses on avoiding shell execution, using safe APIs, and input validation.
The key distinction: prompt injection manipulates the AI brain, SQL injection manipulates databases, and command injection takes over the machine. They can chain together: a prompt injection might convince the AI to call a tool with a malicious parameter, which then triggers command injection on the server.
Attack Path
- Attacker identifies an MCP server that executes shell commands, database queries, or runs code based on tool parameters, since these tools translate user input into system actions and anywhere input becomes action is a potential injection point.
- Attacker crafts input containing shell metacharacters such as
;,|,&,$(), and backticks designed to escape the intended command structure. - The malicious input reaches the MCP tool either directly through a user request or indirectly through data the tool processes (file contents, API responses, database records, log entries).
- The MCP server invokes the tool with the attacker-controlled parameter.
- The MCP server constructs a command by concatenating the parameter without sanitization and executes it via shell.
- The attacker executes with the privileges of the MCP server process, potentially compromising credentials, exfiltrating data, or establishing persistent access.
Conditions That Enable It
- Unsafe command construction: Developers use string concatenation or template literals to build shell commands, passing user input directly into the command string.
- Shell execution instead of direct calls: When tools route commands through the operating system's shell, any special characters in user input can break out of the intended command.
- No input validation: Parameters from tool calls are passed directly to execution functions without checking for dangerous characters or patterns.
- Elevated privileges: MCP servers run with authentication access to databases, APIs, file systems, and credentials, making any compromise high-impact.
- Rapid community development: Many MCP servers are built quickly for functionality, not security. Authors may not recognize unsafe patterns.
What's Different Because of MCP?
Command injection is a classic vulnerability class, but MCP introduces new dynamics:
- Trust assumptions: Users trust their AI assistant. When the assistant calls a tool through the MCP, they may not scrutinize parameters or commands. This inherent social trust layer didn't exist in traditional command injection scenarios.
- Scale of vulnerable code: The MCP ecosystem is young and fast-growing. Many community-built servers prioritize features over security. Vulnerable patterns are widespread and often copied.
- Local execution context: Many MCP servers run on developer machines with access to credentials, source code, and internal systems. A compromised MCP server isn't attacking a remote server; it's attacking your laptop.
What This Enables
- Remote code execution: Attackers execute arbitrary commands on the MCP server host.
- Credential theft: Access environment variables, config files, and credential stores.
- Lateral movement: Use compromised MCP servers as pivot points into internal networks.
- Persistent access: Install backdoors, create new accounts, or modify startup scripts.
- Data exfiltration: Read and transmit sensitive files, database contents, or API responses.
- Supply chain compromise: Inject malicious code into build pipelines, CI/CD systems, or deployment artifacts.
Root Cause Analysis
Command injection in MCP stems from fundamental tensions between developer experience, functionality, and security.
Developer Convenience Over Safety
Building MCP tools is intentionally easy. The SDK provides simple patterns for exposing functionality, but many developers reach for shell commands as the quickest path to integration. Wrapping an existing CLI tool (git, kubectl, npm, gh) feels faster than using native APIs. The result is MCP servers full of exec() calls with string interpolation, which means any special character in user input can escape the intended command and run arbitrary code.
Lack of Security Guidance
The MCP specification and documentation focus on protocol mechanics, not secure implementation. Unlike frameworks that include specific requirements or security chapters in their docs, security has been mostly an afterthought thus far in MCP. Many builders don't know the difference between safe and unsafe execution patterns, or it's not top of mind for them as opposed to speed and ease of workflows.
Inherited Web Security Antipatterns
Developers familiar with web applications may underestimate command injection risks. In web contexts, SQL injection is the dominant injection concern, and prepared statements are well-understood. Command injection defenses are less commonly taught, and the "just use the shell" pattern persists.
Ecosystem Velocity
The MCP ecosystem rewards speed. New servers appear daily, forked and modified without security review. Vulnerable patterns in popular repositories propagate to forks. The mcp-package-docs vulnerability and mcp-server-kubernetes vulnerability both allowed attackers to run arbitrary commands because user input wasn't sanitized before execution.
Risk & Impact Analysis
Why It Matters
Command injection is consistently rated among the most critical vulnerability classes because it provides direct access to the underlying system. In MCP contexts, the risk is amplified:
- MCP servers often have credentials for multiple systems (databases, APIs, cloud services, etc.).
- Developer machines contain source code, SSH keys, and access to internal networks.
- A single vulnerable tool can compromise an entire workflow.
- Attacks can be triggered remotely through indirect prompt injection, with no user interaction beyond normal assistant use.
The CVE-2025-6514 vulnerability in mcp-remote demonstrated real-world impact: a command injection flaw in an OAuth proxy affected over 437,000 downloads, creating the potential for remote code execution through malicious authorization endpoints.
Impact Categories
Remote Code Execution
Reverse shell via injected curl command
Credential Theft
AWS keys, database passwords, SSH keys
Lateral Movement
Stolen credentials access production
Supply Chain Compromise
Backdoor in CI/CD artifacts
Who Can Exploit or Trigger It
- Direct attackers: Submit malicious input through tool parameters that contain shell metacharacters.
- Indirect attackers: Poison data sources (file contents, API responses, database records, log entries) that flow into tool parameters without sanitization.
- Malicious MCP server operators: Provide tools with intentionally vulnerable command construction to compromise user systems.
Potential Mitigations
Secure Coding Practices
- Never use shell execution with user input: Avoid
exec(),system(),shell=True, and backtick execution. Use argument-array execution (execFile,spawn,subprocess.runwith list arguments). - Parameterize everything: For database operations, use prepared statements. For process execution, use argument arrays. Never concatenate user input into command strings.
- Validate and sanitize inputs: Implement strict allowlists for expected characters. Reject any input containing shell metacharacters if shell execution is unavoidable.
- Use native libraries: Instead of shelling out to CLI tools, use native language bindings (e.g., use a Git library instead of calling
gitvia shell). - Scan for unsafe patterns: Use static analysis tools (Semgrep, Snyk, CodeQL) to detect vulnerable command construction in MCP server code before deployment.
Runtime Protections
- Sandbox MCP servers: Run in containers with restricted capabilities, limited network access, and read-only file systems.
- Implement human-in-the-loop: Require user approval before executing any tool that runs system commands, especially with external input.
Detection and Monitoring
- Log all tool invocations: Capture full parameters for forensic analysis.
- Monitor for anomalous execution: Alert on unexpected child processes, unusual command patterns, or execution at unusual times.
- Static analysis: Scan MCP server code for unsafe patterns before deployment.
Supply Chain Security
- Audit dependencies: Review MCP server code before installation. Check for unsafe execution patterns.
- Monitor advisories: Track security disclosures for MCP servers you use.
Proof of Concept
Scenario: The DevOps Shortcut
Context: Mid-size SaaS company with 200 engineers. DevOps team builds a custom MCP server to help developers interact with Kubernetes.
Week 1: The server launches.
- DevOps creates "k8s-helper" MCP server exposing kubectl operations.
- Developers can ask their AI assistant to check pod status, view logs, scale deployments.
- Implementation uses string concatenation:
exec(`kubectl logs ${pod_name}`) - No input validation. Whatever pod_name the tool receives goes straight into the command.
Week 2: Security isn't a priority.
- Server works great. Developers love it. No security review performed.
- 50 developers have the MCP server installed, connected to production clusters.
Week 3: Normal usage.
- Developer asks: "Show me logs for the payment-service pod"
- Tool receives pod_name="payment-service", server executes kubectl logs payment-service
Week 4: Attacker exploits the pattern.
- Attacker gains access to staging, creates pod with malicious name containing shell metacharacters.
- When a developer queries logs, the injected command executes.
- Attacker gains access to production cluster credentials.
Why This Works, And What's At Stake
The vulnerability is simple: the MCP server builds a command by pasting user input directly into a string, then runs it through the shell. The shell interprets special characters like semicolons as command separators, so the attacker's input breaks out of the intended command and runs whatever they want.
This pattern is common in MCP servers because it's the fastest way to wrap existing CLI tools. But "fast to build" can sometimes mean "easy to exploit." The attacker didn't need to compromise the MCP server's code or find a zero-day. They just needed to control data that eventually became a parameter. The code and command becomes the injection.
The zero-friction MCP can make detection harder. The developer asked a normal question in natural language. The malicious payload was hidden in infrastructure data (a pod name) that looked like any other. The command ran locally with the developer's full permissions, giving the attacker access to everything on that machine.
Severity Rating
| Factor | Score | Justification |
|---|---|---|
| Exploitability | 8/10 | Well-understood patterns; indirect injection via data; many vulnerable targets |
| Impact | 9/10 | Full system compromise; credentials, source code, internal network access |
| Detection Difficulty | 6/10 | Traces in logs if enabled; static analysis finds patterns; indirect injection subtle |
| Prevalence | 8/10 | 43% of MCP servers contained flaws; unsafe patterns widespread |
| Remediation | 4/10 | Fixes straightforward (safe APIs); requires changes across many servers |
Related Topics
- Prompt injection (manipulation of AI reasoning that can lead to tool misuse)
- SQL injection in MCP database tools
- Tool poisoning and malicious tool descriptions
- Supply chain attacks on MCP servers
- Sandboxing and isolation for MCP execution
References
- OWASP MCP Top 10: Command Injection & Execution - Security Framework
- Elastic Security Labs: MCP Tools Attack Vectors - Research
- Snyk: Exploiting MCP Servers Vulnerable to Command Injection - Technical Analysis
- mcp-package-docs Command Injection Advisory - CVE/Advisory
- mcp-server-kubernetes Command Injection Advisory - CVE/Advisory
- Docker: MCP Security Issues Threatening AI Infrastructure - Industry Analysis
- Node.js Security: Command Injection in Codehooks MCP Server - Case Study
- Stytch: How to Secure Against MCP Vulnerabilities - Best Practices
Report generated as part of the MCP Security Research Project