How the Remote Device Feature Enables Remote AI Control of Local Machines via OAuth 2.0
The Remote Device feature transforms a local Desktop Commander MCP installation into a secure, AI-driven workstation by using the OAuth 2.0 Device Authorization Flow to authenticate a local agent, which then maintains a persistent WebSocket connection to relay tool calls from cloud-based AI models to your local machine.
The DesktopCommanderMCP repository implements a sophisticated bridge that allows cloud AI services like ChatGPT or Claude to execute commands on local hardware. This capability relies on a three-layer architecture that combines local MCP server execution with OAuth 2.0 authentication and real-time message routing. Understanding this flow reveals how developers can safely expose local development environments to remote AI agents without compromising security.
Three-Layer Architecture of the Remote Device System
The implementation spans three distinct layers that handle authentication, communication, and execution:
- Local MCP Server: Runs the standard Desktop Commander CLI from
src/index.ts, exposing filesystem and shell tool calls via a local RPC interface. - Remote Device Agent: A lightweight Node process defined in
src/remote-device/device.tsthat handles OAuth 2.0 authentication and maintains the WebSocket channel. - Remote MCP (Cloud): The hosted interface where AI connectors subscribe to device-specific channels, storing tool calls in the
mcp_remote_callstable as implemented insrc/remote-device/remote-channel.ts.
OAuth 2.0 Device Authorization Flow Implementation
When the agent initializes, the DeviceAuthenticator.authenticate() method in src/remote-device/device-authenticator.ts initiates the standard OAuth 2.0 Device Authorization Grant flow.
Step 1: Request Device Code
The agent POSTs to the Remote MCP's /api/device/auth endpoint to retrieve a unique device code, verification URI, and short user code.
Step 2: User Authorization
The terminal displays a URL (e.g., https://mcp.desktopcommander.app/device/verify) and a short code (e.g., BLPU-9E9R). The user opens this URL on any device to authorize the connection.
Step 3: Token Polling
The agent polls the token endpoint until authorization completes, receiving an access_token and refresh_token encapsulated in an AuthSession object.
Step 4: Session Persistence
When launched with --persist-session, the agent writes tokens to ~/.desktop-commander-device/device.json, enabling automatic reconnection without repeating the flow.
Real-Time Channel and Tool Call Routing
After authentication, the RemoteChannel class establishes a Supabase Realtime WebSocket subscription to the device_tool_call_queue channel.
Connection Resilience
A watchdog invokes checkConnectionHealth() every 10 seconds to monitor channel state. If the WebSocket encounters errors or remains in a "joining" state, the agent automatically recreates the connection and resubscribes.
Heartbeat Mechanism
Every 15 seconds, updateHeartbeat() updates the last_seen timestamp, allowing the Remote MCP UI to display real-time online/offline status.
Tool Execution Pipeline
When messages arrive, MCPDevice.handleNewToolCall() validates the device_id, invokes markCallExecuting(), and forwards the request to DesktopCommanderIntegration.callClientTool(). Results return via updateCallResult() and propagate back to the cloud AI.
Security Model and Guarantees
The Remote Device feature implements several zero-trust principles:
- Zero-Trust Bridge: The agent runs locally; terminating the process with
Ctrl+Cimmediately severs all AI access. - Least-Privilege Execution: All commands execute under the local user's existing permissions, identical to native terminal sessions.
- Audit Logging: Every interaction logs to both local MCP server output and remote telemetry via
captureRemote('remote_device_auth_*')events.
Implementation Examples
The following snippets demonstrate core functionality from the DesktopCommanderMCP source:
// Initialize the Remote Device agent with session persistence
import { MCPDevice } from './src/remote-device/device.js';
const device = new MCPDevice({ persistSession: true });
await device.start(); // Handles OAuth flow, channel setup, and routing
// OAuth 2.0 Device Flow implementation (simplified from device-authenticator.ts)
export class DeviceAuthenticator {
async authenticate(existingDeviceId?: string): Promise<AuthSession> {
const { device_code, verification_uri, user_code } = await this.requestDeviceCode();
console.log(`Open ${verification_uri} and enter code: ${user_code}`);
const token = await this.pollForToken(device_code);
return {
access_token: token.access_token,
refresh_token: token.refresh_token
};
}
}
// Subscribing to remote tool calls via Supabase Realtime
private async createChannel(): Promise<void> {
this.channel = this.client!.channel('device_tool_call_queue')
.on('postgres_changes', {
event: 'INSERT',
schema: 'public',
table: 'mcp_remote_calls',
filter: `user_id=eq.${this.user!.id}`
}, payload => this.onToolCall?.(payload))
.subscribe((status, err) => {
if (status === 'SUBSCRIBED') console.log('Channel active');
else console.error('Subscription failed:', err);
});
}
Summary
- The Remote Device feature uses a three-layer architecture separating local execution, authentication, and cloud coordination.
- OAuth 2.0 Device Authorization Flow secures the initial connection without requiring local browser access or password entry in the terminal.
- Supabase Realtime WebSockets provide resilient, bi-directional communication with automatic reconnection and heartbeat monitoring.
- Tool calls route through
MCPDevice.handleNewToolCall()to execute locally under existing user permissions, maintaining security boundaries. - Session persistence optional via
--persist-sessionstores credentials in~/.desktop-commander-device/device.json.
Frequently Asked Questions
What happens if the Remote Device agent loses internet connectivity?
The RemoteChannel implementation includes a connection health watchdog that runs checkConnectionHealth() every 10 seconds. If the WebSocket disconnects or fails to subscribe, the agent automatically attempts to recreate the channel and re-authenticate using stored session tokens, ensuring operations resume once connectivity returns.
Can multiple AI services control the same local machine simultaneously?
While the architecture supports multiple connections, the device_tool_call_queue channel filters by user_id in src/remote-device/remote-channel.ts, ensuring only authorized users for that specific device can inject tool calls. Each device maintains a single active WebSocket subscription, though the cloud layer could theoretically round-robin requests from different AI connectors.
How does the OAuth 2.0 flow work without a browser on the local machine?
The Device Authorization Flow decouples authentication from the agent. The local terminal displays a verification_uri and user_code, allowing users to complete authorization on a smartphone or separate computer. The agent polls the token endpoint in the background until the user authorizes the device via the web interface.
Where are the OAuth tokens stored when using --persist-session?
When launched with the --persist-session flag, the DeviceAuthenticator class writes the access_token and refresh_token to ~/.desktop-commander-device/device.json. This JSON file enables the agent to reconnect automatically after restarts without requiring the user to re-authorize through the browser flow.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →