Skip to content
github-actions[bot] edited this page Apr 3, 2026 · 20 revisions

MATLAB MCP Server — FAQ

General / Overview

What is this project?

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.

What MATLAB versions are supported?

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.

What are the supported languages?

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.

What is the license?

This project is open-source. Licensing details are available in the repository's LICENSE file.

Can I use it without MATLAB installed?

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.

What AI agents work with this?

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.


Setup

How do I install the MATLAB Engine API?

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.

What's the quickest way to get started?

  1. Install Python 3.10+
  2. Install the MATLAB Engine API (see above)
  3. Install the server:
    pip install matlab-mcp-python
  4. Generate an auth token:
    matlab-mcp --generate-token
  5. Start the server (example: streamable HTTP for remote agents):
    export MATLAB_MCP_AUTH_TOKEN=<token-from-step-4>
    matlab-mcp --transport streamablehttp
  6. Connect your agent using Agent-Onboarding

Should I use stdio or streamable HTTP?

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.

How do I configure the server?

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-mcp

Via config file (more control):

server:
  transport: streamablehttp
  host: 127.0.0.1
  port: 8765

pool:
  min_engines: 2
  max_engines: 8

execution:
  sync_timeout: 60

See Configuration for the complete reference.

Can I run the server in Docker?

Yes. A docker-compose.yml is included:

docker-compose up

Important: Docker images do not include MATLAB. You must mount your MATLAB installation as a volume. See Installation for Docker setup details.


Performance

How many engines should I allocate?

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.

What if all engines are busy?

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.

Does running multiple engines slow down my MATLAB?

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.

How do I optimize for large batch jobs?

  1. Increase execution.sync_timeout (default 30s) so more jobs complete inline without async promotion
  2. Increase pool.max_engines to handle more concurrent jobs
  3. Configure workspace.default_paths to preload frequently-used toolboxes at startup
  4. Use async jobs (e.g., Monte Carlo simulations) and poll for progress via get_job_status

What about network latency for remote agents?

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.


Integration

How do I expose custom MATLAB functions as MCP tools?

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 frequencies

The 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.

Can I use this with CI/CD pipelines?

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.m

The --inspect flag skips MATLAB engine pool startup; use stdio for direct process I/O.

How do I deploy to production (shared server)?

  1. Start the server with authentication:

    export MATLAB_MCP_AUTH_TOKEN=$(matlab-mcp --generate-token)
    matlab-mcp --transport streamablehttp
  2. 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";
    }
  3. Distribute the token to your team via secure channels (1Password, AWS Secrets Manager, etc.)

  4. Configure each agent to use the shared endpoint and token. See Agent-Onboarding.

  5. Monitor via the dashboard at http://localhost:8766/dashboard (if monitoring is enabled).

What reverse proxy settings do I need?

Required headers:

  • Authorization: Bearer <token> — forwarded to the /mcp endpoint
  • 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

Architecture & Concepts

How does async execution work?

  1. Inline execution (≤ sync_timeout): Code completes in the same request; result returned immediately.
  2. Async promotion (> sync_timeout): Code is promoted to a background job; agent receives a job_id immediately and can poll for completion.
  3. Progress tracking: Use mcp_progress() in MATLAB to update progress, readable via get_job_status.

Example MATLAB progress:

for i = 1:100
    % ... computation ...
    mcp_progress(__mcp_job_id__, i, sprintf('Completed %d%%', i));
end

The agent polls get_job_status and reads the progress percentage.

See Async-Jobs for detailed mechanics and examples.

What happens to files I upload?

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.

Are user sessions isolated?

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

Can I visualize MATLAB plots?

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.


Security

Is it safe to expose over the network?

For HTTP transports (streamablehttp / SSE):

  1. Always put the server behind a reverse proxy with additional authentication (OAuth, mTLS, etc.)
  2. Always use HTTPS in production (reverse proxy terminates TLS)
  3. Enable bearer token auth via MATLAB_MCP_AUTH_TOKEN
  4. Default bind address is 127.0.0.1 (loopback only) — if you need remote access, explicitly bind to 0.0.0.0 and document the firewall rule requirement

For stdio transport:

  • Inherently safe; only the local agent process can execute code

What MATLAB functions are blocked?

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  # optional

See Security for the complete list and rationale.

Can agents read sensitive files from my machine?

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.

What if I need per-user access control?

Out of scope for v2.0. Recommended approaches:

  1. Per-agent token rotation: Generate unique tokens for each user/agent; maintain a whitelist
  2. Reverse proxy scoping: Map reverse proxy auth headers to MATLAB user IDs; pass via custom headers
  3. Per-user MATLAB sessions: Future enhancement — one engine pool per user (tracked as v2.1 feature)

Troubleshooting

Server won't start — "RuntimeError: cannot find MATLAB engine"

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.

All engines are stuck / hanging

This can happen on network-mapped drives or under high load. Restart the server:

pkill -f "matlab-mcp"  # or Ctrl+C
matlab-mcp  # restart

To reduce hang risk, disable network drive access to MATLAB and ensure sufficient disk I/O.

Connection refused when remote agent tries to connect

Check:

  1. Server is running: curl -i http://localhost:8765/health
  2. Server is bound to the correct interface: Check log output for "HTTP endpoint" or "listening on 0.0.0.0:8765"
  3. Firewall is not blocking port 8765: sudo ufw allow 8765 (Linux) or Windows Firewall rules
  4. Bearer token is being sent: curl -H "Authorization: Bearer <token>" http://localhost:8765/health

Bearer token rejected (401 Unauthorized)

Verify the token environment variable:

echo $MATLAB_MCP_AUTH_TOKEN  # should print a 64-character hex string

If empty, generate one:

matlab-mcp --generate-token

Restart the server with the new token set.

Plots are not converting to Plotly

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.

Out of memory errors

Each MATLAB engine consumes 500MB–2GB. Reduce pool.max_engines or increase system RAM.

free -h  # Linux
vm_stat  # macOS

FAQ Links

Clone this wiki locally