MCP Server Core Components in DesktopCommanderMCP's src/server.ts
The MCP server in src/server.ts is built from eight core components: module imports with system-info caching, deferred logging, a Server instance with capability registration, resource/prompt request handlers, client tracking state, remote-client detection, utility imports, and version exposure.
The DesktopCommanderMCP repository implements a Model‑Context‑Protocol (MCP) server that exposes operating-system capabilities to AI clients. The src/server.ts file serves as the central orchestrator, wiring together SDK primitives, telemetry, and UI resources. Understanding its internal structure helps developers extend the server or debug client interactions.
Module Imports and System‑Info Constants
The file begins by pulling in dependencies and pre‑computing environment data. Lines 1–16 import the MCP SDK (@modelcontextprotocol/sdk), Zod validation helpers, and a suite of internal utilities. Lines 19–24 define SYSTEM_INFO, a constant object containing platform details used repeatedly by tool handlers.
// Lines 1-16 (abridged)
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { ListResourcesRequestSchema, ReadResourceRequestSchema } from "@modelcontextprotocol/sdk/types.js";
import * as systemInfo from "./utils/system-info.js";
import * as guidance from "./utils/guidance.js";
// Lines 19-24
const SYSTEM_INFO = {
platform: process.platform,
arch: process.arch,
version: process.version,
pid: process.pid
};
Caching this data avoids repeated system calls during tool execution.
Deferred Logging Mechanism
Before the server finishes initialization, log messages must not vanish. Lines 82–94 implement a deferred logging system using the deferredMessages array and two helper functions.
const deferredMessages: string[] = [];
function deferLog(level: string, message: string) {
deferredMessages.push(`[${level}] ${message}`);
}
function flushDeferredMessages() {
for (const msg of deferredMessages) {
logger.info(msg);
}
deferredMessages.length = 0;
}
This ensures diagnostic output survives the boot sequence.
Server Instance and Capability Registration
Lines 98–111 create the exported server object. The constructor receives metadata and advertises four capabilities: tools, resources, prompts, and logging.
export const server = new Server(
{ name: "desktop-commander", version: VERSION },
{
capabilities: {
tools: {},
resources: {},
prompts: {},
logging: {}
}
}
);
Empty objects signal that handlers will be registered separately. This pattern keeps the server definition declarative while allowing modular handler attachment.
Resource and Prompt Request Handlers
The server exposes UI resources through three handler registrations. Lines 113–118 handle resources/list, returning available panels via listUiResources(). Lines 120–127 implement resources/read, serving file previews and configuration editors. Lines 130–136 respond to prompts/list with an empty array (prompts are reserved for future use).
server.setRequestHandler(ListResourcesRequestSchema, async () => ({
resources: listUiResources(),
}));
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
// Routes to FILE_PREVIEW_RESOURCE_URI or CONFIG_EDITOR_RESOURCE_URI
});
server.setRequestHandler(ListPromptsRequestSchema, async () => ({
prompts: []
}));
These handlers bridge the MCP protocol to the visual components defined in src/ui/contracts.js.
Client Tracking State
Accurate telemetry requires knowing who is calling. Lines 38–100 maintain three pieces of mutable state and three setter functions.
| Variable | Purpose |
|---|---|
currentClient |
Name and version of the connected MCP client |
currentCallIsRemote |
Boolean flag for remote-device detection |
currentRemoteClient |
Identity string for remote callers |
let currentClient = { name: "", version: "" };
let currentCallIsRemote = false;
let currentRemoteClient: string | null = null;
export function setCurrentCallIsRemote(value: boolean) {
currentCallIsRemote = value;
}
export function updateCurrentClient(info: { name?: string; version?: string }) {
if (info.name !== currentClient.name || info.version !== currentClient.version) {
currentClient = { name: info.name ?? currentClient.name, version: info.version ?? currentClient.version };
const transport = (global as any).mcpTransport;
if (transport?.configureForClient) {
transport.configureForClient(currentClient.name);
}
}
}
The updateCurrentClient function additionally reconfigures the transport layer when the client identity changes.
Remote‑Client Detection
Lines 73–81 provide isRemoteClientContext(), a helper that inspects environment variables and connection metadata to determine if the session originated from a remote device. This affects routing decisions and security policies.
function isRemoteClientContext(): boolean {
return process.env.REMOTE_DEVICE === "true" ||
(global as any).mcpTransport?.isRemote === true;
}
Utility and Helper Imports
Between lines 28 and 71, the file imports specialized modules:
./utils/capture.js— Telemetry recording (capture,capture_call_tool)./utils/logger.js— Structured logging (logger,logToStderr)./ui/contracts.js— Resource URI constants (CONFIG_EDITOR_RESOURCE_URI,FILE_PREVIEW_RESOURCE_URI)./utils/ab-tests.js— Feature gating (shouldShowMcpUiPreviews)./utils/tool-history.js— Execution tracking (toolHistory)./utils/docker.js— Container prompt processing (processDockerPrompt)./utils/onboarding.js— Welcome flow (handleWelcomePageOnboarding)
These imports keep server.ts focused on protocol handling while delegating domain logic to focused modules.
Version and Constant Exposure
Line 71 imports VERSION from package.json, ensuring the server reports accurate release metadata. Line 25 defines CMD_PREFIX_DESCRIPTION, a human‑readable string that helps AI clients reference the server correctly in generated commands.
Summary
The MCP server core components in src/server.ts work together to:
- Initialize with cached system info and deferred logging for reliability
- Advertise capabilities (tools, resources, prompts, logging) to any MCP client
- Serve UI resources including file previews and configuration editors
- Track client identity and remote status for telemetry and transport configuration
- Delegate tool execution to handlers in
src/tools/while maintaining protocol compliance
Frequently Asked Questions
What is the purpose of deferred logging in the MCP server?
Deferred logging ensures that diagnostic messages generated during server initialization are captured even before the logging subsystem is fully ready. The deferLog function stores messages in deferredMessages, and flushDeferredMessages releases them once logger is available.
How does the server detect remote clients?
The isRemoteClientContext() function checks the REMOTE_DEVICE environment variable and inspects mcpTransport.isRemote on the global transport object. This detection influences security policies and telemetry tagging for tool calls originating outside the local machine.
Where are the actual tool implementations located?
Tool implementations reside in src/tools/, not in server.ts. The src/server.ts file registers capability handlers and tracks client state, while src/tools/ contains the executable logic, Zod schemas in src/tools/schemas.ts, and execution wrappers imported into the server.
Why does the server export its instance as a constant?
Exporting server as a const allows other modules—particularly those in src/tools/—to register additional request handlers and access server methods without circular dependencies. This pattern supports modular extension while keeping the protocol core in one place.
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 →