-
Notifications
You must be signed in to change notification settings - Fork 0
FAQ
The MATLAB MCP Server is a Python application that implements the Model Context Protocol (MCP) to enable AI agents (Claude, Cursor, etc.) to execute MATLAB code, manage long-running jobs, discover toolboxes and functions, check code quality, and generate interactive visualizations. It bridges MATLAB and AI agents through a standardized protocol.
MATLAB R2022b and later. The MATLAB Engine API for Python must be installed separately from your MATLAB installation. See Installation for platform-specific instructions.
No. The server requires a local MATLAB installation with the Engine API configured. It connects to real MATLAB engines, not a simulator. For CI testing without MATLAB, the project includes a mock engine.
- Windows (10, 11)
- macOS (Intel and Apple Silicon)
- Linux (Ubuntu 20.04+, CentOS 8+, other major distributions)
Docker support is available for all platforms.
The project license is defined in the repository. Check the LICENSE file for details.
Any agent supporting the Model Context Protocol:
- Claude Desktop
- Cursor
- GitHub Copilot (with MCP support)
- Claude Code
- Custom agents built with MCP SDKs for Python, TypeScript, etc.
Yes:
pip install matlab-mcp-pythonYou still need the MATLAB Engine API installed separately. See Installation.
The installation path varies by OS and MATLAB version:
macOS / Linux:
cd /Applications/MATLAB_R2024a.app/extern/engines/python # macOS
# or /usr/local/MATLAB/R2024a/extern/engines/python # Linux
pip install .Windows:
cd "C:\Program Files\MATLAB\R2024a\extern\engines\python"
pip install .Adjust the path for your MATLAB version. See Installation for detailed platform-specific steps.
| Aspect | stdio | SSE |
|---|---|---|
| Users | Single (AI agent launches server) | Multiple (via HTTP) |
| Setup | Simpler | Requires reverse proxy + auth |
| Network | No | Yes (requires HTTP/HTTPS) |
| Best for | Personal use, Claude Desktop | Teams, shared servers |
See Configuration for details.
Stdio (simplest):
python -m matlab_mcp.serverSSE with uvicorn:
uvicorn matlab_mcp.server:app --host 0.0.0.0 --port 8765Docker:
docker-compose upSee Installation for full setup examples.
Yes, with SSE transport. Start the server on a remote machine and connect via HTTP. Important: Always put it behind an authenticating reverse proxy for production. See Security.
Edit config.yaml or use environment variables with the MATLAB_MCP_ prefix. See Configuration for all options and examples.
graph TD
A[AI Agent] -->|MCP Protocol| B[MCP Server]
B -->|Job Executor| C[Engine Pool]
C -->|MATLAB Code| D[MATLAB Engines]
B -->|Security| E[Validator]
B -->|Session| F[Session Manager]
D -->|Results| G[Output Formatter]
G -->|Plotly/PNG| B
B -->|Response| A
- Agent sends code via the
execute_codetool - Server validates code against security policy
- Executor acquires an engine from the pool
- Code runs synchronously (if <30s) or async (if longer)
- Results are formatted and returned with visualizations
- Engine is released back to the pool
See Architecture for the full data flow.
Code exceeding sync_timeout (default 30s) is automatically promoted to a background job:
- Agent gets a
job_idimmediately - Code runs in the background
- Agent polls
get_job_statusfor progress - Agent calls
get_job_resultwhen complete
See Async Jobs for progress reporting and configuration.
Use the mcp_progress() MATLAB helper:
for i = 1:1000000
% ... computation ...
if mod(i, 10000) == 0
mcp_progress(__mcp_job_id__, 100*i/1000000, sprintf('Iteration %d', i));
end
endProgress is stored in a JSON file and readable via get_job_status.
Option 1: Custom Tools (recommended)
Define in custom_tools.yaml:
tools:
- name: signal_analysis
function: my_signal_analysis
description: Analyze frequency content of a signal
parameters:
signal:
type: array
description: Input signal vector
fs:
type: number
description: Sampling frequency (Hz)
returns:
description: Frequencies and magnitudesCustom tools become first-class MCP tools. See Custom Tools.
Option 2: Path Configuration
Add directories to workspace.default_paths in config.yaml, then call from code:
result = my_custom_function(input_data);Yes! MATLAB figures are automatically converted to Plotly JSON for interactive rendering in web-based clients. Fallback static PNG images are generated automatically. See Examples#plotting_examples.md.
- Line plots (2D curves)
- Scatter plots
- Bar / histogram charts
- Surface / mesh plots
- Image plots (heatmaps, contours)
- Subplots with multiple axes
- Tiled layouts
Complex custom graphics may fall back to static PNG.
Yes, three tools available:
| Tool | Purpose |
|---|---|
read_script |
Read .m files as text |
read_data |
Read .mat / .csv / .json / .txt / .xlsx files |
read_image |
Read .png / .jpg / .gif as inline images |
Use list_files to see what's in your session directory.
Use the upload_data tool with base64-encoded content:
upload_data(
filename="data.csv",
content_base64="<base64-encoded file>"
)
Files go to the session's temp directory and persist for the session lifetime.
graph LR
A[Request] --> B{sync_timeout?}
B -->|< 30s| C[Sync execution]
B -->|>= 30s| D[Async job]
C --> E[Return result]
D --> F[Return job_id]
F --> G[Poll status]
G --> H[Get result]
| Scenario | Recommended |
|---|---|
| Personal use, single user | 1–2 engines |
| Small team (2–5 users) | 2–4 engines |
| Medium team (5–20 users) | 4–8 engines |
| Large team / production | 8–16 engines (or more) |
Limits:
- macOS: ~4 concurrent engines (known MATLAB limitation)
- Windows/Linux: Limited by MATLAB license + available memory
Typical range: 500 MB to 2 GB per engine depending on loaded toolboxes and data. Monitor via the dashboard at http://localhost:8766/dashboard.
Requests queue up to queue_max_size (default 50). If capacity allows, a new engine is started proactively. Requests are served FIFO.
-
Increase
max_execution_timefor long computations - Use async jobs for anything >30s
-
Monitor
large_result_threshold— very large results may be truncated - Consider workspace isolation trade-offs (slows warm-up but isolates sessions)
See Configuration.
Yes, in config.yaml:
output:
plotly_conversion: falseThis returns static PNG only, saving conversion time.
Use the stdio transport in your CI/CD scripts:
echo 'x = rand(100, 100); eig(x)' | \
python -m matlab_mcp.server --config config.yamlThe server reads code from stdin and outputs JSON.
Not directly via MCP, but you can:
- Run the server separately
- Use an MCP client library (e.g.,
mcp-client-python) to send requests
The server is an MCP server, not a Python library. To call MATLAB from Python, use the MATLAB Engine API directly:
import matlab.engine
eng = matlab.engine.start_matlab()
result = eng.eval('x = 1:10; mean(x)')
eng.quit()The MCP server is for agent integration, not direct Python code integration.
Yes. MATLAB Coder functions can be called like any other function. GPU acceleration (if available in your MATLAB license) works automatically.
Limited support. You can load and run Simulink models programmatically, but the visual model editor is not exposed through the MCP interface.
SSE Transport (network-exposed):
- ✅ Always put behind an authenticating reverse proxy
- ✅ Set
require_proxy_auth: truein config - ✅ Use HTTPS / TLS
- ✅ Implement rate limiting in the proxy
Stdio Transport:
- Designed for single-user, local only
- Not intended for network exposure
See Security for detailed hardening guidelines.
The default blocklist prevents code injection and sandbox escape:
system, unix, dos, !
eval, feval, evalc, evalin, assignin
perl, python
Blocked functions are detected via regex pattern matching. You can customize the list in config.yaml:
security:
blocked_functions: [system, unix, dos]Yes. When workspace_isolation: true (default), each session's workspace is cleared between runs:
clear all; clear global; clear functions; fclose all; restoredefaultpathThis prevents cross-session data leakage.
Filenames are sanitized to prevent path traversal. File size limits are enforced (default 100 MB). Consider additional validation in your reverse proxy.
Yes. For SSE deployments, a reverse proxy with authentication is mandatory:
- Basic auth (minimum)
- OAuth 2.0 (recommended)
- mTLS (strong option)
- API key validation
See Security for setup examples.
A real-time dashboard is available at:
http://localhost:8766/dashboard
Displays:
- Pool utilization
- Job counts and execution times
- Session metrics
- System memory & CPU
- Error logs
curl http://localhost:8766/healthReturns:
{
"status": "healthy",
"uptime_seconds": 3600,
"pool_utilization": 0.5,
"active_jobs": 2,
"active_sessions": 1
}Health is "degraded" if error rate is high or pool is fully utilized; "unhealthy" if engines are offline.
Check the logs:
tail -f ./logs/server.logCommon issues:
- MATLAB Engine API not installed: Run
pip install matlab-enginefrom your MATLAB installation - MATLAB path incorrect: Set
pool.matlab_rootin config or viaMATLAB_MCP_POOL_MATLAB_ROOT - Incompatible MATLAB version: Use R2022b or later
See Troubleshooting.
- Check
get_job_status(job_id)— is it truly running? - Look at logs for MATLAB errors
- Try
cancel_job(job_id)to force termination - Check for infinite loops or blocking I/O in your code
In config.yaml:
server:
log_level: debugOr via env var:
MATLAB_MCP_SERVER_LOG_LEVEL=debug python -m matlab_mcp.serverLarge results are truncated to max_inline_text_length (default 50,000 chars). Truncated content is saved to a file in the session temp directory and a link is returned.
pip install -e ".[dev]"
pytest tests/ -vTests use a mock MATLAB engine — no real MATLAB needed.
- Implement the tool function in
src/matlab_mcp/tools/ - Register it in
src/matlab_mcp/server.pywith@mcp.tooldecorator - Add comprehensive tests in
tests/test_tools_*.py - Update MCP-Tools-Reference wiki page
See Architecture for the component overview.
pip install build twine
python -m build
python -m twine upload dist/*The CI/CD pipeline (GitHub Actions) automates this on release tags.
Open issues or PRs on GitHub. All contributions welcome!