# Security Implications of Executing Arbitrary MATLAB Code Through the MCP Server

> Discover the security risks of executing arbitrary MATLAB code via MCP server. Learn about RCE, data theft, and DoS attacks resulting from lack of validation.

- Repository: [Jigar Bhoye/matlabmcp](https://github.com/jigarbhoye04/matlabmcp)
- Tags: how-to-guide
- Published: 2026-03-04

---

**Executing arbitrary MATLAB code through the MCP server grants any connected client full remote code execution capabilities on the host system, enabling privilege escalation, data exfiltration, and denial-of-service attacks due to the absence of input validation, sandboxing, or resource limits.**

The `jigarbhoye04/matlabmcp` repository implements a Model Context Protocol (MCP) server that bridges large language models with a persistent MATLAB session. While this enables powerful automation workflows, the **security implications of executing arbitrary MATLAB code through the MCP server** are severe, as the implementation in [`main.py`](https://github.com/jigarbhoye04/matlabmcp/blob/main/main.py) passes unsanitized user input directly to the MATLAB engine without isolation or access controls.

## How the MATLAB MCP Server Executes Code

The server exposes two primary tools defined in [`main.py`](https://github.com/jigarbhoye04/matlabmcp/blob/main/main.py) that interact with the shared MATLAB engine instance.

### The runMatlabCode Tool

Located at lines 78–95 in [`main.py`](https://github.com/jigarbhoye04/matlabmcp/blob/main/main.py), the `runMatlabCode` function handles code execution:

- It logs the incoming request using Python's `logging` module
- Writes the arbitrary code string to a temporary `.m` file
- Executes the file via `eng.run()`
- Falls back to `eng.evalc()` if the file-based execution fails

### The getVariable Tool

Defined at lines 59–73 in [`main.py`](https://github.com/jigarbhoye04/matlabmcp/blob/main/main.py), this tool retrieves workspace variables:

- Accepts a `variable_name` parameter
- Uses a `matlab_to_python` conversion function (lines 52–76) to serialize MATLAB data structures to JSON
- Returns the value to the client without sanitization checks

## Critical Security Vulnerabilities

The architecture of `jigarbhoye04/matlabmcp` introduces multiple attack vectors due to its implicit trust model.

### Remote Code Execution (RCE)

The server executes code strings directly inside the host's MATLAB process. An attacker can invoke system-level commands using MATLAB's `system` function, the `!` operator, or Java interop via `java.lang.Runtime.exec`. This grants immediate shell access with the privileges of the user running the MATLAB session.

### Privilege Escalation and Data Exfiltration

The MATLAB engine inherits the host user's filesystem permissions. Malicious code can use `fileread`, `fopen`, or Java file I/O to read sensitive files such as SSH keys, environment variables, or proprietary data. The `getVariable` tool then provides a convenient exfiltration channel to return this data to the attacker.

### Denial-of-Service (DoS) Attacks

Without resource limits or timeouts, attackers can submit code designed to exhaust system resources:

- Infinite loops: `while true; end`
- Memory exhaustion: `zeros(1e6, 1e6)` or `fft(rand(1e9))`
- CPU saturation: Recursive algorithms or parallel pool abuse

These operations can hang the MATLAB engine, crash the MCP server, or destabilize the host system.

### Workspace Persistence and Side Effects

The shared MATLAB session maintains state between requests. Attackers can:

- Poison the workspace by overwriting variables used by other clients
- Modify the MATLAB path using `addpath` or `rmpath` to load malicious toolboxes
- Create or overwrite files on disk using `save` or file I/O functions

These side effects compromise the integrity of subsequent operations and potentially other users sharing the session.

### Absence of Sandboxing Controls

The current implementation in [`main.py`](https://github.com/jigarbhoye04/matlabmcp/blob/main/main.py) provides no isolation mechanisms:

- No containerization restricting filesystem or network access
- No user-namespace isolation or privilege dropping
- No SELinux, AppArmor, or seccomp profiles limiting system calls
- No chroot jail or restricted MATLAB environment

The MATLAB engine retains full access to the host operating system capabilities.

### Information Leakage via Error Logs

The server uses Python's `logging` module to record request details and error traces. If log files are improperly secured or exposed, they may reveal:

- Internal file paths and directory structures
- MATLAB session names and workspace contents
- Code snippets from failed execution attempts

This information aids attackers in reconnaissance and crafting targeted exploits.

## Attack Scenarios and Proof-of-Concept

The following JSON payload demonstrates how an attacker could exploit the `runMatlabCode` tool to read system files:

```json
{
  "tool": "runMatlabCode",
  "arguments": {
    "code": "system('cat /etc/passwd');"
  }
}

```

When processed by the MCP server, this executes the shell command through MATLAB's `system` function, returning the contents of the host's password file. Similarly, exfiltration of environment variables requires only:

```json
{
  "tool": "runMatlabCode",
  "arguments": {
    "code": "getenv('HOME')"
  }
}

```

The `getVariable` tool then provides the retrieval mechanism:

```json
{
  "tool": "getVariable",
  "arguments": {
    "variable_name": "ans"
  }
}

```

## Recommended Mitigations

While the current `jigarbhoye04/matlabmcp` implementation lacks these controls, the following measures would reduce the attack surface:

- **Input Validation and Whitelisting**: Parse the MATLAB code string to block dangerous functions (`system`, `eval`, `java.lang.Runtime`, `!` operator) before execution.

- **Execution Timeouts**: Implement a watchdog timer to terminate MATLAB processes that exceed a defined CPU time or wall-clock limit.

- **Resource Limits**: Apply OS-level controls such as cgroups (Linux) or Job Objects (Windows) to restrict memory consumption and CPU cores available to the MATLAB engine.

- **Dedicated Low-Privileged User**: Run the MCP server and MATLAB engine under a service account with minimal filesystem permissions and no access to sensitive data.

- **Sandboxed Environments**: Deploy within Docker containers with read-only root filesystems, dropped capabilities, and network isolation, or use Kubernetes security contexts with seccomp profiles.

- **Audit Logging and Rate-Limiting**: Record request origins, implement per-client throttling, and ensure logs are written to secure, append-only locations inaccessible to the service user.

- **Static Analysis**: Pre-screen code submissions using MATLAB's `mtree` parser or regex patterns to detect suspicious constructs before invoking `eng.run`.

## Summary

- The `runMatlabCode` tool in [`main.py`](https://github.com/jigarbhoye04/matlabmcp/blob/main/main.py) (lines 78‑95) executes arbitrary strings directly in the host MATLAB process, granting clients de facto remote code execution capabilities.
- Without sandboxing, input validation, or resource limits, attackers can exploit this to escalate privileges, exfiltrate data, launch denial‑of‑service attacks, and persist malicious changes across sessions.
- The shared MATLAB workspace state allows poisoned variables and path modifications to affect subsequent clients, compromising data integrity for all users sharing the server instance.
- Current logging practices in [`main.py`](https://github.com/jigarbhoye04/matlabmcp/blob/main/main.py) may leak sensitive system information if log files are improperly secured or exposed to untrusted parties.
- Implementing whitelisting, containerization, execution timeouts, and least‑privilege execution contexts would mitigate these critical security risks.

## Frequently Asked Questions

### Can the MATLAB MCP server execute system shell commands?

Yes. Because `runMatlabCode` passes strings directly to `eng.run` and `eng.evalc` without sanitization, clients can invoke MATLAB's `system` function, the `!` operator, or Java interop (`java.lang.Runtime.exec`) to execute arbitrary shell commands on the host operating system with the privileges of the running user.

### Is there any input validation in the current implementation?

No. The code in [`main.py`](https://github.com/jigarbhoye04/matlabmcp/blob/main/main.py) (lines 78‑95) writes the client‑supplied string directly to a temporary `.m` file and executes it. There is no parsing, whitelisting, or static analysis to block dangerous functions or restrict the code to safe operations.

### How can I safely deploy the MATLAB MCP server in a production environment?

To minimize risk, run the server inside a container (Docker or Kubernetes) with a read‑only filesystem, dropped capabilities, and no network access. Execute the MATLAB engine under a dedicated low‑privilege service account with minimal filesystem permissions, and implement resource limits (cgroups) and execution timeouts to prevent resource exhaustion attacks.

### Does the server isolate client sessions from each other?

No. The server maintains a single shared MATLAB engine session. Variables, path modifications, and function definitions persist between requests from different clients. A malicious actor can poison the workspace by overwriting variables or adding malicious directories to the path, affecting all subsequent clients that interact with the same server instance.