Skip to content
github-actions[bot] edited this page Mar 22, 2026 · 21 revisions

MATLAB MCP Server – 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).

What is this?

A Python MCP server that gives AI agents (Claude, Cursor, Copilot, custom agents) the ability to:

  • Execute MATLAB code — sync for fast commands, async for long-running jobs with progress tracking
  • Discover toolboxes & functions — browse installed toolboxes, list functions, retrieve help text
  • Check code quality — run MATLAB's checkcode/mlint linter before execution
  • Generate interactive plots — MATLAB figures auto-converted to interactive Plotly JSON
  • Manage data files — upload, download, and read results from session directories
  • Use custom libraries — expose your own .m functions as first-class MCP tools
  • Monitor server health — real-time metrics dashboard, execution statistics, error tracking

Why it exists

MATLAB is powerful for numerical computing, signal processing, image analysis, and scientific simulations. This server bridges the gap between AI agents and MATLAB by:

  1. Eliminating manual code translation — agents write MATLAB directly, not Python translations
  2. Enabling long-running workflows — async jobs with progress reporting for simulations that take minutes or hours
  3. Preserving numerical precision — native MATLAB execution without conversion overhead
  4. Supporting team deployments — multi-user SSE transport with session isolation and security controls

Key Features

  • Elastic engine pool — dynamically scales MATLAB engines from min_engines to max_engines based on load
  • Hybrid sync/async execution — returns results instantly for fast code, auto-promotes to background jobs if exceeding sync_timeout
  • Progress tracking — long-running jobs report progress via mcp_progress() helper; agents poll status in real time
  • Session isolation — each user gets a dedicated workspace and temp directory; workspace auto-cleared between sessions
  • Security hardening — function blocklist (system, eval, shell escapes), filename sanitization, upload size limits
  • Interactive Plotly figures — MATLAB plots converted to Plotly JSON with WebGL support for 10,000+ data points
  • Custom tool exposure — define MATLAB functions in custom_tools.yaml, agents call them like native MCP tools
  • Monitoring dashboard — web UI with real-time charts of pool utilization, job throughput, execution times, error rates
  • Offline installation — bundled wheel vendor for air-gapped environments

Supported Platforms

Platform MATLAB Version Transport
macOS (Intel/Apple Silicon) 2020b+ stdio, SSE
Windows 10/11 (x64) 2020b+ stdio, SSE
Docker 2020b+ (volume-mounted) SSE

Quick Start

1. Install the Server

# Install from PyPI (requires Python 3.10+)
pip install matlab-mcp-server

# Or install from source
git clone https://github.com/HanSur94/matlab-mcp-server-python.git
cd matlab-mcp-server-python
pip install -e .

2. Verify MATLAB Engine API

# Test that MATLAB Engine for Python is installed
python -c "import matlab.engine; print('✓ MATLAB engine available')"

If this fails, see Installation for MATLAB Engine API setup.

3. Start the Server

Stdio transport (single agent, simplest):

matlab-mcp

SSE transport (multiple agents, reverse proxy recommended):

matlab-mcp --transport sse --port 8765

4. Connect an AI Agent

Claude Desktop: Add to ~/.config/Claude/claude_desktop_config.json:

{
  "mcpServers": {
    "matlab": {
      "command": "matlab-mcp",
      "args": ["--transport", "stdio"]
    }
  }
}

Then restart Claude Desktop and ask:

Execute this MATLAB code: x = magic(5); disp(x);

Result:

x =

    17    24     1     8    15
    23     5     7    14    16
     4     6    13    20    22
    10    12    19    21     3
    11    18    25     2     9

Quickstart Code Snippet

Hello MATLAB

# Terminal 1: Start server
$ matlab-mcp
INFO: MCP server started on stdio
# Terminal 2 (or Claude Desktop): Run code
Agent: Execute: A = [1 2 3; 4 5 6]; b = A * A'; disp(b);

Server response:
b =
    14    32
    32    77

Long-Running Job (Auto Async)

Agent: Run this 10-million-iteration Monte Carlo simulation:

code = '''
n = 1e7;
count = 0;
for i = 1:n
  x = rand(); y = rand();
  if x^2 + y^2 <= 1
    count = count + 1;
  end
  if mod(i, 1e6) == 0
    progress = i / n * 100;
    mcp_progress(progress, sprintf('%d%% done', progress));
  end
end
pi_estimate = 4 * count / n;
disp(['π ≈ ', num2str(pi_estimate)]);
'''

execute_code(code)

Result: {
  "status": "running",
  "job_id": "job-abc123",
  "message": "Code exceeds 30s timeout, promoted to async"
}

Agent: Get status...
get_job_status("job-abc123")

Result: {
  "job_id": "job-abc123",
  "status": "running",
  "progress": 45.0,
  "message": "45% done",
  "elapsed_seconds": 32.1
}

Agent: Retrieve result...
get_job_result("job-abc123")

Result: {
  "status": "completed",
  "output": "π ≈ 3.14159",
  "execution_time": 87.3
}

Generate a Plot

Agent: Create a sine wave plot:

code = '''
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x, y, 'b-', 'LineWidth', 2);
xlabel('x'); ylabel('sin(x)');
title('Sine Wave');
grid on;
'''

execute_code(code)

