How MatlabMCP Connects to a Shared MATLAB Session and Handles Missing Instances

MatlabMCP uses the MATLAB Engine API for Python to automatically discover shared MATLAB sessions via matlab.engine.find_matlab(), connects to the first available instance, and terminates immediately with exit code 1 if no shared session is detected.

MatlabMCP is a Model Context Protocol (MCP) server that enables AI assistants to execute MATLAB code by bridging Python and MATLAB through the official MATLAB Engine API. According to the jigarbhoye04/matlabmcp source code, the server implements a strict discovery-and-connect workflow in main.py that requires a pre-shared MATLAB session to function.

Discovering Shared MATLAB Sessions

When the server initializes, it immediately scans the system for shareable MATLAB instances. In main.py at line 27, the code calls matlab.engine.find_matlab(), which returns a list of session names for any MATLAB processes that have executed matlab.engine.shareEngine in their Command Window.

The discovered sessions are logged for troubleshooting purposes at line 28:

names = matlab.engine.find_matlab()
logger.info(f"Found sessions: {names}")

If the returned list contains multiple shared sessions, MatlabMCP selects only the first entry (names[0]) for the connection, ignoring subsequent instances.

Connecting to the MATLAB Engine

Upon finding at least one shared session, the server attempts to establish a live connection. Lines 36-40 in main.py extract the first session name and invoke matlab.engine.connect_matlab():

session_name = names[0]
try:
    eng = matlab.engine.connect_matlab(session_name)
    logger.info(f"Connected to MATLAB session: {session_name}")
except matlab.engine.EngineError as e:
    logger.error(f"Failed to connect: {e}", exc_info=True)
    sys.exit(1)

This produces a live engine object (eng) that the MCP server uses to execute MATLAB commands. A final safety guard at lines 48-50 ensures eng is not None, aborting the process if the connection object is invalid.

Handling Missing Shared Sessions

If matlab.engine.find_matlab() returns an empty list, MatlabMCP implements a fail-fast strategy. Lines 30-34 in main.py handle this scenario by logging a descriptive error and terminating the process:

if not names:
    logger.error(
        "No shared MATLAB sessions found. Start MATLAB and run "
        "'matlab.engine.shareEngine' before launching the MCP server."
    )
    sys.exit(1)

The server exits with status code 1, preventing any further tool execution. As documented in the repository's README.md (lines 47-52), users must manually start MATLAB and execute matlab.engine.shareEngine in the Command Window to create a shareable session before launching the MCP server.

Connection Failure Management

Beyond the no-session case, MatlabMCP handles connection exceptions that occur when connect_matlab() fails. The try-except block at lines 41-46 catches EngineError and other exceptions, logs the specific failure reason, and exits with code 1:

except Exception as e:
    logger.error(f"Failed to connect to MATLAB: {e}", exc_info=True)
    sys.exit(1)

This ensures the server does not hang or operate in a degraded state when MATLAB is unreachable despite being discoverable.

Summary

  • Automatic Discovery: MatlabMCP calls matlab.engine.find_matlab() in main.py (line 27) to scan for MATLAB instances shared via matlab.engine.shareEngine.
  • First-Session Selection: The server connects exclusively to the first session in the discovered list (names[0]) using matlab.engine.connect_matlab().
  • Fail-Fast Behavior: If no shared sessions exist, the server logs an error at lines 30-34 and exits with sys.exit(1).
  • Robust Error Handling: Connection failures trigger immediate termination with detailed logging to prevent undefined behavior.

Frequently Asked Questions

How do I prepare MATLAB for MatlabMCP connection?

Start MATLAB and execute matlab.engine.shareEngine in the Command Window. This makes the current MATLAB session discoverable by the Python engine API. Without this step, matlab.engine.find_matlab() returns an empty list and MatlabMCP will terminate immediately with exit code 1.

Can MatlabMCP connect to multiple MATLAB sessions simultaneously?

No. According to the source code in main.py (lines 36-40), MatlabMCP selects only the first session from the discovered list (names[0]) and establishes a single connection. Additional shared sessions are ignored.

What error message appears if MATLAB is not shared?

The server logs: "No shared MATLAB sessions found. Start MATLAB and run 'matlab.engine.shareEngine' before launching the MCP server." followed by an immediate exit with status code 1. This appears in the console output at lines 30-34 of main.py.

Does MatlabMCP support starting MATLAB automatically?

No. The jigarbhoye04/matlabmcp implementation requires a pre-existing shared session. It does not launch MATLAB processes automatically; it only connects to sessions explicitly shared via matlab.engine.shareEngine as documented in the README.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →