Model Context Protocol (MCP) provides an open standard for connecting AI models directly to external tools, databases, and programming environments. While most AI coding tools focus on Python and JavaScript, you can use MCP to give local large language models (such as Qwen 2.5, DeepSeek, or Llama 3 running via Ollama or local clients) direct control over an active MATLAB session.
This setup allows your local AI assistant to generate MATLAB code, run calculations on your physical machine, inspect workspace variables, and export plots without sending proprietary engineering data to external cloud APIs.
How the MATLAB MCP Architecture Works
The workflow connects three components running on your local machine:
- The MCP Client: An application such as Claude Desktop, OpenCode, or VS Code (Cline/Roo Code) that handles conversation and user prompts.
- The Python MCP Server: A lightweight Python service using the official
mcpSDK that translates JSON-RPC tool calls from the client into MATLAB commands. - The MATLAB Engine API: The official MathWorks Python interface that connects directly to a live or background MATLAB process.
Prerequisites
- MATLAB (R2022b, R2023a/b, R2024a/b, or R2025a) installed locally.
- Python (version supported by your MATLAB release, typically Python 3.10 or 3.11).
- An MCP-compatible desktop client (e.g., Claude Desktop, VS Code with Cline/Roo Code, or OpenCode).
- A local LLM runner such as Ollama or LM Studio (if running fully offline).
Step 1: Install and Verify the MATLAB Engine for Python
First, install the MATLAB Engine API into your Python environment. Open your terminal or command prompt and locate your MATLAB installation directory:
# For Windows (adjust the version folder to match yours):
cd "C:\Program Files\MATLAB\R2024b\extern\engines\python"
python -m pip install .
# For macOS / Linux:
cd "/Applications/MATLAB_R2024b.app/extern/engines/python"
python -m pip install .
Next, install the official FastMCP library:
pip install mcp
Verify that Python can communicate with MATLAB by running a quick test:
import matlab.engine
eng = matlab.engine.start_matlab()
result = eng.sqrt(144.0)
print(f"MATLAB connected successfully. Result: {result}")
eng.quit()
Step 2: Build the Python MATLAB MCP Server
Create a new file named matlab_mcp_server.py and paste the following server script. This script exposes three tools to the LLM: running arbitrary code, listing workspace variables, and rendering plots.
import os
import io
import sys
import matlab.engine
from mcp.server.fastmcp import FastMCP
# Initialize FastMCP server
mcp = FastMCP("MATLAB-Engine-Server")
# Start MATLAB in the background (or attach to an existing shared session)
print("Starting MATLAB engine instance...", file=sys.stderr)
eng = matlab.engine.start_matlab()
print("MATLAB engine ready.", file=sys.stderr)
@mcp.tool()
def execute_matlab_code(code: str) -> str:
"""
Executes a MATLAB script or command string in the active MATLAB workspace
and returns the console output or error messages.
"""
try:
out = io.StringIO()
err = io.StringIO()
eng.eval(code, nargout=0, stdout=out, stderr=err)
output_str = out.getvalue().strip()
error_str = err.getvalue().strip()
if error_str:
return f"Error:\n{error_str}\n\nOutput:\n{output_str}"
return output_str if output_str else "Command executed successfully with no console output."
except Exception as e:
return f"Execution failed: {str(e)}"
@mcp.tool()
def get_workspace_variables() -> str:
"""
Returns a summary of all variables currently stored in the MATLAB base workspace.
"""
try:
var_names = eng.eval("who", nargout=1)
if not var_names:
return "Workspace is currently empty."
summary = []
for name in var_names:
var_class = eng.eval(f"class({name})", nargout=1)
var_size = eng.eval(f"size({name})", nargout=1)
summary.append(f"- {name}: class={var_class}, size={list(var_size[0])}")
return "Active Workspace Variables:\n" + "\n".join(summary)
except Exception as e:
return f"Could not inspect workspace: {str(e)}"
@mcp.tool()
def generate_and_export_plot(plot_code: str, file_path: str = "output_plot.png") -> str:
"""
Runs plotting commands in MATLAB and saves the active figure to a PNG file.
"""
try:
abs_path = os.path.abspath(file_path)
full_command = f"""
close all;
figure('Visible', 'off');
{plot_code}
saveas(gcf, '{abs_path.replace(os.sep, "/")}');
close(gcf);
"""
eng.eval(full_command, nargout=0)
if os.path.exists(abs_path):
return f"Figure successfully exported to: {abs_path}"
return "Plot command completed, but output file was not found."
except Exception as e:
return f"Failed to generate plot: {str(e)}"
if __name__ == "__main__":
mcp.run(transport="stdio")
Step 3: Connect the Server to Your MCP Client
To let your desktop AI assistant use this tool, register it in your client's configuration file.
For Claude Desktop (or compatible local tools), open your configuration file:
- Windows:
%APPDATA%\Claude\claude_desktop_config.json - macOS:
~/Library/Application Support/Claude/claude_desktop_config.json
Add the server definition under the mcpServers section:
{
"mcpServers": {
"matlab": {
"command": "python",
"args": [
"C:\\path\\to\\your\\matlab_mcp_server.py"
]
}
}
}
Step 4: Running Interactive Engineering Prompts
Restart your MCP client. You can now prompt your assistant with real engineering tasks. Here are three examples:
Example 1: Signal Filtering
User prompt: "Create a noisy 50 Hz signal sampled at 1 kHz in MATLAB, design a 4th-order Butterworth low-pass filter with a 100 Hz cutoff, apply the filter, and report the SNR improvement."
The LLM calls execute_matlab_code, computes the vectors inside MATLAB, and reads the returned command window values to answer your prompt.
Example 2: State Space and Control System Analysis
User prompt: "Define a 2nd-order transfer function G(s) = 25 / (s^2 + 4s + 25) in MATLAB, compute its damping ratio and natural frequency, and export the step response to step_response.png."
The model executes the control toolbox commands, exports the image file, and provides the damping values directly.
Practical Engineering Considerations
- Engine Startup Time: Starting a new MATLAB instance takes several seconds. Keeping the Python server running as a persistent background process avoids repeated startup delays.
- Connecting to an Open Desktop Session: If you already have MATLAB open, run
matlab.engine.shareEnginein the MATLAB command window, then change the Python script to calleng = matlab.engine.find_matlab(); eng = matlab.engine.connect_matlab(eng[0]). This allows the LLM to modify your active desktop workspace in real time. - Memory Cleanup: When running large matrix simulations or loops, have the LLM invoke
clear varnameorclose allto keep RAM usage stable during long sessions.
Related Verified MATLAB & Simulink Projects
Need pre-built, debugged Simulink models with complete parameter initialization scripts and documentation? Explore top related solutions:
Common Engineering Troubleshooting & Q&A
Frequently encountered bugs, solver convergence issues, and implementation questions answered by our engineering mentors:
Recommended Engineering Articles
Need Custom MATLAB / Simulink Implementation?
Our team of PhD engineers build custom simulation plants, train machine learning agents, tune PID/MPC controllers, and deliver complete, executable code with Turnitin reports.