Skip to content

Troubleshooting

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

Troubleshooting

Installation Issues

MATLAB Engine Not Found

Symptom: ImportError: No module named matlab.engine or matlab.engine not found

Likely Cause: MATLAB Engine API not installed or not on Python path.

Solution:

  1. Verify MATLAB is installed (R2022b or later):

    matlab -v
  2. Install the Engine API:

    macOS/Linux:

    cd /path/to/matlab/extern/engines/python
    pip install .

    Windows:

    cd "C:\Program Files\MATLAB\R2024a\extern\engines\python"
    pip install .
  3. Verify installation:

    python -c "import matlab.engine; print('Engine API OK')"
  4. If still failing, set the MATLAB root explicitly in config.yaml:

    pool:
      matlab_root: "/Applications/MATLAB_R2024a.app"  # or your MATLAB path

Python Version Mismatch

Symptom: ModuleNotFoundError when importing matlab.engine; message mentions version mismatch

Likely Cause: MATLAB Engine API was built for a different Python version.

Solution:

  1. Check your Python version:

    python --version
  2. Check MATLAB Engine supports that version:

    • R2022b supports Python 3.8–3.11
    • R2023b supports Python 3.9–3.12
    • R2024a supports Python 3.9–3.12
  3. Reinstall Engine API or use a supported Python version:

    # Use Python 3.10 specifically
    python3.10 -m pip install /path/to/matlab/extern/engines/python

pip install Fails on Windows Without Admin

Symptom: Access is denied or ERROR: Could not install packages due to an OSError

Likely Cause: No write permission to Python installation directory.

Solution:

  1. Use the provided installer script:

    install.bat

    This script handles installation in a virtual environment without requiring admin rights.

  2. Or install to user directory:

    pip install --user matlab-mcp
  3. Verify by running the server:

    matlab-mcp --help

Runtime Issues

Server Fails to Start

Symptom: matlab-mcp command exits immediately with an error

Likely Cause: Configuration file syntax error or missing required settings.

Solution:

  1. Check configuration syntax:

    python -c "from matlab_mcp.config import load_config; load_config('config.yaml')"

    If this succeeds silently, config is valid.

  2. Enable debug logging:

    server:
      log_level: "debug"

    Or via environment:

    export MATLAB_MCP_SERVER_LOG_LEVEL=debug
    matlab-mcp
  3. Check for common config errors:

    • YAML indentation (must be 2 spaces, not tabs)
    • Missing colons after keys
    • Unquoted strings with special characters
  4. Start with minimal config:

    server:
      transport: stdio
    pool:
      min_engines: 1
      max_engines: 2

MATLAB Engine Pool Won't Initialize

Symptom: Engine pool failed to start or Timeout waiting for engine

Likely Cause: MATLAB startup is slow; engine takes longer than timeout to initialize.

Solution:

  1. Increase engine startup timeout:

    pool:
      engine_start_timeout: 300  # 5 minutes (default: 60)
  2. Check MATLAB isn't hanging:

    • Run matlab interactively and verify it starts normally
    • Check if MATLAB has license issues (popup dialogs blocking startup)
    • On network drives, MATLAB can be slow — try a local MATLAB installation
  3. Reduce pool size temporarily for testing:

    pool:
      min_engines: 0  # Start with no engines, let them initialize on demand
      max_engines: 1
  4. Check system resources:

    • Each MATLAB engine uses ~500 MB RAM
    • Ensure you have min_engines × 500 MB free RAM
    • Use --inspect mode to skip engine startup entirely for testing:
      matlab-mcp --inspect

"Max engines exceeded" Warning on macOS

Symptom: Warning: macOS concurrent engine limit may be exceeded

Explanation: MATLAB on macOS typically supports only 4 concurrent instances.

Solution:

pool:
  max_engines: 4  # Set to macOS limit

Connection Refused (HTTP/SSE)

Symptom: Agent can't connect; Connection refused or Failed to connect to http://localhost:8765

Likely Cause: Server not binding to correct address/port; firewall blocking; wrong transport selected.

Solution:

  1. Verify server is running:

    curl http://127.0.0.1:8765/health
    # Should return JSON response, not "Connection refused"
  2. Check configured port and host:

    server:
      host: "127.0.0.1"  # or 0.0.0.0 for remote access
      port: 8765
      transport: "streamablehttp"  # or "sse" for legacy agents
  3. Check firewall (remote connections):

    • Windows: Allow Python in Windows Defender Firewall
    • macOS: Allow Python in System Settings → Security & Privacy
    • Linux: sudo ufw allow 8765 or equivalent for your firewall
  4. Verify transport matches agent:

    • Claude Code: supports stdio and streamablehttp
    • Codex CLI: requires streamablehttp (SSE not supported)
    • Cursor: supports stdio and streamablehttp

Bearer Token Authentication Fails

Symptom: HTTP 401 Unauthorized or Invalid bearer token

Likely Cause: Token not set; token mismatch; header format incorrect.

