How Remote MCP Creates Secure Connections Between Cloud and Local Devices

Remote MCP establishes secure connections through OAuth 2.0 device authentication, TLS-encrypted WebSockets via Supabase Realtime, and per-user channel isolation with automated health monitoring.

DesktopCommanderMCP enables remote AI services to execute tools on local machines through a lightweight Remote Device client. According to the wonderwhy-er/DesktopCommanderMCP source code, this architecture creates an encrypted tunnel that verifies device identity before every command and isolates all traffic to authenticated user sessions.

Three-Layer Security Architecture

The security model implemented in src/remote-device/remote-channel.ts and src/remote-device/device-authenticator.ts relies on distinct layers that operate together to protect data in transit and prevent unauthorized access.

Authentication Layer: OAuth 2.0 Device Flow

The DeviceAuthenticator class executes an OAuth 2.0 Device Authorization Flow to prove device ownership. The process begins when DeviceAuthenticator.authenticate() requests a device code from the server. The user authorizes this code in a browser, and the device polls /device/poll until it receives a short-lived access_token and optional refresh_token. These tokens are stored in memory (or persisted with --persist-session) and used for all subsequent API calls.

Transport Security: TLS-Encrypted WebSockets

Once authenticated, the RemoteChannel.initialize(url, key) method creates a Supabase Realtime client that communicates over TLS-encrypted WebSockets (wss://). The client authenticates each request using the bearer token obtained during the OAuth flow via client.auth.setSession. This ensures that all data exchanged between the cloud and local device remains encrypted end-to-end, with the server URL and publishable key supplied by the infrastructure.

Channel Isolation: Per-User Filtering and Access Control

RemoteChannel.createChannel() constructs a dedicated Realtime channel named device_tool_call_queue that filters messages using the authenticated user_id. The filter user_id=eq.${this.user.id} guarantees that the device only receives tool calls intended for that specific user. Every payload is tied to the device ID and logged via captureRemote for auditability, ensuring that AI-initiated commands remain isolated to the authorized device.

Connection Lifecycle and Implementation Flow

The secure connection follows a rigorous eight-step lifecycle that combines registration, subscription, and continuous health monitoring.

  1. Initialize the Remote Device – The Device class boots and instantiates RemoteChannel, preparing the infrastructure for secure communication.

  2. Execute Device AuthenticationDeviceAuthenticator.authenticate() displays a URL and user code, then polls the authorization endpoint until tokens are granted.

  3. Create Supabase ClientRemoteChannel.initialize(url, key) builds a client configured for the remote server endpoint.

  4. Bind User SessionRemoteChannel.setSession() invokes client.auth.setSession with the access_token and refresh_token, binding the WebSocket to the user's identity.

  5. Register Device PresenceRemoteChannel.registerDevice() creates or updates a row in the mcp_devices table, marking the device as online and storing its capabilities.

  6. Subscribe to Tool CallsRemoteChannel.createChannel() opens the device_tool_call_queue channel, listening for INSERT events on mcp_remote_calls filtered by the authenticated user_id. The AI pushes tool calls into this table; the device receives them via the channel callback.

  7. Maintain Heartbeat and HealthRemoteChannel.startHeartbeat() updates last_seen every 15 seconds, while checkConnectionHealth() runs every 10 seconds. If the socket becomes half-open or the channel remains in a joining state for longer than 30 seconds, the recreateChannel watchdog forces a fresh WebSocket connection.

  8. Execute and Respond – Upon receiving a tool call, the device executes the requested operation via runTool(), then calls RemoteChannel.updateCallResult() to write the result (or error) back to mcp_remote_calls. The Remote MCP reads this row and relays the response to the AI.

Code Implementation Examples

The following TypeScript examples demonstrate the core implementation patterns found in the DesktopCommanderMCP codebase.

// 1️⃣ Initialise the RemoteChannel (inside src/remote-device/device.ts)
const remoteChannel = new RemoteChannel();
remoteChannel.initialize(supabaseUrl, anonKey);

// 2️⃣ Authenticate the device (OAuth2 Device Flow)
const authenticator = new DeviceAuthenticator(baseServerUrl);
const session = await authenticator.authenticate();   // returns { access_token, refresh_token }

// 3️⃣ Bind the session to the Supabase client
await remoteChannel.setSession(session);

// 4️⃣ Register (or update) the device and start the realtime channel
await remoteChannel.registerDevice(
  { /* capabilities */ },
  existingDeviceId,
  'My‑Laptop',
  (payload) => onToolCall(payload)          // handler for AI‑initiated tool calls
);

// 5️⃣ Start heartbeats to keep the device marked online
remoteChannel.startHeartbeat(deviceId);
// 6️⃣ Handling an incoming tool call (simplified)
async function onToolCall(payload: any) {
  const callId = payload.new.id;
  await remoteChannel.markCallExecuting(callId);
  try {
    const result = await runTool(payload.new.tool_name, payload.new.args);
    await remoteChannel.updateCallResult(callId, 'completed', result);
  } catch (e) {
    await remoteChannel.updateCallResult(callId, 'failed', null, e.message);
  }
}

Key Source Files for Security Implementation

Understanding the secure connection architecture requires examining these specific files in the DesktopCommanderMCP repository:

Summary

Remote MCP creates secure connections between cloud AI services and local devices through several interconnected mechanisms:

  • OAuth 2.0 Device Flow authenticates devices without exposing long-term credentials, using short-lived access tokens obtained through browser-based user authorization.
  • TLS-encrypted WebSockets (via Supabase Realtime) protect all data in transit, with authentication enforced on every connection.
  • Per-user channel isolation ensures tool calls are filtered by user_id, preventing cross-user access or channel hijacking.
  • Continuous health monitoring via checkConnectionHealth() and automatic recreateChannel() logic prevents the use of stale or compromised connections.
  • Audit logging through captureRemote provides visibility into all AI-initiated tool calls for security review.

Frequently Asked Questions

How does Remote MCP authenticate devices without exposing user credentials?

DesktopCommanderMCP uses the OAuth 2.0 Device Authorization Flow implemented in DeviceAuthenticator (src/remote-device/device-authenticator.ts). The device requests a temporary device code, the user authorizes it in a browser, and the device receives a short-lived access token. Long-term credentials never touch the local device; only the temporary bearer token is used to authenticate WebSocket connections.

What happens if the WebSocket connection drops during a tool execution?

The RemoteChannel class runs checkConnectionHealth() every 10 seconds to detect half-open sockets or channels stuck in the joining state for more than 30 seconds. If the connection is unhealthy, recreateChannel() forces a fresh WebSocket and resubscribes to the device_tool_call_queue. The device continues executing local operations, and results are written to mcp_remote_calls once connectivity restores.

Is the communication between cloud and device end-to-end encrypted?

Yes. All traffic travels over TLS-encrypted WebSockets (wss://) established by the Supabase Realtime client. Additionally, each request includes the bearer token obtained during OAuth authentication, ensuring that even if the WebSocket endpoint were discovered, unauthorized parties could not impersonate the device without valid credentials.

How does the system prevent unauthorized AI agents from accessing my device?

Access control operates at multiple levels. First, the Supabase channel filters (user_id=eq.${this.user.id}) ensure the device only receives messages for its authenticated user. Second, the device must complete the OAuth flow and register in the mcp_devices table before accepting commands. Finally, users maintain physical control; pressing Ctrl+C immediately terminates the device process, severing the secure connection and preventing further tool invocations.

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 →