# How the Remote Device Feature Creates Secure Connections Between AI Clients and Local Machines

> Learn how the Remote Device feature builds secure, end-to-end encrypted tunnels between AI clients and local machines using PKCE OAuth and Supabase Realtime WebSockets. Ensure safe AI-to-local connections.

- Repository: [Eduard Ruzga/DesktopCommanderMCP](https://github.com/wonderwhy-er/DesktopCommanderMCP)
- Tags: how-to-guide
- Published: 2026-07-09

---

**The Remote Device feature creates secure connections by combining PKCE-protected OAuth authentication, Supabase Realtime WebSocket channels, and automatic health monitoring to establish end-to-end encrypted tunnels between AI clients and local machines.**

The `wonderwhy-er/DesktopCommanderMCP` repository implements a sophisticated remote execution architecture that allows AI assistants to safely invoke tools on user workstations. This system leverages short-lived access tokens, device-code OAuth flows, and resilient WebSocket connections to ensure that only authorized clients can trigger local commands. Understanding how this Remote Device feature establishes connectivity is essential for deploying secure remote operations in production environments.

## End-to-End Encryption Architecture

The Remote Device feature operates through three coordinated layers: a PKCE-protected authentication system, a bidirectional Realtime channel, and a health-monitoring subsystem. According to the DesktopCommanderMCP source code, when the CLI launches via `desktop-commander-device`, it initializes an `MCPDevice` instance that orchestrates these components.

In [`src/remote-device/device.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/device.ts) (lines 25-33), the constructor sets the remote server URL, prepares a configuration path for session persistence, and registers graceful shutdown handlers. The device then fetches Supabase configuration from the public `/api/mcp-info` endpoint via `fetchSupabaseConfig()` (lines 42-58), obtaining the anonymous key required to initialize the Realtime client.

## PKCE-Protected Authentication Flow

### Device Code Flow Implementation

The authentication sequence begins in [`src/remote-device/device-authenticator.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/device-authenticator.ts) (lines 60-77), where the device implements the OAuth device-code flow with PKCE (Proof Key for Code Exchange) protection. This process generates a unique `code_verifier` and `code_challenge` pair to prevent interception attacks during the token exchange.

If no persisted session exists, the device executes the flow: generating PKCE parameters, requesting a device code from the authorization server, displaying user instructions, and polling for tokens. The resulting short-lived `access_token` is then passed to the Supabase client via `setSession()` in [`src/remote-device/remote-channel.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/remote-channel.ts) (lines 62-95), which stores the token locally and fetches the associated user record.

### Token-Only Access Model

Security is maintained through a token-only access model between AI clients and local machines. The only credential transmitted over the network is the temporary access token obtained from the device flow. No long-lived secret keys are stored in the repository or hardcoded in the source. All communication with Supabase endpoints occurs over TLS-encrypted HTTPS/WSS connections, ensuring confidentiality and integrity during transit.

## Realtime Channel and Secure Communication

### Channel Initialization

After authentication, the device registers itself in the [`src/remote-device/remote-channel.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/remote-channel.ts) implementation (lines 53-86). The `registerDevice()` method writes the device's capabilities to the `mcp_devices` table and creates a Realtime subscription using `client.channel('device_tool_call_queue')`. This WebSocket channel serves as the encrypted transport for bidirectional tool-call messages.

### Device-ID Binding and Verification

Every tool-call payload includes a `device_id` field that binds requests to specific hardware. When incoming calls arrive via the Realtime channel, the `handleNewToolCall()` function in [`src/remote-device/device.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/device.ts) (lines 62-84) validates that the payload's `device_id` matches the local device's identifier before execution. This verification prevents cross-device impersonation and ensures that AI clients cannot invoke tools on unauthorized machines.

## Connection Resilience and Health Monitoring

### Automatic Reconnection Strategy

The Remote Device feature implements robust reconnection logic to maintain secure connectivity without user intervention. In [`src/remote-device/remote-channel.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/remote-channel.ts) (lines 44-58), the `recreateChannel()` method forcibly disconnects stalled WebSockets and constructs fresh connections when the channel enters an unhealthy state or remains in the "joining" state for more than 30 seconds.

### Heartbeat Mechanism

Two independent timers manage connection liveness: `heartbeatInterval` and `connectionCheckInterval`. As implemented in [`src/remote-device/remote-channel.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/remote-channel.ts) (lines 52-64), the `startHeartbeat()` function periodically updates the device's status via `updateHeartbeat()` while `checkConnectionHealth()` monitors socket state. If either check detects a broken connection, the system triggers a channel recreation automatically.

## Graceful Shutdown and Cleanup

When the process receives SIGINT or SIGTERM signals, the `shutdown()` method in [`src/remote-device/device.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/device.ts) (lines 22-34) executes a coordinated cleanup sequence. This stops the heartbeat timers, unsubscribes from the Realtime channel, marks the device as offline in the database, and closes the local Desktop Commander integration. This graceful shutdown prevents orphaned connections and ensures the device status accurately reflects availability to AI clients.

## Implementation Examples

### Running the Remote Device CLI

To start a secure remote device from the command line:

```bash

# Install the package globally

npm install -g @wonderwhy-er/desktop-commander

# Start the device with session persistence

desktop-commander-device --persist-session

```

This command launches [`src/remote-device/device.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/device.ts), which executes the complete authentication flow and maintains the encrypted channel.

### Programmatic Device Initialization

For integration into existing Node.js applications:

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

(async () => {
  const device = new MCPDevice({ persistSession: true });
  await device.start(); // Triggers authentication, channel subscription, and heartbeat
})();

```

This approach instantiates the device class defined in [`src/remote-device/device.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/device.ts) and begins the secure connection sequence.

### Sending Tool Calls from AI Clients

AI clients can invoke local tools by writing to the Supabase table:

```typescript
import { createClient } from '@supabase/supabase-js';

const supabase = createClient(SUPABASE_URL, SERVICE_ROLE_KEY);

// Insert a tool call targeting a specific device
await supabase.from('mcp_remote_calls').insert({
  user_id: USER_ID,
  device_id: DEVICE_ID,
  tool_name: 'list_files',
  tool_args: { path: '/' },
  status: 'queued',
});

```

The Remote Device receives this `INSERT` event through its Realtime channel subscription, validates the `device_id`, executes the tool locally via Desktop Commander integration, and writes results back to the same row.

## Summary

- **PKCE Protection**: The OAuth device-code flow with code verifier/challenge pairs prevents token interception during authentication between AI clients and local machines.
- **Encrypted Transport**: All communication uses TLS-encrypted HTTPS for REST APIs and WSS for WebSocket Realtime channels.
- **Device Binding**: Every tool call is validated against the specific `device_id` to prevent unauthorized cross-device execution.
- **Resilient Connections**: Automatic health checks and forced reconnection logic maintain secure connectivity without manual intervention.
- **Token Security**: Only short-lived access tokens traverse the network; no long-lived secrets are stored in the repository.

## Frequently Asked Questions

### How does the Remote Device feature prevent unauthorized access to local machines?

The system prevents unauthorized access through multiple layers: PKCE-protected OAuth device-code flows ensure tokens cannot be intercepted and replayed, device-ID binding validates that each tool call targets the specific authorized machine, and all transport layers use TLS encryption. Additionally, the device validates incoming Realtime payloads in [`src/remote-device/device.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/device.ts) (lines 62-84) before executing any local commands.

### What happens if the WebSocket connection drops during operation?

The health monitoring system in [`src/remote-device/remote-channel.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/remote-channel.ts) detects connection failures through periodic checks (lines 52-64). When a stall or error is detected, the `recreateChannel()` method (lines 44-58) forcibly closes the broken socket and establishes a fresh WebSocket connection, then resubscribes to the `device_tool_call_queue` channel. This process occurs automatically without requiring user re-authentication if the session remains valid.

### Where are authentication credentials stored on the local machine?

When using the `--persist-session` flag, the short-lived access token and refresh token are stored locally in a configuration path prepared by the `MCPDevice` constructor ([`src/remote-device/device.ts`](https://github.com/wonderwhy-er/DesktopCommanderMCP/blob/main/src/remote-device/device.ts), lines 25-33). These credentials are never transmitted to the AI client or stored in cloud repositories; they remain exclusively on the local device to authenticate with Supabase Realtime channels.

### Can multiple AI clients connect to the same Remote Device simultaneously?

While the architecture supports multiple concurrent connections through the Supabase Realtime channel, the device processes tool calls sequentially based on the `mcp_remote_calls` table updates. Each client must authenticate separately and include the correct `device_id` when inserting calls. The local device validates ownership of each request before execution to maintain security boundaries between AI clients and local machines.