Solution:

  1. Generate a token:

    matlab-mcp --generate-token
    # Output: export MATLAB_MCP_AUTH_TOKEN=abc123...
  2. Set the token in your environment:

    export MATLAB_MCP_AUTH_TOKEN="<token from --generate-token>"
  3. Restart server (server reads token at startup):

    matlab-mcp
  4. Verify token is set:

    echo $MATLAB_MCP_AUTH_TOKEN
    # Should print the 64-character hex string
  5. Check agent is sending token correctly:

    • Claude Code: Set MATLAB_MCP_AUTH_TOKEN in your shell, Claude Code will use it
    • Codex CLI: Pass --header "Authorization: Bearer $MATLAB_MCP_AUTH_TOKEN"
    • Custom client: Send header: Authorization: Bearer <token>
  6. Disable auth for testing (NOT for production):

    unset MATLAB_MCP_AUTH_TOKEN
    # Restart server — auth will be disabled

Workspace Isolation Not Working

Symptom: Code from different sessions can access the same variables; clear all affects other sessions

Likely Cause: Single-user stdio transport (workspace not isolated); or max_sessions set to 1.

Solution:

  1. Use HTTP transport for true session isolation:

    server:
      transport: "streamablehttp"  # Not "stdio"
  2. Increase max sessions:

    sessions:
      max_sessions: 10  # Allow multiple concurrent sessions
  3. Verify each agent gets its own session ID:

    • Monitor logs for session_id=... in each connection
    • Different session IDs = different workspaces

Configuration Issues

Code Execution Blocked (Security Validation)

Symptom: BlockedFunctionError: Function 'system' is blocked or similar

Explanation: The security validator blocks dangerous functions (system calls, shell escapes, etc.) by default.

Solution:

  1. Use MATLAB-native alternatives:

    Blocked Alternative
    system('dir') dir or ls command
    unix('ls') !ls or MATLAB dir
    dos('cmd') Windows batch commands won't work; use MATLAB functions
    !rm file.txt delete file.txt
    eval(code) Restructure code; eval is almost never needed in legitimate use
  2. Disable blocklist if needed (development only):

    security:
      blocked_functions_enabled: false
  3. Remove specific functions from blocklist:

    security:
      blocked_functions:
        - "unix"
        - "dos"
        # "system" removed — now allowed

File Upload Rejected

Symptom: FileUploadError or File too large when uploading data

Likely Cause: File exceeds size limit; filename has invalid characters.

Solution:

  1. Check file size:

    security:
      max_upload_size_mb: 100  # Increase if needed
  2. Check filename restrictions:

    • Only [a-zA-Z0-9._-] allowed in filenames
    • data-2024 (1).csv (space and parentheses invalid)
    • data-2024-1.csv (valid)
  3. Rename file and retry:

    # Good filenames
    training_data.csv
    model_weights_v2.mat
    config-2024-01.json

Output Truncated or Saved to File

Symptom: Result says Output saved to 'job_12345_output.txt' instead of returning inline

Explanation: Output exceeds configured inline limits.

Solution:

  1. Increase inline limits:

    output:
      max_inline_text_length: 100000    # Default: 50000
      max_inline_variables: 50000       # Default: 50000
      large_result_threshold: 50000     # Default: 10000
  2. Or accept file-based results:

    • Use list_files to find the output file
    • Use read_data to retrieve its contents in chunks
  3. Reduce output in MATLAB code:

    % Bad: prints 1M lines
    disp(repmat("x", 1, 1e6));
    
    % Good: print summary
    fprintf("Generated %d items\n", 1e6);

Plots Not Converting to Interactive Format

Symptom: No Plotly JSON returned; only static PNG image

Explanation: Plot type not supported; conversion disabled; or figure extraction failed.

Solution:

  1. Check supported plot types:

    • ✅ Line, scatter, bar, histogram, surface, heatmap, image
    • ❌ Custom graphics objects, specialized toolbox plots (signal processing, statistics)
  2. Enable Plotly conversion:

    output:
      plotly_conversion: true  # Default: true
  3. Check for MATLAB errors in figure extraction:

    • Enable debug logging and look for mcp_extract_props.m errors
    • Try a simpler plot: plot([1 2 3], [1 2 3]) to verify basic functionality
  4. Use static images as fallback:

    • Plotly conversion is optional
    • Agent can still display the PNG thumbnail

Async Job Issues

Job Stuck in "Running" State

Symptom: Job never completes; status stays running; progress stops updating

Likely Cause: MATLAB code is blocked or in infinite loop; network timeout; or MATLAB engine crashed.

