Skip to content
github-actions[bot] edited this page Mar 23, 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, search functions, fetch help documentation
  • Check code quality — run static linting (checkcode/mlint) before execution
  • Get interactive plots — MATLAB figures auto-converted to interactive Plotly JSON
  • Manage files — upload data, read scripts/images/data files, manage session storage
  • Use custom libraries — expose your .m files and MEX functions as first-class MCP tools
  • Monitor health — real-time server metrics, engine pool status, error logs
  • Isolate sessions — per-user workspaces with automatic cleanup

Supported Platforms

Platform MATLAB Version Python Status
macOS (Intel/Apple Silicon) 2020b+ 3.10–3.12 ✅ Supported
Windows 10/11 2020b+ 3.10–3.12 ✅ Supported
Linux 2020b+ (requires Engine API) 3.10–3.12 ⚠️ Limited support

Key Features & Capabilities

  • Hybrid sync/async execution — Completes fast operations immediately; promotes long-running jobs to background tasks
  • Progress reporting — Track job progress via the mcp_progress() helper function
  • Engine pool management — Auto-scales engines from min_engines to max_engines based on demand
  • Security by default — Function blocklist, workspace isolation, filename sanitization, upload limits
  • Multi-user SSE transport — Shared server behind reverse proxy with per-session isolation
  • Monitoring dashboard — Real-time metrics, performance graphs, event logs
  • Custom tools — Define MATLAB functions in YAML; they become MCP tools instantly
  • Rich output formatting — Automatic Plotly conversion, inline images, variable summaries, error handling
  • Toolbox filtering — Control which toolboxes agents can discover and use

Quick Start – Install & Hello World

1. Prerequisites

  • MATLAB 2020b or later installed on your system
  • Python 3.10+ (3.12 recommended)
  • MATLAB Engine API for Python installed (see Installation)

2. Install Server

pip install matlab-mcp-python

3. Run Server

matlab-mcp --config config.yaml

4. Hello World Code

% Execute this through any MCP client:
x = 1:10;
y = sin(x);
plot(x, y);
disp('Hello from MATLAB via MCP!')

Result:

Hello from MATLAB via MCP!

ans =

    1.0000    0.8415    0.9093   …

Figures are auto-converted to interactive Plotly JSON and embedded in the response.


Architecture at a Glance

graph LR
    A["AI Agent<br/>(Claude, Cursor, etc.)"]
    B["MCP Server<br/>(Python FastMCP)"]
    C["Engine Pool<br/>(2–N MATLAB engines)"]
    D["MATLAB<br/>(R2020b+)"]
    E["Job Tracker<br/>(persistent state)"]
    F["Session Manager<br/>(temp directories)"]
    G["Monitoring<br/>(metrics, health)"]
    
    A -->|"MCP Protocol<br/>stdio or SSE"| B
    B -->|"Acquire/release<br/>execute code"| C
    C -->|"eval(code)"| D
    B -->|"Create/track<br/>jobs"| E
    B -->|"Isolate<br/>workspaces"| F
    B -->|"Collect<br/>metrics"| G
    
    style A fill:#e1f5ff
    style B fill:#fff3e0
    style C fill:#f3e5f5
    style D fill:#e8f5e9
    style E fill:#fce4ec
    style F fill:#f1f8e9
    style G fill:#ede7f6
Loading

Key Components

  • MCP Server — Exposes 20+ tools (code execution, discovery, files, monitoring, jobs)
  • Engine Pool Manager — Starts engines on-demand, maintains min/max bounds, health checks, auto-scales
  • Job Executor — Runs code sync (blocks until done) or async (background task if timeout exceeded)
  • Session Manager — Per-user temp directories, activity tracking, automatic expiry
  • Security Validator — Blocklist checker, workspace isolation, filename sanitization
  • Result Formatter — Converts raw MATLAB output to structured MCP responses, handles Plotly conversion
  • Monitoring — Collector accumulates metrics; dashboard shows real-time pool status, job throughput, errors

For detailed architecture including data flow diagrams, see Architecture.


The 20 Built-in MCP Tools

Code Execution (3 tools)

Tool Purpose
execute_code Run MATLAB code (sync or async promotion)
check_code Lint code with checkcode/mlint
get_workspace List variables via whos

Async Job Management (4 tools)

