A Model Context Protocol (MCP) server that provides AI assistants with the ability to create, execute, and manage MATLAB code. This server enables seamless integration between AI tools and MATLAB environments.
- Code Validation: Check MATLAB syntax without execution
- Code Execution: Run MATLAB expressions and capture results
- File Management: Create, read, and execute MATLAB files
- Testing Support: Run MATLAB test files with detailed results
- Toolbox Detection: Discover installed MATLAB toolboxes
- Coding Guidelines: Built-in MATLAB best practices prompts
Before setting up the MATLAB MCP server, ensure you have:
- MATLAB Installation: A working MATLAB installation with Python engine support
- uv: Modern Python package manager (install from https://docs.astral.sh/uv/)
- VS Code: With MCP extension for testing (optional but recommended)
# Create project directory
mkdir matlab-mcp
cd matlab-mcp
# Or clone if you have a repository
git clone <your-repo-url> matlab-mcp
cd matlab-mcpInitialize the project with uv and install dependencies:
# Initialize uv project (if not already done)
uv init
# Install MCP CLI as a dependency
uv add 'mcp[cli]'
# Alternatively, install directly without project setup
# uv pip install mcp[cli]The server will automatically attempt to install the MATLAB Python engine if not found. To ensure proper setup:
-
Set the
MATLAB_PATHenvironment variable to your MATLAB installation directory:# Windows set MATLAB_PATH=C:\Program Files\MATLAB\R2024b # macOS/Linux export MATLAB_PATH=/Applications/MATLAB_R2024b.app
-
The server will automatically install the MATLAB engine for Python on first run if needed.
Your project should have the following structure:
matlab-mcp/
βββ main.py # MCP server implementation
βββ src/ # MATLAB files directory (auto-created)
βββ .vscode/
β βββ mcp.json # VS Code MCP configuration
βββ README.md # This file
Create .vscode/mcp.json for VS Code integration:
{
"servers": {
"MATLAB": {
"type": "stdio",
"command": "uv",
"args": [
"run",
"--with",
"mcp[cli]",
"mcp",
"run",
"C:\\Users\\<username>\\path\\to\\matlab-mcp\\main.py"
],
"cwd": "C:\\Users\\<username>\\path\\to\\matlab-mcp",
"env": {
"UV_LINK_MODE": "copy"
}
}
}
}Important: Replace <username> and paths with your actual system paths.
Ensure your main.py file (the MCP server implementation) is in the root of your project directory. The file should contain all the MATLAB MCP tools and be executable by the Python environment.
- Open VS Code in your project directory
- Open
.vscode/mcp.json - Click "Start MCP" button that appears
# Run the server with uv
uv run --with mcp[cli] mcp run main.py
# Or if you have a pyproject.toml with mcp[cli] as dependency
uv run mcp run main.pycheck_matlab_code: Validate MATLAB syntax without executionevaluate_matlab_code: Execute MATLAB expressions and return resultscreate_matlab_file: Create new MATLAB files with coderun_matlab_file: Execute existing MATLAB filesrun_matlab_test_file: Run MATLAB test files with structured resultsdetect_matlab_toolboxes: List installed MATLAB toolboxes
matlab://scripts/{script_name}: Read MATLAB file contents
matlab_coding_guidelines: Get MATLAB coding best practices and standards
Use these example prompts with your AI assistant to test each tool:
Check this MATLAB code for syntax errors:
x = [1, 2, 3
y = sin(x
plot(x, y)
Evaluate this MATLAB expression: 2 + 3 * 4
Create a MATLAB function called "calculate_mean" that takes an array and returns its mean
Run the MATLAB file "calculate_mean" with the array [1, 2, 3, 4, 5]
Create and run a test file for the calculate_mean function
Show me what MATLAB toolboxes are installed on my system
Show me the MATLAB coding guidelines
- MATLAB Files: Created in
src/directory - Automatic Extension:
.mextension added automatically if not specified - Path Handling: Supports both relative and absolute paths
- File Validation: Automatic filename validation for MATLAB compatibility
MATLAB_PATH: Path to your MATLAB installation (required for engine setup)UV_LINK_MODE: Set to "copy" for better compatibility
- MATLAB Directory: Change
MATLAB_DIRinmain.pyto customize where files are stored - Output Limits: Modify
MAX_OUTPUT_LENGTHto control output truncation - Coding Guidelines: Update the
matlab_coding_guidelinesprompt to match your standards
-
MATLAB Engine Not Found
- Ensure MATLAB is installed and
MATLAB_PATHis set correctly - The server will attempt automatic installation
- Ensure MATLAB is installed and
-
Permission Errors
- Ensure the
src/directory is writable - Check file permissions for the project directory
- Ensure the
-
Server Won't Start
- Verify uv is installed and available in PATH
- Check that MCP CLI dependency is installed (
uv add 'mcp[cli]') - Ensure
main.pypath inmcp.jsonis correct - Verify the
cwdpath inmcp.jsonpoints to your project directory
-
Files Created in Wrong Location
- Check the working directory when server starts
- Verify
MATLAB_DIRpath resolution
To add new MCP tools, use the @mcp.tool() decorator:
@mcp.tool()
def your_new_tool(param: str) -> dict:
"""Your tool description."""
# Implementation
return {"result": "success"}To add new MCP resources, use the @mcp.resource() decorator:
@mcp.resource("your://resource/{param}")
def get_resource(param: str) -> str:
"""Resource description."""
# Implementation
return "resource content"Note: This MCP server requires a valid MATLAB installation and license to function properly. Ensure MATLAB is properly configured and accessible before using the server.
initialization in codespaces
curl -LsSf https://astral.sh/uv/install.sh | sh source $HOME/.cargo/env # install uv and add it to your PATH. After installation, restart your terminal or run: uv --version
uv init uv venv chmod +x .venv/bin/activate
uv cache clean --force uv add mcp --reinstall
uv pip install matlabengine
1 curl -LsSf https://astral.sh/uv/install.sh | sh 2 pwd 3 python 4 uv run main.py 5 uv add mcp 6 uv init 7 uv add mcp 8 uv run main.py 9 echo $MATLAB_PATH 10 export MATLAB_PATH="/opt/matlab/R2025b" 11 echo $MATLAB_PATH 12 uv run main.py 13 python -m pip install setuptools 14 python -m pip install setuptools --break-system-packages 15 uv run main.py 16 pip install mcp 17 pip install mcp --break-system-packages 18 export MATLAB_PATH="/opt/matlab/R2025b" 19 python -m mcp run main.py 20 which mcp 21 mcp run main.py 22 pip install mcp[cli] 23 pip install mcp[cli] --break-system-packages 24 pip install mcp[cli] 25 mcp run main.py 26 history
class MATLABEngineManager: """Manages MATLAB engine initialization and lifecycle."""
def __init__(self):
self._engine = None
self._initialize()
def _initialize(self):
"""Initialize MATLAB engine with proper error handling."""
self._ensure_matlab_engine_installed()
import matlab.engine
self._engine = matlab.engine.connect_matlab("MATLAB_3616")
self._engine.addpath(str(MATLAB_DIR))