# How Remote MCP Works with Desktop Commander: Architecture and Communication Flow

> Discover how Remote MCP securely connects cloud AI to your local Desktop Commander. Learn about the three-tier architecture and Supabase Realtime communication flow without direct internet exposure.

- Repository: [Eduard Ruzga/DesktopCommanderMCP](https://github.com/wonderwhy-er/DesktopCommanderMCP)
- Tags: architecture
- Published: 2026-07-26

---

**The Remote MCP feature creates a secure bridge between cloud-based AI assistants and your local Desktop Commander instance using a three-tier architecture that routes tool calls through Supabase Realtime channels without exposing your machine to direct internet access.**

The Remote MCP feature in `wonderwhy-er/DesktopCommanderMCP` enables remote AI models to control your local machine without exposing sensitive credentials or opening firewall ports. This architecture allows ChatGPT, Claude, and other MCP-compatible assistants to execute terminal commands, edit files, and manage processes on your computer through a secure, authenticated tunnel managed by the Remote Device script.

## Three-Tier Architecture of Remote MCP

### Local MCP Server

The **Local MCP Server** is the standard Desktop Commander backend that runs on your machine. Located in [`src/server.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/server.ts), this component executes the actual tool calls—including terminal operations, file previews, and code edits—and exposes a Supabase-backed API for internal communication with the Remote Device.

### Remote Device

The **Remote Device** is a lightweight Node.js script (`desktop-commander-device`) defined in [`src/remote-device/device.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/device.ts). This component authenticates the user via OAuth 2.0, registers the device with the cloud service, and maintains a persistent WebSocket connection to receive tool calls. It acts as the secure intermediary between the cloud Remote MCP and your local machine, forwarding requests to the Local MCP Server.

### Remote MCP Cloud Service

The **Remote MCP cloud service** (`https://mcp.desktopcommander.app`) hosts the Supabase project that stores device metadata and routes AI-generated tool calls. Implemented in [`src/remote-device/remote-channel.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/remote-channel.ts), this layer manages the Realtime channels that deliver commands to specific devices through the `mcp_remote_calls` table.

## Communication Flow and Connection Lifecycle

### Startup and Authentication

When you run `desktop-commander-device` or `npm run device:start`, the script creates an `MCPDevice` instance that initiates the connection sequence:

1. **Configuration Fetching**: The device retrieves Supabase configuration from `${MCP_SERVER_URL}/api/mcp-info` using the `fetchSupabaseConfig` function.
2. **OAuth 2.0 Device Flow**: If no persisted session exists, `DeviceAuthenticator` executes the OAuth 2.0 Device Authorization Flow, prompting you to visit a verification URL and enter a short code.
3. **Session Establishment**: After authorization, the device receives a Supabase session containing `access_token`, `refresh_token`, and a unique `device_id`.

### Session and Channel Setup

Once authenticated, the device establishes persistent communication channels:

- **Session Persistence**: The device optionally stores tokens locally when using the `--persist-session` flag.
- **Channel Registration**: The `RemoteChannel` class calls `registerDevice`, which looks up the device record via `findDevice`, marks it as **online** in the `mcp_devices` table, and creates a Realtime channel named `device_tool_call_queue`.
- **Subscription Setup**: The channel subscribes to `INSERT` events on the `mcp_remote_calls` table filtered by user ID, ensuring AI-generated tool calls appear as new database rows ready for processing.

### Heartbeat and Health Monitoring

To maintain connection integrity, `RemoteChannel.startHeartbeat` implements dual-interval monitoring in [`src/remote-device/remote-channel.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/remote-channel.ts):

- **15-Second Heartbeat**: Updates the `last_seen` timestamp in the `mcp_devices` table to signal active status to the cloud service.
- **10-Second Health Check**: Monitors the Realtime channel state; if the channel becomes unhealthy (e.g., stuck in `joining` state), `recreateChannel` tears down the old connection, forces a fresh WebSocket, and resubscribes to prevent message loss.

### Tool Call Execution

When a new row arrives in `mcp_remote_calls`, `RemoteChannel` delivers the payload to `MCPDevice.handleNewToolCall`:

1. **Status Update**: The device marks the call as **executing** via `markCallExecuting`.
2. **Built-in Tools**: For `ping` and `shutdown` commands, the device generates static responses locally without invoking the Local MCP Server.
3. **Local Delegation**: All other tools route through `DesktopCommanderIntegration.callClientTool` in [`src/desktop-commander-integration.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/desktop-commander-integration.ts), which communicates with the local MCP server to execute the requested operation.
4. **Result Persistence**: After execution, `updateCallResult` writes the outcome—including `status`, `result`, and `error_message`—back to the `mcp_remote_calls` row for the cloud service to retrieve.

### Graceful Shutdown

On `SIGINT`/`SIGTERM` signals or remote `shutdown` tool calls, the device executes cleanup routines: it stops the heartbeat intervals, unsubscribes from the Realtime channel, marks the device as **offline** in the database, and terminates the local Desktop Commander integration.

## Implementation Examples

Start the device with session persistence:

```bash
desktop-commander-device --persist-session

```

Development startup:

```bash
npm run device:start

```

Programmatic integration:

```typescript
import { MCPDevice } from './src/remote-device/device.js';

const device = new MCPDevice({ persistSession: true });
await device.start();   // Resolves when registered and listening

```

Internal tool call handling logic from [`src/remote-device/device.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/device.ts):

```typescript
// Inside MCPDevice.handleNewToolCall
if (tool_name === 'ping') {
  result = { content: [{ type: 'text', text: `pong ${new Date().toISOString()}` }] };
} else {
  result = await this.desktop.callClientTool(tool_name, tool_args, metadata);
}
await this.remoteChannel.updateCallResult(call_id, 'completed', result);

```

Heartbeat implementation in [`src/remote-device/remote-channel.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/remote-channel.ts):

```typescript
startHeartbeat(deviceId: string) {
  this.connectionCheckInterval = setInterval(() => this.checkConnectionHealth(), 10_000);
  this.heartbeatInterval = setInterval(() => this.updateHeartbeat(deviceId), 15_000);
}

```

## Key Source Files and Components

- **[`src/remote-device/device.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/device.ts)**: Main entry point handling authentication, session persistence, tool-call routing, and shutdown procedures.
- **[`src/remote-device/remote-channel.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/remote-channel.ts)**: Wraps Supabase Realtime functionality, managing channels, heartbeats, health checks, and database updates for remote calls.
- **[`src/remote-device/device-authenticator.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/device-authenticator.ts)**: Implements OAuth 2.0 Device Authorization Flow for secure first-run authentication.
- **[`src/remote-device/desktop-commander-integration.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/desktop-commander-integration.ts)**: Bridges remote calls to the local Desktop Commander MCP server via internal API.
- **[`src/server.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/server.ts)**: Core Desktop Commander MCP server executing tools locally.
- **[`src/remote-device/README.md`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/README.md)**: User documentation for installation and operation of the Remote Device.

## Summary

- **Remote MCP** enables secure remote control by connecting cloud AI assistants to local Desktop Commander instances through a three-tier architecture consisting of the Local MCP Server, Remote Device, and cloud-hosted Remote MCP service.
- The **Remote Device** script ([`src/remote-device/device.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/device.ts)) maintains persistent WebSocket connections via Supabase Realtime, handling authentication through OAuth 2.0 Device Flow and storing session tokens securely.
- **Health monitoring** uses dual intervals: 15-second heartbeats update presence status in the `mcp_devices` table, while 10-second checks ensure channel viability with automatic reconnection via `recreateChannel`.
- Tool calls flow from cloud to local through the `mcp_remote_calls` table, with `DesktopCommanderIntegration.callClientTool` executing commands on your machine and writing results back to the database.
- All communication uses Supabase authentication tokens; the Remote Device never exposes credentials externally, and immediate shutdown is available via `Ctrl-C` or remote command.

## Frequently Asked Questions

### What is the Remote MCP feature in Desktop Commander?

The Remote MCP feature is a secure tunneling system that allows remote AI assistants like ChatGPT or Claude to control your local Desktop Commander instance. It consists of a cloud-hosted routing service, a local device connector script, and the standard MCP server, enabling command execution without exposing your machine directly to the internet or sharing sensitive credentials with third parties.

### How does the Remote Device authenticate with the cloud service?

The Remote Device uses the OAuth 2.0 Device Authorization Flow implemented in [`src/remote-device/device-authenticator.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/device-authenticator.ts). On first run, it displays a verification URL and short code for you to authorize in a browser. After authorization, it receives Supabase session tokens (`access_token` and `refresh_token`) and a `device_id`, which it uses for all subsequent authenticated WebSocket connections to the Remote MCP cloud service.

### What happens if the Remote Device loses connection?

If the connection becomes unhealthy (detected via 10-second health checks in [`src/remote-device/remote-channel.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/remote-channel.ts)), the `recreateChannel` method automatically tears down the stale WebSocket, establishes a fresh connection, and resubscribes to the `device_tool_call_queue` channel. The device also updates its `last_seen` timestamp every 15 seconds; if these updates stop, the cloud service marks the device as offline and queues calls until reconnection.

### Can I run the Remote Device without installing it globally?

Yes, you can run the Remote Device directly from the source repository without global installation. Use `npm run device:start` from the project root, or import the `MCPDevice` class programmatically from [`src/remote-device/device.js`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/device.js) to integrate remote capabilities into your own Node.js applications while maintaining full control over the execution environment.