-
Notifications
You must be signed in to change notification settings - Fork 0
FAQ
The MATLAB MCP Server is a Python application that bridges MATLAB to any AI agent supporting the Model Context Protocol (MCP). It enables Claude, Cursor, GitHub Copilot, and other MCP-compatible agents to execute MATLAB code, discover toolboxes, read files, and access MATLAB capabilities through a standardized interface.
Key value: Minimal setup — agents connect with just an environment variable (auth token) and a network endpoint; no hardcoded credentials or complex configuration required.
MATLAB 2022b and later with the MATLAB Engine API for Python installed.
The Engine API is included with MATLAB but must be installed separately as a Python package. See Installation for step-by-step instructions by platform.
The server itself is written in Python 3.10+. MATLAB code execution uses the MATLAB Engine API. Custom tools and configuration files use YAML and JSON.
This project is open-source. Licensing details are available in the repository's LICENSE file.
No — the server requires a local MATLAB installation with the Engine API configured. For testing without MATLAB, run with the --inspect flag, which skips engine pool startup.
Any agent supporting the Model Context Protocol:
- Claude Code (Anthropic) — via stdio or streamable HTTP
- Codex CLI (Anthropic) — via streamable HTTP (SSE is deprecated)
- Cursor — via stdio or streamable HTTP
- GitHub Copilot — when MCP support is enabled
- Custom agents built with the MCP Python SDK
See Agent-Onboarding for copy-pasteable configuration examples.
The Engine API must be installed separately from your MATLAB installation:
macOS / Linux:
cd /Applications/MATLAB_R2024a.app/extern/engines/python # macOS example
python -m pip install .Windows:
cd "C:\Program Files\MATLAB\R2024a\extern\engines\python"
python -m pip install .Verify the installation:
python -c "import matlab.engine; print('✓ Engine API installed')"See Installation for detailed platform-specific instructions.
- Install Python 3.10+
- Install the MATLAB Engine API (see above)
- Install the server:
pip install matlab-mcp-python
- Generate an auth token:
matlab-mcp --generate-token
- Start the server (example: streamable HTTP for remote agents):
export MATLAB_MCP_AUTH_TOKEN=<token-from-step-4> matlab-mcp --transport streamablehttp
- Connect your agent using Agent-Onboarding
| Transport | Use Case | Setup |
|---|---|---|
| stdio | Single user; agent launches server directly | Simplest; no network config needed |
| streamablehttp | Multiple users; remote agents; corporate deployments | Requires HTTP endpoint; supports concurrent access; recommended for new setups |
| SSE | Legacy; not recommended | Deprecated as of v2.0 — use streamablehttp instead |
Recommendation: Start with --transport stdio for personal use. Switch to --transport streamablehttp when you need multi-user or remote access.
Create a config.yaml file or use environment variables with the MATLAB_MCP_* prefix:
Via environment variable (simplest for deployment):
export MATLAB_MCP_POOL_MIN_ENGINES=2
export MATLAB_MCP_POOL_MAX_ENGINES=8
export MATLAB_MCP_EXECUTION_SYNC_TIMEOUT=60
matlab-mcpVia config file (more control):
server:
transport: streamablehttp
host: 127.0.0.1
port: 8765
pool:
min_engines: 2
max_engines: 8
execution:
sync_timeout: 60See Configuration for the complete reference.
Yes. A docker-compose.yml is included:
docker-compose upImportant: Docker images do not include MATLAB. You must mount your MATLAB installation as a volume. See Installation for Docker setup details.
| Deployment | Recommended | Reasoning |
|---|---|---|
| Personal use | 1–2 | MATLAB is memory-intensive (~500MB–2GB per engine) |
| Small team (2–5 users) | 2–4 | Balance concurrency and memory usage |
| Larger shared server | 4–8 (or based on license limits) | Each concurrent user needs an engine; monitor pool utilization |
Check available memory and MATLAB license concurrent-engine limits before increasing pool.max_engines.
Requests queue up (configurable via execution.queue_max_size, default 50). If the pool hasn't reached max_engines, a new engine is started automatically. Requests are served FIFO as engines become available.
Monitor queue depth via the Monitoring-Dashboard or the get_pool_status tool.
Each engine is an independent MATLAB process consuming separate memory. Running 4 engines with typical toolboxes uses ~4GB of RAM. No shared-process overhead, but cumulative memory can grow.
- Increase
execution.sync_timeout(default 30s) so more jobs complete inline without async promotion - Increase
pool.max_enginesto handle more concurrent jobs - Configure
workspace.default_pathsto preload frequently-used toolboxes at startup - Use async jobs (e.g., Monte Carlo simulations) and poll for progress via
get_job_status
Streamable HTTP transport adds ~100–200ms per request due to HTTP round-trip. For multi-step workflows, batch operations when possible (e.g., send multiple MATLAB commands in one execute_code call) to reduce round-trips.
Use custom_tools.yaml:
tools:
- name: analyze_signal
function: signal_analysis.analyze
description: Analyze a signal (FFT, filtering)
parameters:
signal:
type: array
description: Input signal samples
sample_rate:
type: number
default: 1000
return:
type: object
description: FFT magnitude and frequenciesThe function signal_analysis.analyze becomes a first-class MCP tool. Agents can call it directly without writing MATLAB code.
See Custom-Tools for detailed schema documentation and examples.
Yes. Example: Run MATLAB tests via GitHub Actions:
- name: Run MATLAB tests
env:
MATLAB_MCP_AUTH_TOKEN: ${{ secrets.MCP_TOKEN }}
run: |
matlab-mcp --inspect --transport stdio < test_script.mThe --inspect flag skips MATLAB engine pool startup; use stdio for direct process I/O.
-
Start the server with authentication:
export MATLAB_MCP_AUTH_TOKEN=$(matlab-mcp --generate-token) matlab-mcp --transport streamablehttp
-
Put it behind a reverse proxy (nginx example):
location /mcp { proxy_pass http://localhost:8765/mcp; proxy_set_header Authorization "Bearer $http_x_mcp_token"; }
-
Distribute the token to your team via secure channels (1Password, AWS Secrets Manager, etc.)
-
Configure each agent to use the shared endpoint and token. See Agent-Onboarding.
-
Monitor via the dashboard at
http://localhost:8766/dashboard(if monitoring is enabled).
Required headers:
-
Authorization: Bearer <token>— forwarded to the/mcpendpoint -
Content-Type: application/json— request content type -
Accept: application/json— response content type
Optional:
-
X-Forwarded-For— log the original client IP -
X-Forwarded-Proto— preserve HTTPS scheme
Timeout recommendations:
- Connect timeout: 5 seconds
- Read timeout: 300 seconds (for long MATLAB jobs)
- Write timeout: 300 seconds
-
Inline execution (≤
sync_timeout): Code completes in the same request; result returned immediately. -
Async promotion (>
sync_timeout): Code is promoted to a background job; agent receives ajob_idimmediately and can poll for completion. -
Progress tracking: Use
mcp_progress()in MATLAB to update progress, readable viaget_job_status.
Example MATLAB progress:
for i = 1:100
% ... computation ...
mcp_progress(__mcp_job_id__, i, sprintf('Completed %d%%', i));
endThe agent polls get_job_status and reads the progress percentage.
See Async-Jobs for detailed mechanics and examples.
Files are stored in a per-session temporary directory (/tmp/matlab_mcp/<session_id> on Unix, %TEMP%\matlab_mcp\<session_id> on Windows). They persist for the duration of the session (default idle timeout: 1 hour). After cleanup, files are deleted.
To retrieve results, use read_image, read_data, or read_script tools to fetch files as base64 or plain text.
Yes. By default (workspace_isolation: true):
- Each session gets its own temporary directory
- Each session's MATLAB workspace is cleared between executions:
clear all; clear global; clear functions; fclose all; restoredefaultpath - Sessions do not interfere with each other
Yes. MATLAB figures are automatically converted to interactive Plotly JSON. Supported plot types:
- Line plots
- Scatter plots
- Bar charts
- Histograms
- 3D surfaces
- Heatmaps / image plots
A static PNG fallback is generated for custom graphics. See Examples for plotting examples.
For HTTP transports (streamablehttp / SSE):
- Always put the server behind a reverse proxy with additional authentication (OAuth, mTLS, etc.)
- Always use HTTPS in production (reverse proxy terminates TLS)
-
Enable bearer token auth via
MATLAB_MCP_AUTH_TOKEN -
Default bind address is
127.0.0.1(loopback only) — if you need remote access, explicitly bind to0.0.0.0and document the firewall rule requirement
For stdio transport:
- Inherently safe; only the local agent process can execute code
The security validator blocks 11 dangerous functions by default:
-
system(),unix(),dos()— shell escape (blocked everywhere) -
eval(),evalc(),evalin()— dynamic code execution -
feval()— indirect function calls (optional, can be unblocked) -
assignin()— write to caller's workspace -
python(),perl()— shell escape to other languages -
!— shell escape operator
You can customize the blocklist in config.yaml:
security:
blocked_functions:
- system
- eval
- feval # optionalSee Security for the complete list and rationale.
No, with the default security.upload_max_bytes limit (50MB). MATLAB code runs in an isolated workspace with filesystem access limited to the session's temporary directory. Reading files outside that directory requires explicit MATLAB code (fileread(), load(), etc.); it's not automatic.
Out of scope for v2.0. Recommended approaches:
- Per-agent token rotation: Generate unique tokens for each user/agent; maintain a whitelist
- Reverse proxy scoping: Map reverse proxy auth headers to MATLAB user IDs; pass via custom headers
- Per-user MATLAB sessions: Future enhancement — one engine pool per user (tracked as v2.1 feature)
The MATLAB Engine API is not installed or not found on PYTHONPATH. Run:
python -c "import matlab.engine; print('✓ OK')"If this fails, reinstall the Engine API. See Installation.
This can happen on network-mapped drives or under high load. Restart the server:
pkill -f "matlab-mcp" # or Ctrl+C
matlab-mcp # restartTo reduce hang risk, disable network drive access to MATLAB and ensure sufficient disk I/O.
Check:
- Server is running:
curl -i http://localhost:8765/health - Server is bound to the correct interface: Check log output for "HTTP endpoint" or "listening on 0.0.0.0:8765"
- Firewall is not blocking port 8765:
sudo ufw allow 8765(Linux) or Windows Firewall rules - Bearer token is being sent:
curl -H "Authorization: Bearer <token>" http://localhost:8765/health
Verify the token environment variable:
echo $MATLAB_MCP_AUTH_TOKEN # should print a 64-character hex stringIf empty, generate one:
matlab-mcp --generate-tokenRestart the server with the new token set.
Plots may fall back to static PNG if:
- The figure uses custom graphics objects not recognized by the converter
- Plotly schema validation fails (malformed JSON)
Check config.output.plotly_threshold (default 10MB) — very large figures are not converted. Reduce figure complexity or increase the threshold.
Each MATLAB engine consumes 500MB–2GB. Reduce pool.max_engines or increase system RAM.
free -h # Linux
vm_stat # macOS- Installation — Detailed setup by platform (Windows, macOS, Linux, Docker)
-
Configuration — Complete
config.yamlreference - Agent-Onboarding — MCP connection configs for Claude Code, Codex CLI, Cursor
- Security — Security architecture and best practices
- Async-Jobs — How async execution works; progress reporting
- Custom-Tools — Expose custom MATLAB functions as MCP tools
- Examples — Ready-to-run code examples
- Architecture — System design and component overview
- MCP-Tools-Reference — All 20 MCP tool signatures and behaviors