Tool Purpose
get_job_status Poll job progress (includes .progress file if available)
get_job_result Retrieve full result of completed job
cancel_job Cancel pending/running job
list_jobs List all jobs for the session

Discovery (3 tools)

Tool Purpose
list_toolboxes Browse available toolboxes (filtered by config)
list_functions Show functions in a toolbox
get_help Fetch MATLAB help documentation

File Management (3 tools)

Tool Purpose
upload_data Upload base64 file to session temp dir
delete_file Remove file from temp dir
list_files Enumerate temp directory contents

File Reading (3 tools)

Tool Purpose
read_script Read .m file as text
read_data Read data file (.mat, .csv, .json, .xlsx, etc.)
read_image Read image file (returns inline MCP Image)

Admin & Monitoring (4 tools)

Tool Purpose
get_pool_status Engine pool availability (total, busy, available, max)
get_server_metrics Comprehensive snapshot (pool, jobs, sessions, system)
get_server_health Health status with issue detection (healthy/degraded/unhealthy)
get_error_log Recent error events with filtering

Plus: Any number of custom tools you define in custom_tools.yaml — your .m functions become MCP tools instantly.

For full parameter reference, see MCP Tools Reference.


Navigation

Getting Started

  • Installation — Prerequisites, MATLAB Engine API setup, server installation, agent integration (Claude Desktop, Code, Cursor, Docker)

Configuration & Customization

  • Configuration — Complete YAML reference (server, pool, execution, security, custom tools, monitoring, output formatting)
  • Custom Tools — How to expose your own .m functions as first-class MCP tools via YAML

Deployment & Architecture

  • Architecture — System design, component responsibilities, data flow (sync/async paths), engine pool lifecycle
  • Examples — Ready-to-run MATLAB code samples (basic calculations, plotting, signal processing, Monte Carlo, file I/O)

Advanced Topics

  • Async Jobs — Long-running job lifecycle, timeout promotion, progress reporting with mcp_progress(), polling patterns
  • Security — Function blocklist with smart scanning, workspace isolation, upload protection, SSE security with reverse proxy, recommendations by scenario

Help & Troubleshooting

  • FAQ — Frequently asked questions (setup, usage, performance, security, development)
  • Troubleshooting — Common issues (engine startup, MATLAB limits, SSE connection, blocked functions, stuck jobs, Plotly failures, truncated output, debug logging)

Example: Execute Code → Get Plotly Figure

# Using Claude or another AI agent:
tools = [execute_code, read_image, ...]

# Agent runs:
response = execute_code(code="""
    t = linspace(0, 2*pi, 100);
    y1 = sin(t);
    y2 = cos(t);
    plot(t, y1, 'b-', t, y2, 'r--');
    legend('sin(t)', 'cos(t)');
    grid on;
""")

# Returns:
{
  "status": "completed",
  "job_id": "...",
  "text": "ans = Line with properties:\n  Color: [0 0 1] ...",
  "figures": [
    {
      "type": "plotly",
      "data": [
        {"type": "scatter", "x": [...], "y": [...], "name": "sin(t)", ...},
        {"type": "scatter", "x": [...], "y": [...], "name": "cos(t)", ...}
      ],
      "layout": {"title": "", "xaxis": {...}, "yaxis": {...}}
    }
  ]
}

The agent (or UI) can render this Plotly JSON as an interactive chart — users can zoom, pan, toggle traces, export to PNG.


Performance & Limits

Setting Default Configurable
Min engines (startup) 2 Yes (pool.min_engines)
Max engines (scaling) 10 Yes (pool.max_engines)
Sync execution timeout 30s Yes (execution.sync_timeout)
Max execution time 24h Yes (execution.max_execution_time)
Session timeout 1h Yes (sessions.session_timeout)
Max upload size 100MB Yes (security.max_upload_size_mb)
Job history retention 24h Yes (sessions.job_retention_seconds)

Getting Help

  • 📖 GitHub README — Project overview
  • 🐛 GitHub Issues — Report bugs or request features
  • 💬 MCP Discord — Community chat
  • 📚 Wiki (this site) — Comprehensive documentation

What's Next?

  1. New user? Start with Installation to get the server running
  2. Ready to configure? See Configuration for all options
  3. Want examples? Check Examples for ready-to-run code
  4. Deploying to production? Read Security and Architecture
  5. Stuck? Try Troubleshooting or FAQ

Version: 1.5.0 | Status: Production-ready | License: MIT

Clone this wiki locally