Skip to content

Troubleshooting

github-actions[bot] edited this page Mar 22, 2026 · 20 revisions
# Troubleshooting

## MATLAB Engine Won't Start

**Symptom:** `Engine start timeout` or `matlab.engine not found`

**Solutions:**

1. **Verify MATLAB Engine API is installed:**
   ```bash
   python -c "import matlab.engine; print('OK')"
  1. Install the Engine API:

    cd /Applications/MATLAB_R2024a.app/extern/engines/python  # macOS
    # cd "C:\Program Files\MATLAB\R2024a\extern\engines\python"  # Windows
    pip install .
  2. Check MATLAB version: Must be R2022b or later.

  3. Check MATLAB is on PATH or set matlab_root in config:

    pool:
      matlab_root: "/Applications/MATLAB_R2024a.app"  # macOS
      # matlab_root: "C:\\Program Files\\MATLAB\\R2024a"  # Windows
  4. Increase engine start timeout: If MATLAB is slow to start:

    pool:
      engine_start_timeout: 300  # 5 minutes
  5. Check engine logs: Set log level to debug to see detailed startup errors:

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

Pool Startup Problems

Symptom: MinEngines failed to initialize or engines not starting on server launch

Solutions:

  1. Check minimum engines setting: Ensure min_engines is achievable on your system:

    pool:
      min_engines: 2  # 4 or more on macOS may exceed platform limits
      max_engines: 10
  2. Verify MATLAB license availability: Multiple concurrent MATLAB instances require sufficient licenses:

    # macOS: typical limit is ~4 concurrent engines
    # Windows: limit depends on your license agreement
  3. Check disk space: MATLAB engine startup requires temporary files. Ensure /tmp (Unix) or %TEMP% (Windows) has space.

  4. Gradual startup: The pool warms up engines over time if initial startup fails:

    pool:
      proactive_warmup_threshold: 0.8  # starts new engine if utilization > 80%

Engine Connection Failures

Symptom: Failed to connect to MATLAB engine or Engine died unexpectedly

Solutions:

  1. Check engine health: Monitor engine status:

    # Call get_pool_status to see available/busy/max engines
  2. Enable health checks: Ensure health monitoring is active:

    pool:
      health_check_interval: 60  # ping engines every 60 seconds
  3. Check for workspace corruption: Reset the workspace:

    execution:
      workspace_isolation: true  # isolate each job's workspace
  4. Increase queue size if backed up:

    pool:
      queue_max_size: 50  # increase if jobs are being rejected

Connection Refused (SSE)

Symptom: Client can't connect to http://localhost:8765/sse

Solutions:

  1. Check the server is running:

    matlab-mcp --transport sse
  2. Check port is available: Default is 8765

    # macOS/Linux
    lsof -i :8765
    # Windows
    netstat -ano | findstr :8765
  3. Check host binding: Default is 0.0.0.0 for all interfaces

    server:
      host: "0.0.0.0"  # all interfaces
      port: 8765
  4. Firewall: Ensure port 8765 (and 8766 for monitoring) are open:

    # macOS example
    sudo pfctl -f /etc/pf.conf  # reload firewall rules
  5. Docker networking: See Docker Networking Issues section

Docker Networking Issues

Symptom: Container runs but can't connect from host, or MATLAB engine won't start in Docker

Solutions:

  1. Ensure MATLAB is properly mounted:

    docker run -p 8765:8765 -p 8766:8766 \
      -v /path/to/MATLAB:/opt/matlab:ro \
      -e MATLAB_MCP_POOL_MATLAB_ROOT=/opt/matlab \
      matlab-mcp --transport sse
  2. Check MATLAB path in container:

    docker exec <container_id> ls -la /opt/matlab/bin/matlab
  3. Use docker-compose: Simplifies environment setup:

    # Edit docker-compose.yml, then:
    docker compose up
  4. Port mapping: Ensure both SSE (8765) and monitoring (8766) ports are mapped:

    docker run -p 8765:8765 -p 8766:8766 matlab-mcp
  5. Volume permissions: MATLAB needs to write temp files:

    # Add temp directory volume
    -v /tmp/matlab-temp:/tmp:rw \
    -e MATLAB_MCP_EXECUTION_TEMP_DIR=/tmp/matlab-temp
  6. Network mode: For host access, use host network on Linux:

    docker run --network host matlab-mcp --transport sse

Timeout Tuning

Symptom: Fast jobs timeout, or slow jobs hang indefinitely

Solutions:

  1. Sync timeout (promotion to async):

    execution:
      sync_timeout: 30  # seconds before returning job ID instead of blocking

    Increase for slower machines, or if you want fast jobs to stay synchronous:

    export MATLAB_MCP_EXECUTION_SYNC_TIMEOUT=60
  2. Execution hard limit:

    execution:
      max_execution_time: 86400  # 24 hours

    Safety limit to prevent jobs from running forever:

    export MATLAB_MCP_EXECUTION_MAX_EXECUTION_TIME=3600
  3. Engine startup timeout:

    pool:
      engine_start_timeout: 120  # seconds to wait for MATLAB process

    Increase on slow systems:

    export MATLAB_MCP_POOL_ENGINE_START_TIMEOUT=300
  4. Scale-down idle timeout:

    pool:
      scale_down_idle_timeout: 900  # 15 min before shutting down idle engines

    Increase to keep engines warm:

    export MATLAB_MCP_POOL_SCALE_DOWN_IDLE_TIMEOUT=3600
  5. Drain timeout during shutdown:

    server:
      drain_timeout_seconds: 300  # wait for running jobs during graceful shutdown

Logging Configuration

Enable detailed logging for troubleshooting:

Basic Debug Logging

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

Or via environment variable:

export MATLAB_MCP_SERVER_LOG_LEVEL=debug
matlab-mcp

Log Levels

  • debug: Everything — engine startup, job queuing, workspace state
  • info: Normal operations, job completion, warnings
  • warning: Potential issues (high utilization, slow responses)
  • error: Failures and exceptions

Check Logs

# View server log
tail -f ./logs/server.log

# Filter for errors
grep ERROR ./logs/server.log

# Filter for a specific job
grep <job_id> ./logs/server.log

Docker Logging

# Stream container logs
docker logs -f <container_id>

# View past logs
docker logs <container_id> | tail -100

Enable Debug Logging

Step 1: Update config.yaml:

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

Step 2: Or set environment variable:

export MATLAB_MCP_SERVER_LOG_LEVEL=debug

Step 3: Restart the server:

matlab-mcp --transport sse

Step 4: Check logs:

tail -f ./logs/server.log

Debug logs will show:

  • Engine startup/shutdown
  • Job queuing and dispatch
  • Workspace state changes
  • Code execution details
  • Plot conversion steps
  • Network traffic (SSE)

"Max engines exceeded" on macOS

Symptom: Warning about max engines on macOS

Explanation: MATLAB on macOS has a practical limit of ~4 concurrent engine instances. The server warns but respects your configured max_engines.

Solution: Set max_engines: 4 on macOS:

pool:
  max_engines: 4

Blocked Function Error

Symptom: BlockedFunctionError: Function 'system' is blocked

Explanation: The security validator blocks dangerous functions by default to prevent unintended system access.

Solutions:

  1. Use MATLAB-native alternatives instead of system():

    • File operations: dir, mkdir, copyfile, movefile
    • Environment: getenv, setenv
    • Command execution: Use MATLAB functions instead
  2. Disable blocklist (not recommended for shared servers):

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

    security:
      blocked_functions:
        - "unix"
        - "dos"
        # system removed from list
  4. Verify code before executing: Use check_code tool first:

    # Checks for blocked functions and best practices

Job Stuck in "Running" State

Symptom: Job never completes, progress stops updating

Solutions:

  1. Check job status: Call get_job_status with the job ID to see current progress and state.

  2. Cancel the job: Call cancel_job with the job ID to force termination.

  3. Check max execution time:

    execution:
      max_execution_time: 86400  # 24h hard limit

    Jobs exceeding this are forcibly terminated.

  4. Check MATLAB code: Is there an infinite loop? Add progress reporting to debug:

    for i = 1:n
        % ... compute ...
        mcp_progress(__mcp_job_id__, i/n*100, sprintf('Iteration %d/%d', i, n));
    end
  5. Check for deadlock: If multiple jobs are waiting for the same resource, they may hang. Review code for synchronization issues.

Plotly Conversion Failed

Symptom: No interactive plot returned, only static PNG

Explanation: The Plotly converter (mcp_extract_props.m) supports common plot types. Some complex or custom plot types may not convert. The server always generates a static PNG fallback.

Solutions:

  1. Check supported plot types:

    • line, scatter, bar, area, histogram
    • surface, image
    • subplots (subplot, tiledlayout)
    • multiple axes
  2. Simplify the plot: Complex multi-axis or custom graphics objects may not convert. Try:

    % Instead of complex custom rendering:
    plot(x, y);  % basic plots convert reliably
  3. Static fallback is always available: Even if Plotly fails, a PNG image is returned.

  4. Disable Plotly conversion (fall back to static only):

    output:
      plotly_conversion: false
  5. Check debug logs for Plotly conversion errors:

    export MATLAB_MCP_SERVER_LOG_LEVEL=debug
    grep -i plotly ./logs/server.log

Large Result Truncated

Symptom: Output is cut off or saved to file instead of returned inline

Explanation: Results exceeding max_inline_text_length (50,000 chars) or large_result_threshold (10,000 elements) are saved to file to avoid overloading the agent.

Solutions:

  1. Increase limits:

    output:
      max_inline_text_length: 100000   # text output
      large_result_threshold: 50000    # matrix/table elements
  2. Use file API to access full results:

    # Agent calls:
    list_files  # find the result file
    read_data   # read with format: "raw" for full output
  3. Summarize in MATLAB:

    % Instead of returning huge matrix, compute statistics:
    summary_stats = struct('mean', mean(data), 'std', std(data), ...
                           'min', min(data), 'max', max(data));
    disp(summary_stats);

Workspace Isolation and Persistence

Symptom: Variables from one job appear in another, or workspace clears unexpectedly

Solutions:

  1. Enable workspace isolation (default):

    execution:
      workspace_isolation: true  # each job gets clean workspace
  2. Persist workspace between jobs: Disable isolation for the same session:

    execution:
      workspace_isolation: false

    Note: This is riskier in multi-user environments.

  3. Pin session to engine for persistent workspace:

    execution:
      engine_affinity: true  # same session always uses same engine

Code Checker Issues

Symptom: check_code returns unexpected warnings, or won't run

Solutions:

  1. Ensure code checker is enabled:

    code_checker:
      enabled: true
  2. Auto-check before execution:

    code_checker:
      auto_check_before_execute: true  # runs checks before execute_code
  3. Filter severity levels:

    code_checker:
      severity_levels: ["error", "warning"]  # omit "info" or "fix" if noisy
  4. Suppress specific warnings in your MATLAB code:

    %#ok<NUSED>  % suppress "variable unused" warnings
    %#ok<NASGU>  % suppress "assigned but never used"

Pool Affinity and Workspace Persistence

Symptom: Workspace variables are lost between jobs, or you need persistent state

Solutions:

  1. Enable engine affinity:

    execution:
      engine_affinity: true  # same session always gets same engine

    This ensures a session sticks to one engine, preserving workspace.

  2. Disable workspace isolation:

    execution:
      workspace_isolation: false  # workspace persists across jobs

    Combined with affinity, this gives a stateful MATLAB instance.

  3. Use startup commands to initialize workspace on every engine:

    workspace:
      startup_commands:
        - "addpath('/shared/custom_libs')"
        - "format long"

Session Timeout and Cleanup

Symptom: Session disconnects unexpectedly, or old sessions linger

Solutions:

  1. Check session timeout:

    sessions:
      session_timeout: 3600  # seconds of inactivity before cleanup
  2. Job retention:

    sessions:
      job_retention_seconds: 86400  # how long to keep completed job metadata
  3. Temp directory cleanup:

    execution:
      temp_cleanup_on_disconnect: true  # clean session temp files on disconnect
  4. Check max sessions limit:

    sessions:
      max_sessions: 50  # reject new sessions if limit reached

Monitoring and Health Checks

Symptom: Server appears healthy but jobs fail, or high latency

Solutions:

  1. Get pool status: Call get_pool_status to see available/busy/max engines.

  2. Get server health: Call get_server_health to see detailed health status (healthy/degraded/unhealthy).

  3. Get server metrics: Call get_server_metrics for comprehensive pool, job, session, and system stats.

  4. Access monitoring dashboard:

    monitoring:
      dashboard_enabled: true
      http_port: 8766  # access at http://localhost:8766
  5. Check error log: Call get_error_log to see recent errors and notable events.

Custom Tools Not Appearing

Symptom: Custom tools from custom_tools.yaml don't appear in tool list

Solutions:

  1. Check config path:

    custom_tools:
      config_file: "./custom_tools.yaml"

    Ensure file exists relative to working directory or use absolute path.

  2. Validate YAML syntax:

    python -c "import yaml; yaml.safe_load(open('custom_tools.yaml'))"
  3. Check function paths:

    % Verify MATLAB function exists:
    which mylib.analyze_signal
  4. Add to startup paths:

    workspace:
      default_paths:
        - "/path/to/mylib"
  5. Enable debug logging to see tool loading:

    export MATLAB_MCP_SERVER_LOG_LEVEL=debug
    grep -i custom ./logs/server.log

High Memory Usage

Symptom: Server memory grows over time, or crashes with out-of-memory

Solutions:

  1. Monitor metrics: Call get_server_metrics to see memory usage trends.

  2. Scale down idle engines:

    pool:
      scale_down_idle_timeout: 900  # shut down idle engines after 15 min
      min_engines: 2               # keep minimum running
  3. Reduce max engines:

    pool:
      max_engines: 6  # fewer concurrent instances = less memory
  4. Enable temp cleanup:

    execution:
      temp_cleanup_on_disconnect: true
  5. Check for memory leaks in MATLAB code: Profile your code:

    memory  % check memory usage

Clone this wiki locally