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

> Learn how MatlabMCP connects to shared MATLAB sessions using the MATLAB Engine API and handles missing instances by exiting cleanly with code 1.

- Repository: [Jigar Bhoye/matlabmcp](https://github.com/jigarbhoye04/matlabmcp)
- Tags: internals
- Published: 2026-03-04

---

**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`](https://github.com/jigarbhoye04/matlabmcp/blob/main/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`](https://github.com/jigarbhoye04/matlabmcp/blob/main/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:

```python
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`](https://github.com/jigarbhoye04/matlabmcp/blob/main/main.py) extract the first session name and invoke `matlab.engine.connect_matlab()`:

```python
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`](https://github.com/jigarbhoye04/matlabmcp/blob/main/main.py) handle this scenario by logging a descriptive error and terminating the process:

```python
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`](https://github.com/jigarbhoye04/matlabmcp/blob/main/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:

```python
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`](https://github.com/jigarbhoye04/matlabmcp/blob/main/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`](https://github.com/jigarbhoye04/matlabmcp/blob/main/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`](https://github.com/jigarbhoye04/matlabmcp/blob/main/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.