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

Welcome to the MATLAB MCP Server

Give any AI agent the power of MATLAB — via the Model Context Protocol.

MATLAB MCP Server is a Python-based MCP server that connects coding agents (Claude, Cursor, Copilot) to a shared MATLAB installation. Execute code, discover toolboxes, get interactive Plotly plots, manage files, and run long-running simulations—all through a single secure connection.

Why This Exists

  • AI agents need MATLAB access. Cursor and Codex CLI have no native MATLAB support; this server bridges that gap.
  • Shared MATLAB is expensive. One server + elastic engine pool serves multiple users and agents without buying extra licenses.
  • Code execution should be safe. Function blocklists, workspace isolation, and file upload limits prevent accidents.
  • Long jobs should not block agents. Auto-promote slow code to background execution; agents keep working while MATLAB computes.

Key Capabilities

  • Execute MATLAB Code — Sync for fast commands (< 30s), auto-async for long jobs
  • Elastic Engine Pool — Scales 2–10+ engines based on demand; all engines share one MATLAB license
  • Toolbox Discovery — Browse installed toolboxes, functions, and help text
  • Code Quality Checks — Run checkcode/mlint before execution
  • Interactive Plotly Plots — MATLAB figures auto-convert to interactive JSON charts
  • Custom MCP Tools — Expose your .m functions as first-class AI-callable tools (via YAML)
  • Progress Reporting — Long jobs report execution progress back to the agent
  • Multi-User Sessions — Per-user workspaces via SSE or streamable HTTP
  • Human-in-the-Loop Approval — Optional approval gates for sensitive operations
  • Cross-Platform — Windows 10 (no admin), macOS; MATLAB R2022b+
  • One-Click Windows Install — Offline install.bat with no admin rights needed

Architecture Overview

graph TB
    Agent["AI Agent<br/>(Claude, Cursor)"]
    Transport["Transport Layer<br/>(stdio / SSE / HTTP)"]
    Auth["Auth Middleware<br/>(Bearer Token)"]
    Server["FastMCP Server<br/>(20+ Tools)"]
    JobExec["Job Executor<br/>(Sync/Async)"]
    Pool["Engine Pool Manager<br/>(2-10 engines)"]
    Sessions["Session Manager<br/>(Per-user workspace)"]
    MATLAB["MATLAB Engines<br/>(Shared License)"]
    
    Agent -->|MCP Protocol| Transport
    Transport --> Auth
    Auth --> Server
    Server --> JobExec
    JobExec --> Pool
    JobExec --> Sessions
    Pool --> MATLAB
    Sessions --> MATLAB
Loading

Data Flow for Code Execution

sequenceDiagram
    participant Agent as AI Agent
    participant Server as MCP Server
    participant Executor as Job Executor
    participant Pool as Engine Pool
    participant Engine as MATLAB Engine
    
    Agent->>Server: execute_code(code='x=randn(1000,1000);')
    Server->>Executor: execute_code_impl(...)
    Executor->>Executor: Security validation
    Executor->>Pool: acquire()
    Pool->>Engine: assign engine
    Executor->>Engine: eval(code)
    alt Completes in < 30s
        Engine-->>Executor: result
        Executor->>Server: {status: completed, output: ...}
    else Exceeds 30s timeout
        Executor->>Executor: Auto-promote to async
        Executor->>Server: {status: running, job_id: abc123}
        Engine->>Engine: Continue execution in background
        Agent->>Server: get_job_status(job_id)
        Executor->>Engine: Check status
        Server-->>Agent: {status: running, progress: 45%}
    end
    Executor->>Pool: release()
Loading

Quick Start

Prerequisites

  • Python 3.10+
  • MATLAB R2022b+ with Engine API installed

Install

Windows (one-click, no admin):

git clone https://github.com/HanSur94/matlab-mcp-server-python.git
cd matlab-mcp-server-python
install.bat

macOS / Linux:

pip install matlab-mcp-python

Run

# Single-user stdio (local)
matlab-mcp

# Multi-user HTTP (remote agents)
matlab-mcp --transport streamablehttp

Connect to Claude Desktop

Edit ~/Library/Application Support/Claude/claude_desktop_config.json:

{
  "mcpServers": {
    "matlab": {
      "command": "matlab-mcp"
    }
  }
}

Generate a Bearer Token (for HTTP)

matlab-mcp --generate-token
# Output:
# MATLAB_MCP_AUTH_TOKEN=a3f9e2c1b8d4e7f6a9c2b1d8e7f6a3c9
# 
# Bash:  export MATLAB_MCP_AUTH_TOKEN='...'
# Zsh:   export MATLAB_MCP_AUTH_TOKEN='...'
# Cmd:   set MATLAB_MCP_AUTH_TOKEN=...
# PowerShell: $env:MATLAB_MCP_AUTH_TOKEN='...'

Hello World

% In Claude or your agent, ask it to execute:
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x, y, 'b-', 'LineWidth', 2);
title('sin(x)');
xlabel('x');
ylabel('sin(x)');

The server will:

  1. Execute the code in a pooled MATLAB engine
  2. Capture the plot and extract properties (axes, lines, colors, labels)
  3. Convert to interactive Plotly JSON
  4. Return an Image object that renders in the agent's UI

Tool Categories

Code Execution (3 tools)

  • execute_code — Run MATLAB code with auto-async promotion
  • check_code — Lint code via checkcode/mlint
  • get_workspace — Query workspace variables

Async Jobs (4 tools)

  • get_job_status — Poll running job progress
  • get_job_result — Retrieve completed job result
  • cancel_job — Cancel pending/running job
  • list_jobs — List all jobs in session

Discovery (3 tools)

  • list_toolboxes — Browse installed toolboxes
  • list_functions — List functions in toolbox
  • get_help — Get function help text

