# How to Manage Connection and Reconnection in Unity MCP: A Complete Guide

> Master Unity MCP connection and reconnection with automatic retries, UDP discovery, and lifecycle management. Explore our complete guide for robust networking.

- Repository: [いすず/unitymcp](https://github.com/isuzu-shiranui/unitymcp)
- Tags: how-to-guide
- Published: 2026-03-04

---

**Unity MCP maintains persistent TCP connections through automatic retry logic with exponential backoff, UDP discovery, and lifecycle management handled by [`McpServer.cs`](https://github.com/isuzu-shiranui/unitymcp/blob/main/McpServer.cs) and [`McpEditorInitializer.cs`](https://github.com/isuzu-shiranui/unitymcp/blob/main/McpEditorInitializer.cs).**

Managing connection and reconnection in Unity MCP is essential for maintaining stable communication between the Unity Editor and external MCP servers. The `isuzu-shiranui/unitymcp` repository implements a robust connection manager that handles network interruptions, editor state changes, and dynamic server discovery automatically.

## Core Architecture for Connection Management

The connection system relies on two primary components that work together to maintain the TCP link.

### McpServer.cs - The TCP Client Engine

Located at [`jp.shiranui-isuzu.unity-mcp/Editor/Core/McpServer.cs`](https://github.com/isuzu-shiranui/unitymcp/blob/main/jp.shiranui-isuzu.unity-mcp/Editor/Core/McpServer.cs), this class implements the core TCP client functionality. It manages the background thread, connection state machine, and reconnection logic. The `McpServer` class exposes `Connected` and `Disconnected` events that other editor systems can subscribe to for reacting to connection state changes.

### McpEditorInitializer.cs - Lifecycle Orchestration

The [`McpEditorInitializer.cs`](https://github.com/isuzu-shiranui/unitymcp/blob/main/McpEditorInitializer.cs) file in the same directory acts as the entry point. When Unity starts, this initializer creates the `McpServer` instance, registers it with the global `McpServiceManager`, discovers available command handlers, and optionally calls `server.Start()` if `McpSettings.autoStartOnLaunch` is enabled.

## The Connection Lifecycle

Understanding how Unity MCP establishes and maintains connections requires examining the sequence from initialization to data processing.

### Automatic Startup and Initialization

When the editor loads, `McpEditorInitializer` performs the following steps:

1. Instantiates `McpServer` with configuration from `McpSettings`
2. Registers the server with `McpServiceManager.Instance.RegisterService(server)`
3. Discovers and registers command handlers via reflection
4. Invokes `server.Start()` if automatic startup is configured

The `Start()` method launches a background thread (`clientThread`) that executes the `RunClient` method, ensuring the main Unity thread remains unblocked.

### The Main Client Loop (RunClient)

The `RunClient` method in [`McpServer.cs`](https://github.com/isuzu-shiranui/unitymcp/blob/main/McpServer.cs) (lines 391-405) implements the main execution loop:

```csharp
// Simplified representation of the RunClient loop
while (isRunning)
{
    if (!IsConnected && !isConnecting)
    {
        TryConnect();
    }
    else if (IsConnected)
    {
        ProcessIncomingData();
    }
    
    Thread.Sleep(10); // Prevents busy-waiting
}

```

This loop checks the connection state every 10 milliseconds. If disconnected and not currently attempting connection, it triggers `TryConnect()`. When connected, it processes incoming MCP messages.

### Connection Attempts with TryConnect

The `TryConnect()` method encapsulates the connection logic including throttling, timeout handling, and state management.

## Reconnection Strategy and Exponential Backoff

Unity MCP implements intelligent reconnection logic to handle temporary network failures without overwhelming the system or network.

### Backoff Mechanism Implementation

When a connection attempt fails, the system enters a reconnection state controlled by the `isReconnecting` flag. The `TryConnect` method checks the elapsed time since `lastConnectionAttempt` against `currentReconnectDelay`. If insufficient time has passed, the method returns early, effectively throttling connection attempts.

The delay intervals follow an exponential backoff pattern:

- **Initial delay**: Defined by `reconnectDelay` (default typically 1-2 seconds)
- **Maximum delay**: Capped by `maxReconnectDelay` (prevents indefinite waiting)
- **Multiplier**: Doubles after each failure until reaching the maximum

### Success and Failure Handling

**On successful connection:**

1. Resets `currentReconnectDelay` to the base `reconnectDelay`
2. Clears `isReconnecting` flag
3. Records `connectedSince` timestamp
4. Sends registration payload to the MCP server
5. Raises `Connected` event on the main thread via Unity's synchronization context

**On connection failure:**

1. Closes the `TcpClient` instance
2. Sets `isReconnecting = true`
3. Doubles `currentReconnectDelay` (up to `maxReconnectDelay`)
4. Updates `lastConnectionAttempt` timestamp

This ensures that transient failures result in brief waits, while persistent failures gradually increase the retry interval to conserve resources.

## UDP Discovery for Dynamic Host Resolution

Unity MCP supports automatic server discovery via UDP broadcasts, eliminating the need for manual host configuration in dynamic environments.

When enabled via `McpSettings.useUdpDiscovery`, the `StartUdpListener` method opens a `UdpClient` on a specific port. This listener runs asynchronously, waiting for broadcast packets from the TypeScript MCP server.

Upon receiving a `"mcp_server_announce"` packet, the handler:
1. Parses the host and port from the payload
2. Updates the `host` and `port` fields in `McpServer`
3. Immediately invokes `TryConnect()` on the main thread to establish the TCP connection

This mechanism allows the Unity Editor to automatically connect to MCP servers running on the local network without manual IP configuration.

## Handling Play Mode Changes

Unity MCP must maintain connection stability across editor state transitions, particularly when entering or exiting play mode.

The `McpEditorInitializer` subscribes to `EditorApplication.playModeStateChanged`. When the editor transitions between edit mode and play mode:

1. **Stop Phase**: The current `McpServer` instance stops gracefully, closing the TCP connection and terminating the background thread
2. **Start Phase**: A fresh `McpServer` instance initializes and begins the connection cycle anew

This restart ensures that the MCP connection state aligns with the new play mode session, preventing stale data or connection handles from persisting across domain reloads.

## Practical Implementation Examples

The following code snippets demonstrate common connection management tasks using the Unity MCP API.

### Manual Server Startup

```csharp
// Manually start the MCP server from an editor window or tool
var server = new UnityMCP.Editor.Core.McpServer();
UnityMCP.Editor.Core.McpServiceManager.Instance.RegisterService(server);
server.Start();   // Launches background thread and begins connection attempts

```

### Subscribing to Connection Events

```csharp
// React to connection state changes in your editor tools
server.Connected += (_, __) => Debug.Log("MCP connected successfully");
server.Disconnected += (_, __) => Debug.LogWarning("MCP disconnected - will retry automatically");

```

### Forcing Reconnection

```csharp
// Useful after network changes or configuration updates
if (server.IsRunning)
{
    server.Stop();      // Cleanly close current socket
    server.Start();     // Trigger fresh TryConnect cycle
}

```

### Disabling UDP Discovery

```csharp
// Use static host configuration instead of automatic discovery
var settings = UnityMCP.Editor.Settings.McpSettings.instance;
settings.useUdpDiscovery = false;   // Must manually set host/port in McpSettings

```

## Key Configuration Files and Settings

Understanding the file structure helps when debugging connection issues or extending the system.

| File | Role |
|------|------|
| **[`Editor/Core/McpServer.cs`](https://github.com/isuzu-shiranui/unitymcp/blob/main/Editor/Core/McpServer.cs)** | Implements the TCP client, connection/reconnection logic, UDP discovery, and event handling. |
| **[`Editor/Core/McpEditorInitializer.cs`](https://github.com/isuzu-shiranui/unitymcp/blob/main/Editor/Core/McpEditorInitializer.cs)** | Boots the MCP system on Unity start, registers services, and restarts connections on play-mode changes. |
| **[`Editor/Core/McpServiceManager.cs`](https://github.com/isuzu-shiranui/unitymcp/blob/main/Editor/Core/McpServiceManager.cs)** | Simple DI container storing the singleton `McpServer` instance for global access. |
| **[`Editor/Settings/McpSettings.cs`](https://github.com/isuzu-shiranui/unitymcp/blob/main/Editor/Settings/McpSettings.cs)** | Holds configurable options including host, port, `useUdpDiscovery`, `autoStartOnLaunch`, and back-off timings. |

## Summary

Unity MCP provides a robust, self-healing connection system that requires minimal manual intervention:

- **Automatic management** occurs through [`McpServer.cs`](https://github.com/isuzu-shiranui/unitymcp/blob/main/McpServer.cs), which runs a background thread checking connection health every 10 milliseconds.
- **Exponential backoff** prevents connection spam, starting with short delays and gradually increasing to a configurable maximum.
- **UDP discovery** enables zero-configuration networking by automatically detecting MCP servers on the local network.
- **Play-mode resilience** ensures connections restart cleanly when entering or exiting play mode, preventing domain reload issues.
- **Global access** via `McpServiceManager` allows any editor tool to monitor or control the connection state.

## Frequently Asked Questions

### How does Unity MCP handle connection failures?

Unity MCP handles connection failures through the `TryConnect()` method in [`McpServer.cs`](https://github.com/isuzu-shiranui/unitymcp/blob/main/McpServer.cs). When a connection attempt fails, the system sets the `isReconnecting` flag to true, closes the failed socket, and doubles the `currentReconnectDelay` value up to a maximum limit. The background thread continues attempting connections using this exponential backoff strategy until successful, preventing network overload while maintaining persistence.

### Can I disable automatic reconnection in Unity MCP?

While the system is designed to be persistent, you can effectively disable automatic reconnection by stopping the server entirely. Call `server.Stop()` to terminate the background thread and close the socket. To prevent automatic startup when Unity launches, disable `McpSettings.instance.autoStartOnLaunch` in the project settings. However, there is no built-in setting to run the server without reconnection attempts while maintaining the background thread.

### What triggers the connection restart when entering play mode?

The [`McpEditorInitializer.cs`](https://github.com/isuzu-shiranui/unitymcp/blob/main/McpEditorInitializer.cs) subscribes to `EditorApplication.playModeStateChanged`. When Unity transitions between edit mode and play mode (in either direction), the event handler stops the current `McpServer` instance, waits for the background thread to terminate, then creates a fresh server instance and starts it again. This ensures that the TCP connection and all MCP state align with the new scripting domain, preventing stale references across the domain reload that occurs during play mode changes.

### How do I configure the reconnection delay intervals?

Reconnection delays are configured through [`McpSettings.cs`](https://github.com/isuzu-shiranui/unitymcp/blob/main/McpSettings.cs), accessible via `McpSettings.instance`. The key parameters include the base `reconnectDelay` (initial wait time after first failure) and `maxReconnectDelay` (upper limit for the backoff interval). When connections fail, the system automatically doubles the delay between attempts until reaching the maximum value. These settings persist in Unity's editor preferences, allowing you to tune the aggression of reconnection attempts based on your network stability requirements.