Result: {
  "status": "completed",
  "figure": {
    "type": "image/plotly+json",
    "data": [{"x": [...], "y": [...], "type": "scatter", "mode": "lines", ...}],
    "layout": {...}
  },
  "thumbnail": "data:image/png;base64,iVBORw0KGgoAAAA..."
}

Quick Navigation

Getting Started

  • Installation — Prerequisites, MATLAB Engine API setup, server installation & startup
  • Configuration — Full YAML reference (pool, timeouts, security, monitoring)
  • Examples — Ready-to-run MATLAB snippets for common tasks

Tools & Integration

  • MCP Tools Reference — All 20 built-in tools: code execution, job management, discovery, file I/O, monitoring
  • Custom Tools — Define MATLAB functions in custom_tools.yaml, expose as AI-callable tools

Deep Dives

  • Architecture — System design: engine pool, job executor, async promotion, session model
  • Async Jobs — Job lifecycle, progress reporting, timeout-based promotion mechanics
  • Security — Function blocklist, workspace isolation, upload validation

Troubleshooting

  • Troubleshooting — Engine startup, SSE connection, blocked functions, stuck jobs, Plotly conversion
  • FAQ — MATLAB versions, agent compatibility, performance tuning, deployment scenarios

Monitoring & Operations

The server includes a web dashboard for real-time monitoring:

┌─────────────────────────────────────────────┐
│ MATLAB MCP Server Dashboard                 │
├──────────────────┬──────────────────────────┤
│ Status: Healthy  │ Uptime: 12h 34m          │
├──────────────────┼──────────────────────────┤
│ Pool Utilization │ 60%                      │
│ Engines (busy)   │ 3/5                      │
│ Active Jobs      │ 2 (1 running, 1 pending)│
│ Completed Today  │ 287                      │
│ Avg Execution    │ 42ms                     │
│ Errors/min       │ 0                        │
└──────────────────┴──────────────────────────┘

Access at http://localhost:8766/dashboard when running SSE transport with monitoring enabled.


Architecture Overview

graph TD
    Agent["AI Agent<br/>(Claude/Cursor/Copilot)"]
    MCP["MCP Server<br/>(FastMCP)"]
    Executor["Job Executor<br/>(sync/async hybrid)"]
    Pool["Engine Pool Manager<br/>(elastic scaling)"]
    Engines["MATLAB Engines<br/>(2020b+)"]
    
    Agent -->|MCP Protocol| MCP
    MCP -->|submit job| Executor
    Executor -->|acquire engine| Pool
    Pool -->|exec code| Engines
    Engines -->|result| Pool
    Pool -->|return to executor| Executor
    Executor -->|formatted result| MCP
    MCP -->|response| Agent
Loading

Data Flow: Sync Execution

sequenceDiagram
    Agent->>Server: execute_code("x = magic(3)")
    Server->>Security: check_code()
    Security-->>Server: OK
    Server->>Pool: acquire_engine()
    Pool-->>Server: Engine #1
    Server->>Engine: eval("x = magic(3)")
    Engine-->>Server: result (completed in 0.2s)
    Server->>Executor: format_result()
    Executor-->>Server: formatted JSON
    Server->>Agent: {status: "completed", output: "x = ...", ...}
Loading

Data Flow: Async Promotion

sequenceDiagram
    Agent->>Server: execute_code("long_simulation()")
    Server->>Security: check_code()
    Security-->>Server: OK
    Server->>Pool: acquire_engine()
    Pool-->>Server: Engine #2
    Server->>Engine: eval(background=True)
    Server-->>Agent: {status: "running", job_id: "abc123"}
    Engine->>Engine: ...running... (60s)
    Agent->>Server: get_job_status("abc123")
    Server-->>Agent: {progress: 45%, message: "..."}
    Agent->>Server: get_job_result("abc123")
    Server->>Engine: get_result()
    Engine-->>Server: completed result
    Server-->>Agent: {status: "completed", output: "..."}
Loading

Key Concepts

Session Model

  • stdio mode: Single default session shared by all requests
  • SSE mode: Each client gets a unique session with isolated temp directory
  • Workspace auto-cleared between sessions (when workspace_isolation=true)

Elastic Pool

  • Starts with min_engines (default 1)
  • Scales up to max_engines (default 5) when queue forms
  • Scales down to min_engines when engines idle >15 minutes
  • Health-checked every 60 seconds; dead engines auto-replaced

Async Promotion

  • Code completing within sync_timeout (default 30s) returns immediately
  • Code exceeding timeout auto-promoted to background job
  • Agent polls get_job_status() for progress, calls get_job_result() when done

Security

  • Blocklist scanning: Detects system(), unix(), dos(), ! (shell escape), eval(), and others
  • String-literal aware: Ignores blocked functions inside strings and comments
  • Workspace isolation: Each session has dedicated temp directory, workspace cleared on switch
  • Upload limits: Max 100MB per file (configurable)
  • Filename sanitization: Prevents ../ path traversal

Getting Help

  • GitHub Issues — Bug reports, feature requests, discussions
  • README — Quick start and project overview
  • Troubleshooting — Common issues and solutions
  • FAQ — Frequently asked questions

Next Steps

  1. Installation — Get the server running
  2. Quick Examples — Try a few MATLAB snippets
  3. MCP Tools Reference — Explore all 20 tools
  4. Configuration — Tune for your environment
  5. Custom Tools — Expose your own MATLAB functions

Happy coding! 🚀

Clone this wiki locally