-
Notifications
You must be signed in to change notification settings - Fork 0
Home
Welcome to the MATLAB MCP Server wiki! This server connects any AI agent to a shared MATLAB installation via the Model Context Protocol (MCP).
The MATLAB MCP Server bridges the gap between AI agents and MATLAB by exposing a complete execution environment as a set of standardized tools. Whether you're running Monte Carlo simulations, processing signals, training machine learning models, or generating interactive plots, your AI agents can now call MATLAB directly without leaving the conversation.
Key capabilities:
- 🔧 Code Execution — Run MATLAB code synchronously (fast queries) or asynchronously (long-running jobs)
- 🔍 Toolbox Discovery — Browse installed toolboxes, list available functions, retrieve help text
- ✅ Code Quality — Lint code with
checkcode/mlintbefore execution - 📊 Interactive Plots — Automatically convert MATLAB figures to Plotly JSON for web rendering
- 🛠️ Custom Tools — Expose your own
.mand.mexfunctions as first-class AI-callable tools - 📁 File Management — Upload data, read results, manage session workspaces
- 📈 Monitoring & Health — Real-time dashboard, metrics, error logs, engine pool status
- 🔐 Multi-User Isolation — Session-based workspaces with configurable security
| Platform | MATLAB Version | Status |
|---|---|---|
| macOS | R2020b+ | ✅ Fully supported |
| Windows | R2020b+ | ✅ Fully supported |
| Docker | R2020b+ | ✅ Supported (with licensing) |
# Install MATLAB Engine API (macOS/Linux/Windows)
cd /path/to/MATLAB/extern/engines/python
python setup.py install
# Install the MCP server
pip install matlab-mcp-server# Run this once to test your installation
matlab-mcp-server --config config.yamlThen, via your AI agent (Claude, Cursor, etc.), call the execute_code tool:
fprintf('Hello from MATLAB!\n');
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x, y);
title('Sine Wave');The agent receives the plot as interactive Plotly JSON, executable output, and any errors.
graph LR
A["AI Agent<br/>(Claude, Cursor, ...)"] -->|MCP Protocol| B["MATLAB MCP Server<br/>(Python FastMCP)"]
B -->|Acquire Engine| C["Engine Pool Manager<br/>(2–N MATLAB instances)"]
C -->|Execute Code| D["MATLAB<br/>(Local or Remote)"]
D -->|Result| E["Job Executor<br/>(Sync or Async)"]
E -->|Format Output| F["ResultFormatter<br/>(Text, Plots, Files)"]
F -->|Response| A
style A fill:#e1f5ff
style B fill:#fff3e0
style C fill:#f3e5f5
style D fill:#e8f5e9
style E fill:#fce4ec
style F fill:#e0f2f1
- Installation — Step-by-step setup, Python/MATLAB versions, Docker
- Configuration — YAML reference for all server settings (pool sizing, timeouts, security, etc.)
- Examples — Ready-to-run MATLAB snippets and server configs
- MCP Tools Reference — All 20+ built-in tools with parameters, examples, and response formats
-
Custom Tools — How to expose your own
.mfunctions as AI-callable tools - Async Jobs — Patterns for long-running computations, progress reporting, job lifecycle
- Architecture — System design, elastic engine pooling, job tracking, session model
- Security — Function blocklist, workspace isolation, upload controls, multi-user best practices
- Troubleshooting — Common issues (engine startup, macOS limits, stuck jobs, etc.) with solutions
- FAQ — Frequently asked questions
graph TB
subgraph "Code Execution"
A["Sync Execution<br/><30s"]
B["Async Promotion<br/>>30s"]
C["Job Tracking<br/>(Status, Results)"]
end
subgraph "Engine Management"
D["Elastic Pool<br/>(Min–Max engines)"]
E["Health Checks<br/>(Auto-replace dead)"]
F["Proactive Warmup<br/>(Avoid cold starts)"]
end
subgraph "Session Isolation"
G["Per-user Workspaces<br/>(Temp dirs)"]
H["Variable Isolation<br/>(clear all between)"]
I["Auto-cleanup<br/>(Temp file deletion)"]
end
subgraph "Output Formatting"
J["Plotly Conversion<br/>(Figures → JSON)"]
K["Image Thumbnails<br/>(Base64 embedded)"]
L["Text Truncation<br/>(Configurable)"]
end
subgraph "Security"
M["Function Blocklist<br/>(system, eval, ...)"]
N["Path Sanitization<br/>(Prevent traversal)"]
O["Upload Limits<br/>(Size, filename rules)"]
end
subgraph "Monitoring"
P["Live Dashboard<br/>(Pool, jobs, metrics)"]
Q["Health Evaluation<br/>(Healthy/Degraded)"]
R["Metrics Storage<br/>(SQLite time-series)"]
end
style A fill:#c8e6c9
style D fill:#bbdefb
style G fill:#ffe0b2
style J fill:#f8bbd0
style M fill:#d1c4e9
style P fill:#b2dfdb
The server orchestrates multiple components working in concert:
- FastMCP Server — Receives tool calls from AI agents via stdio or SSE
- Engine Pool — Maintains 2–N MATLAB engines with auto-scaling and health checks
-
Job Executor — Promotes code to async if it exceeds
sync_timeout(default 30s) - Session Manager — Isolates workspaces; each user gets a temp directory
-
Security Validator — Blocks dangerous functions (
system,eval, etc.) before execution - Result Formatter — Converts MATLAB output to MCP response format (text, plots, files)
- Monitoring Subsystem — Tracks metrics, health, and events (optional, off by default)
sequenceDiagram
participant Agent as AI Agent
participant MCP as FastMCP Server
participant Exec as JobExecutor
participant Pool as EnginePool
participant Engine as MATLAB Engine
Agent->>MCP: execute_code("x = 1:10; plot(x);")
MCP->>Exec: execute(code, session_id)
Exec->>Exec: Security check (blocklist)
Exec->>Pool: acquire_engine()
Pool-->>Exec: engine (IDLE)
Exec->>Engine: eval(code, background=False, timeout=30)
Engine->>Engine: Run code
alt Completes < 30s
Engine-->>Exec: result + figures
Exec->>Exec: Format output (Plotly, text)
else Exceeds 30s
Engine-->>Exec: (not done)
Exec-->>MCP: job_id (async)
MCP-->>Agent: job_id
Agent->>MCP: get_job_result(job_id)
end
Exec->>Pool: release_engine()
Exec-->>MCP: {"status": "completed", "output": "...", "figures": [...]}
MCP-->>Agent: MCP response
- Install MATLAB Engine API for Python
pip install matlab-mcp-server- Create
config.yaml(or use defaults) - Run
matlab-mcp-server --config config.yaml - Connect via Claude Desktop, Cursor, or custom agent
docker-compose up
# Dashboard: http://localhost:8766/dashboard
# MCP Server: localhost:8765 (stdio) or SSE endpointSee Installation for detailed steps.
- stdio — Default; connects directly to a single process (ideal for Claude Desktop)
- SSE (Server-Sent Events) — Multi-user; requires reverse proxy with authentication (ideal for shared servers)
Key settings in config.yaml:
server:
transport: stdio # or "sse" for multi-user
log_level: info
pool:
min_engines: 2
max_engines: 10
health_check_interval: 60 # seconds
execution:
sync_timeout: 30 # Promote to async if exceeds
max_execution_time: 86400 # 1 day
workspace_isolation: true # Clear between sessions
output:
plotly_conversion: true # Convert figures to JSON
max_inline_text_length: 50000 # Truncate large outputs
security:
blocked_functions_enabled: true # Enable function blocklist
max_upload_size_mb: 100 # Upload size limit
monitoring:
enabled: true # Optional dashboard
dashboard_enabled: true
http_port: 8766See Configuration for the complete reference.
The server exposes 20+ tools organized into categories:
| Category | Tools |
|---|---|
| Code Execution |
execute_code, check_code, get_workspace
|
| Job Management |
get_job_status, get_job_result, cancel_job, list_jobs
|
| Discovery |
list_toolboxes, list_functions, get_help
|
| File Management |
upload_data, delete_file, list_files
|
| File Reading |
read_script, read_data, read_image
|
| Admin | get_pool_status |
| Monitoring |
get_server_metrics, get_server_health, get_error_log
|
Plus any custom tools you define in custom_tools.yaml.
See MCP Tools Reference for full details.
Expose your MATLAB functions (.m, .mex) as AI-callable tools:
# custom_tools.yaml
tools:
- name: signal_fft
matlab_function: signal_processing.fft_analysis
description: "Perform FFT frequency analysis on input signal"
parameters:
signal:
type: array
description: Input signal vector
sampling_rate:
type: number
description: Sampling rate in Hz
returns:
frequencies: "Frequency vector"
magnitude: "FFT magnitude spectrum"Your agent can then call signal_fft just like any built-in tool.
See Custom Tools for full documentation.
The repository includes working MATLAB examples:
- basic_usage.m — Matrix ops, linear solvers, statistics
- plotting_examples.m — Line plots, scatter, 3D surfaces (all convert to Plotly)
- signal_processing.m — FFT, filtering, spectrograms
- async_simulation.m — Long-running Monte Carlo with progress updates
- config_minimal.yaml — Single-user stdio setup
- config_multiuser.yaml — Multi-user SSE setup
See Examples for details and runnable code.
The server includes multiple safeguards:
-
Function Blocklist — Blocks
system(),eval(), shell escapes (!), etc. (customizable) -
Workspace Isolation — Separate temp directories per session;
clear allbetween sessions - Upload Protection — Filename sanitization, size limits, path-traversal prevention
- Session Cleanup — Auto-delete temp files and expired jobs
- Proxy Authentication — SSE requires reverse proxy with authentication
See Security for detailed recommendations by deployment scenario.
Optional real-time dashboard (enabled by default in monitoring):
http://localhost:8766/dashboard
Shows:
- Live Gauges — Pool utilization, active jobs, memory, errors
- Time-Series Charts — Job throughput, execution time, sessions, memory
- Event Log — Job completions, failures, engine scaling, blocked attempts
- Health Status — Current health (Healthy/Degraded/Unhealthy), uptime
Also available via get_server_metrics and get_server_health tools.
- Startup overhead — First code execution on an idle engine takes ~2–5s (MATLAB startup)
-
Proactive warmup — Set
proactive_warmup_thresholdto keep engines ready -
Async for long jobs — Anything >30s auto-promotes to async; use
mcp_progress()for updates -
Tune pool size — Start with
min_engines: 2, increase if under contention -
macOS note — Limit
max_engines ≤ 4due to known stability issues
See Troubleshooting for solutions to common problems.
- Read the docs — Check the wiki pages linked above
-
Review examples — Run the example
.mfiles in the repo -
Check config — Look at
config.yamlfor all tuning options -
Enable debug logging — Set
log_level: debugto see detailed traces - File an issue — GitHub Issues
| File | Purpose |
|---|---|
config.yaml |
Main configuration (server, pool, execution, security, etc.) |
custom_tools.yaml |
Define custom MATLAB functions as MCP tools |
docker-compose.yml |
Multi-container deployment (server + dashboard) |
src/matlab_mcp/server.py |
FastMCP server entry point |
src/matlab_mcp/pool/manager.py |
Engine pool orchestration |
src/matlab_mcp/jobs/executor.py |
Code execution and job lifecycle |
src/matlab_mcp/monitoring/dashboard.py |
Web dashboard and metrics |
matlab-mcp-server is maintained by @HanSur94.
For issues, contributions, or questions, visit the GitHub repository.
Ready to get started? Head to Installation to set up your first MATLAB MCP server instance.