File Management (3 tools)

  • upload_data — Upload file to session workspace
  • delete_file — Delete file from workspace
  • list_files — List files in workspace

File Reading (3 tools)

  • read_script — Read .m script files
  • read_data — Read .mat, .csv, .json files
  • read_image — Read and display images

Admin & Monitoring (3 tools)

  • get_pool_status — Engine pool utilization
  • get_server_metrics — Comprehensive server metrics
  • get_server_health — Health status and diagnostics

Configuration

All settings use YAML + environment variables. Example config.yaml:

server:
  name: matlab-mcp-server
  transport: streamablehttp     # or 'stdio', 'sse'
  host: 127.0.0.1              # loopback safe for Windows 10 no-admin
  port: 8765
  log_level: info

pool:
  min_engines: 2
  max_engines: 10
  engine_start_timeout: 120
  health_check_interval: 60

execution:
  sync_timeout: 30              # Auto-async if > 30s
  max_execution_time: 86400
  workspace_isolation: true

security:
  blocked_functions:
    - system
    - unix
    - eval
    - assignin

sessions:
  max_sessions: 50
  session_timeout: 3600         # 1 hour idle timeout
  job_retention_seconds: 86400  # Keep job history 24h

monitoring:
  enabled: true
  database: ./data/metrics.db

Override any setting with environment variables:

export MATLAB_MCP_POOL_MAX_ENGINES=20
export MATLAB_MCP_SERVER_TRANSPORT=streamablehttp
matlab-mcp

Navigation

Page Purpose
Installation Prerequisites, MATLAB Engine setup, installation methods
Configuration Complete config.yaml reference, env var overrides
MCP-Tools-Reference All 20+ tools, parameters, example responses
Custom-Tools Expose your own .m functions as MCP tools via YAML
Examples Ready-to-run MATLAB code snippets for agents
Architecture System design, component hierarchy, data flow
Async-Jobs Long-running job lifecycle, progress reporting
Security Function blocklist, workspace isolation, upload limits
Troubleshooting Common issues: engine startup, SSE, blocked functions
FAQ Frequent questions: MATLAB versions, transports, async jobs

Features Highlight

Interactive Plotly Plots

Every MATLAB figure is auto-converted to interactive Plotly JSON:

% Agent asks for a sine wave plot
x = linspace(0, 2*pi, 200);
plot(x, sin(x), 'r-', 'LineWidth', 2);
hold on;
plot(x, cos(x), 'b--', 'LineWidth', 2);
legend('sin(x)', 'cos(x)');

Result: An interactive chart with hover tooltips, pan/zoom, and legend toggling—all without the agent writing a single JSON line.

Long-Running Async Jobs

% Agent requests a 2-hour Monte Carlo simulation
trials = 10_000_000;
count = 0;
for i = 1:trials
    x = rand(); y = rand();
    if sqrt(x^2 + y^2) <= 1
        count = count + 1;
    end
    if mod(i, 100_000) == 0
        mcp_progress(100 * i / trials, sprintf('Trial %d/%d', i, trials));
    end
end
pi_estimate = 4 * count / trials;

Server response: {status: running, job_id: xyz, progress: 2%}. Agent waits via get_job_status() polling. When done, get_job_result() returns the final answer.

Custom MCP Tools

Define your own tools in custom_tools.yaml:

custom_tools:
  - name: signal_fft
    function: signal.fft_analysis
    description: "Compute FFT of a signal"
    parameters:
      signal:
        type: array
        description: "Input signal"
      fs:
        type: number
        description: "Sampling frequency (Hz)"

Agents now have signal_fft as a native tool—no coding required.

Human-in-the-Loop Approval

Protect sensitive operations with optional human approval:

hitl:
  enabled: true
  protected_functions:
    - system
    - unix
    - copyfile
  all_execute: false

When an agent tries execute_code with a protected function or upload_data, the server asks the human for approval before proceeding.

Multi-User Sessions (SSE & HTTP)

Each agent or user gets a dedicated session with isolated workspace:

Agent A (Client 1) → Session A → Temp Dir A → Engine 1
Agent B (Client 2) → Session B → Temp Dir B → Engine 2
Agent C (Client 3) → Session A → Temp Dir A → Engine 1  (shares with A)

No cross-contamination; variables from Client 1 never leak to Client 2.


Supported Platforms

OS MATLAB Transport Install Notes
macOS (Intel/Apple Silicon) 2020b+ stdio, SSE, HTTP pip install Native Python engine
Windows 10/11 2020b+ stdio, SSE, HTTP install.bat (no admin) Loopback binding by default (avoids firewall)
Linux (Ubuntu/Debian) 2020b+ stdio, SSE, HTTP pip install Requires libhwloc, libgomp

Example Deployments

Development (Single User)

matlab-mcp --transport stdio

Uses stdio (pipes). No network. No auth. Simplest for local testing.

Team Shared Server (Multi-User)

export MATLAB_MCP_AUTH_TOKEN=$(matlab-mcp --generate-token)
matlab-mcp --transport streamablehttp --host 10.0.1.50

All team members connect via HTTP with bearer token auth. Each gets isolated workspace.

Production (Corporate Cluster)

server:
  transport: streamablehttp
  host: 127.0.0.1           # Behind reverse proxy
  port: 8765

pool:
  min_engines: 5
  max_engines: 20

security:
  blocked_functions:
    - system
    - eval
    - assignin
  max_upload_size_mb: 500

Reverse proxy (nginx) handles SSL/TLS and route external MATLAB_MCP_AUTH_TOKEN. MATLAB in container with mounted license server.


Community & Support


Happy coding! 🚀

Clone this wiki locally