MATLAB MCP Server: Complete Integration Guide
Connect an AI agent to a real MATLAB session using the official MATLAB Engine API for Python and the real MCP Python SDK — evaluate expressions, run scripts, and generate plots on demand.
MATLAB is widely used in engineering, research, and quantitative analysis, but it's usually operated interactively — a human running commands in the MATLAB desktop. An MCP server changes that: it lets an AI agent evaluate MATLAB expressions, run scripts, and generate plots on demand, using the real MATLAB Engine API for Python rather than shelling out to the MATLAB executable or re-implementing numerical routines in Python.
Prerequisites
- A licensed, installed copy of MATLAB (R2022b or later is simplest — it supports installing the engine via pip).
- Python 3.9+ matching one of the versions your MATLAB release supports.
- Basic familiarity with MATLAB syntax and the MCP TypeScript/Python SDK pattern.
Step 1: Install the MATLAB Engine API for Python
MathWorks ships an official Python package that embeds a real MATLAB session inside a Python process. On R2022b and later, install it directly from PyPI:
pip install matlabengine
On older releases without a PyPI package, install it from the MATLAB installation itself instead:
cd "matlabroot/extern/engines/python"
python setup.py install
Verify it works before writing any MCP code:
import matlab.engine
eng = matlab.engine.start_matlab()
print(eng.sqrt(4.0)) # 2.0
Starting the engine takes several seconds — MATLAB itself is booting in the background. Start it once when your server starts, not per tool call.
Step 2: Build the Server
Use the real MCP Python SDK's FastMCP class, the same one covered in the beginner's guide — a decorated function becomes a tool automatically, with no hand-written JSON Schema.
import base64
import os
import tempfile
import matlab.engine
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("matlab-server")
eng = matlab.engine.start_matlab()
@mcp.tool()
def run_matlab_expression(expression: str) -> str:
"""Evaluate a MATLAB expression and return the result as a string.
Args:
expression: A MATLAB expression, e.g. "eig([1 2; 3 4])".
"""
try:
result = eng.eval(expression, nargout=1)
return str(result)
except Exception as exc:
return f"MATLAB error: {exc}"
@mcp.tool()
def plot_expression(y_expression: str, x_range: str = "0:0.1:(2*pi)") -> str:
"""Plot y_expression over x_range and return a base64-encoded PNG.
Args:
y_expression: A MATLAB expression in terms of x, e.g. "sin(x)".
x_range: A MATLAB range expression for x, e.g. "0:0.1:10".
"""
with tempfile.TemporaryDirectory() as tmp_dir:
png_path = os.path.join(tmp_dir, "plot.png").replace("\\", "/")
eng.eval(
f"x = {x_range}; y = {y_expression}; "
f"fig = figure('Visible', 'off'); plot(x, y); "
f"saveas(fig, '{png_path}'); close(fig);",
nargout=0,
)
with open(png_path, "rb") as f:
return base64.b64encode(f.read()).decode("utf-8")
if __name__ == "__main__":
mcp.run()
Two things worth noting: nargout tells the engine how many return values to expect — use 0 for statements that don't return anything (like a plot command) and 1 when you want the expression's value back. And the figure is created with 'Visible', 'off' so it renders in a headless environment without needing a display.
Step 3: Run and Connect
Test it with the MCP Inspector first, exactly as covered in the beginner's guide:
npx @modelcontextprotocol/inspector python3 matlab_server.py
Then add it to claude_desktop_config.json, using an absolute path to your Python interpreter and script:
{
"mcpServers": {
"matlab": {
"command": "/absolute/path/to/python3",
"args": ["/absolute/path/to/matlab_server.py"]
}
}
}
Security Considerations
eng.eval() executes arbitrary MATLAB code — that's what makes this useful, and it's also a real risk if the server is ever exposed beyond a single trusted local user. There's no sandboxing built into the MATLAB engine itself. If you need to expose this to multiple users or run it remotely, put real boundaries around it: an allowlist of permitted function calls instead of raw eval, a timeout on long-running computations, and a dedicated OS-level user with no access to anything the MATLAB process shouldn't be able to touch. Don't rely on the MCP layer alone for isolation.
Join the Discussion
Code Snippets (0)
No code snippets shared yet. Be the first to contribute!
Community Q&A (0 questions)
No questions yet. Ask the first one!