Solution:

  1. Cancel the job:

    # Agent calls: cancel_job(job_id="12345")
    # Or via API
    curl -X POST http://localhost:8765/mcp \
      -H "Authorization: Bearer $MATLAB_MCP_AUTH_TOKEN" \
      -d '{"jsonrpc":"2.0","method":"cancel_job","params":{"job_id":"12345"}}'
  2. Check MATLAB code for infinite loops:

    % Bad: infinite loop
    while true
      % something
    end
    
    % Good: bounded loop with progress
    for i = 1:1000
      mcp_progress(__mcp_job_id__, i/1000*100);
      % work
    end
  3. Increase timeout if code is legitimately long-running:

    execution:
      sync_timeout: 30       # Code > 30s becomes async
      max_execution_time: 86400  # 24h hard limit
  4. Check job was actually created:

    # Agent calls: list_jobs()
    # Should return the job in the list

Progress Not Updating

Symptom: mcp_progress() calls do not appear to update job status

Likely Cause: Progress files not being written to correct location; server not reading them.

Solution:

  1. Verify progress file location:

    • Server watches ${MCP_TEMP_DIR}/${job_id}.progress for JSON files
    • Ensure MATLAB code writes to that path:
      mcp_progress(__mcp_job_id__, 50, "halfway done");
      % Internally writes to: $MCP_TEMP_DIR/job_uuid.progress
  2. Check temp directory permissions:

    ls -la $MATLAB_MCP_TEMP_DIR  # Verify writable
  3. Enable debug logging to see progress file activity:

    server:
      log_level: "debug"

Monitoring and Debugging

Enable Debug Logging

For detailed server operation logs:

server:
  log_level: "debug"
  log_file: "./logs/server.log"

Or via environment:

export MATLAB_MCP_SERVER_LOG_LEVEL=debug
matlab-mcp 2>&1 | tee server.log

Log levels:

  • debug: Detailed info about every request, session, and job
  • info: Normal operation (default)
  • warning: Potential issues
  • error: Failures requiring attention

Access the Health Check Endpoint

Check server status (no auth required):

curl http://127.0.0.1:8765/health | python -m json.tool

Response includes:

  • status: healthy, degraded, or unhealthy
  • uptime_seconds: How long server has been running
  • engine_pool: Count of available/busy/total engines
  • active_sessions: Number of current client sessions
  • error_rate: Errors per minute

View Monitoring Dashboard

Open in browser:

http://127.0.0.1:8766/dashboard

(Port 8766 is monitoring dashboard; MCP server is on 8765)

Provides:

  • Real-time gauge charts (engine utilization, job count, error rate)
  • Time-series history (last 1 hour, 24 hours, 7 days)
  • Event log table (recent jobs, errors, cancelations)

Collect Diagnostic Information for Bug Reports

Run the diagnostic command:

matlab-mcp --diagnose

Or manually collect:

# Server version and config
matlab-mcp --version
python -c "from matlab_mcp.config import load_config; import json; print(json.dumps(load_config('config.yaml'), default=str, indent=2))" > config_dump.json

# System info
python --version
pip list | grep -E "matlab|fastmcp|pydantic"
uname -a  # or `systeminfo` on Windows

# Recent logs
tail -n 100 ./logs/server.log > server_logs.txt

# Health status
curl http://127.0.0.1:8765/health > health.json

# Compress for sharing
tar czf diagnostic_bundle.tar.gz config_dump.json server_logs.txt health.json

When reporting issues, include:

  • python --version and pip list output
  • MATLAB version (matlab -v)
  • Your config.yaml (redact any tokens)
  • Full error message and server logs (last 100 lines)
  • Platform (Windows/macOS/Linux, version)
  • What command/agent was running when it failed

Still Stuck?

Check Known Issues

graph TD
    A["Problem?"] -->|Engine won't start| B["Engine Issues"]
    A -->|Can't connect| C["Connection Issues"]
    A -->|Code blocked| D["Security"]
    A -->|Output wrong| E["Output Format"]
    A -->|Job stuck| F["Async/Job Issues"]
    
    B --> B1["MATLAB not installed?"]
    B --> B2["Engine API not installed?"]
    B --> B3["MATLAB slow to start?"]
    
    C --> C1["Wrong transport?"]
    C --> C2["Firewall blocking?"]
    C --> C3["Wrong auth token?"]
    
    D --> D1["Use MATLAB alternatives"]
    D --> D2["Check allowed functions list"]
    
    E --> E1["Output > size limit?"]
    E --> E2["Plotly conversion disabled?"]
    
    F --> F1["Use cancel_job"]
    F --> F2["Check for infinite loop"]
Loading

Community Resources


Report a Bug

Include in your bug report:

  1. What you were trying to do
  2. Exact error message (full traceback)
  3. Your configuration (redacted)
  4. Server logs (last 50 lines with log_level: debug)
  5. Output of matlab-mcp --diagnose (if available)
  6. Platform, Python version, MATLAB version

Create an issue on GitHub:

Title: [Transport] Brief description

Description:
- **What I did:** Steps to reproduce
- **What I expected:** Expected behavior
- **What happened:** Actual error
- **Diagnostic info:** Config, logs, versions (see "Collect Diagnostic Information" above)

Clone this wiki locally