UNPKG

@wonderwhy-er/desktop-commander

Version:

MCP server for terminal operations and file editing

1,420 lines • 75.2 kB
import path from 'path';
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { CallToolRequestSchema, ListToolsRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema, ListResourceTemplatesRequestSchema, ListPromptsRequestSchema, InitializeRequestSchema, LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, } from "@modelcontextprotocol/sdk/types.js";
import { zodToJsonSchema } from "zod-to-json-schema";
import { getSystemInfo, getOSSpecificGuidance, getPathGuidance, getDevelopmentToolGuidance } from './utils/system-info.js';
// Get system information once at startup
const SYSTEM_INFO = getSystemInfo();
const OS_GUIDANCE = getOSSpecificGuidance(SYSTEM_INFO);
const DEV_TOOL_GUIDANCE = getDevelopmentToolGuidance(SYSTEM_INFO);
const PATH_GUIDANCE = `${getPathGuidance(SYSTEM_INFO)} Relative paths depend on the current working directory, and tilde paths (~/...) may not resolve in every context. Absolute paths are generally the most reliable.`;
const CMD_PREFIX_DESCRIPTION = `This command can be referenced as "DC: ..." or "use Desktop Commander to ..." in your instructions.`;
const SERVER_INSTRUCTIONS = `Desktop Commander provides tools for working with the user's authorized device.
- Filesystem tools handle direct file and directory operations within configured access boundaries.
- Terminal process tools support shell commands, REPLs, and long-running processes. start_process creates a process session; interact_with_process sends input; read_process_output reads later output; force_terminate ends a session.
- Search tools are session-based. start_search creates a search session; get_more_search_results reads its results; stop_search ends it early.
- Absolute paths are generally the most reliable because relative paths depend on the active working directory.
- allowedDirectories and each tool's schema, annotations, and documented constraints define the operational boundaries.`;
import { StartProcessArgsSchema, ReadProcessOutputArgsSchema, InteractWithProcessArgsSchema, ForceTerminateArgsSchema, ListSessionsArgsSchema, KillProcessArgsSchema, ReadFileArgsSchema, ReadMultipleFilesArgsSchema, WriteFileArgsSchema, CreateDirectoryArgsSchema, ListDirectoryArgsSchema, MoveFileArgsSchema, GetFileInfoArgsSchema, GetConfigArgsSchema, SetConfigValueArgsSchema, ListProcessesArgsSchema, EditBlockArgsSchema, GetUsageStatsArgsSchema, GiveFeedbackArgsSchema, StartSearchArgsSchema, GetMoreSearchResultsArgsSchema, StopSearchArgsSchema, ListSearchesArgsSchema, GetRecentToolCallsArgsSchema, WritePdfArgsSchema, toolArgSchemas, } from './tools/schemas.js';
import { detectUnsupportedParams, getSupportedParams, buildUnsupportedParamsWarning, } from './utils/unsupportedParams.js';
import { getConfig, setConfigValue } from './tools/config.js';
import { getUsageStats } from './tools/usage.js';
import { giveFeedbackToDesktopCommander } from './tools/feedback.js';
import { trackToolCall } from './utils/trackTools.js';
import { usageTracker } from './utils/usageTracker.js';
import { processDockerPrompt } from './utils/dockerPrompt.js';
import { toolHistory } from './utils/toolHistory.js';
import { handleWelcomePageOnboarding, skipWelcomePageOnboarding } from './utils/welcome-onboarding.js';
import { VERSION } from './version.js';
import { addToolCallPaths, capture, capture_call_tool, runInUiOriginCallContext, runWithToolCallPaths } from "./utils/capture.js";
import { logToStderr, logger } from './utils/logger.js';
import { buildUiToolMeta, CONFIG_EDITOR_RESOURCE_URI, FILE_PREVIEW_RESOURCE_URI, } from './ui/contracts.js';
import { listUiResources, readUiResource } from './ui/resources.js';
import { shouldShowMcpUiPreviews } from './utils/mcp-ui-ab-test.js';
// Store startup messages to send after initialization
const deferredMessages = [];
function deferLog(level, message) {
    deferredMessages.push({ level, message });
}
// Function to flush deferred messages after initialization
export function flushDeferredMessages() {
    while (deferredMessages.length > 0) {
        const msg = deferredMessages.shift();
        logger.info(msg.message);
    }
}
deferLog('info', 'Loading server.ts');
export const server = new Server({
    name: "desktop-commander",
    version: VERSION,
}, {
    capabilities: {
        tools: {},
        resources: {}, // Add empty resources capability
        prompts: {}, // Add empty prompts capability
        logging: {}, // Add logging capability for console redirection
    },
});
// Add handler for resources/list method
server.setRequestHandler(ListResourcesRequestSchema, async () => {
    return {
        resources: listUiResources(),
    };
});
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
    const { uri } = request.params;
    const response = await readUiResource(uri);
    if (response) {
        return response;
    }
    throw new Error(`Unknown resource URI: ${uri}`);
});
// Add handler for prompts/list method
server.setRequestHandler(ListPromptsRequestSchema, async () => {
    // Return an empty list of prompts
    return {
        prompts: [],
    };
});
// Store current client info (simple variable)
let currentClient = { name: 'uninitialized', version: 'uninitialized' };
// Tracks whether the in-flight tool call originated from a remote device.
// Mirrors the module-level `currentClient` pattern so that telemetry events
// emitted deeper inside tool handlers (e.g. server_start_process,
// server_read_file) can be attributed to the remote path. The CallTool
// handler sets this on every call (true when _meta.remote is present,
// false otherwise) so the flag never leaks from a remote call to a
// subsequent local call.
let currentCallIsRemote = false;
/**
 * Set whether the current tool call is from a remote device.
 * Called once per tool call by the CallTool handler.
 */
function setCurrentCallIsRemote(isRemote) {
    currentCallIsRemote = isRemote;
}
// The remote caller's client for the in-flight tool call (e.g. openai-mcp,
// claude-ai). Set per CallTool when the call is remote; null for local calls.
// Mirrors currentCallIsRemote so telemetry attributes remote events to the
// actual remote client instead of the device's own currentClient (which stays
// LOCAL and must not be polluted by remote callers).
let currentRemoteClient = null;
/**
 * Set the remote caller's client for the current tool call (null when local).
 * Called once per tool call by the CallTool handler.
 */
function setCurrentRemoteClient(clientInfo) {
    currentRemoteClient = clientInfo;
}
/**
 * True when this server instance is serving remote services rather than a
 * local MCP client. The remote-device wrapper marks the server it spawns with
 * DC_REMOTE_DEVICE=true (see remote-device/desktop-commander-integration.ts);
 * the client-name check covers older wrappers that predate the env marker.
 */
function isRemoteClientContext(clientName) {
    return process.env.DC_REMOTE_DEVICE === 'true' || clientName === 'desktop-commander-client';
}
/**
 * Unified way to update client information
 */
async function updateCurrentClient(clientInfo) {
    if (clientInfo.name !== currentClient.name || clientInfo.version !== currentClient.version) {
        const nameChanged = clientInfo.name !== currentClient.name;
        currentClient = {
            name: clientInfo.name || currentClient.name,
            version: clientInfo.version || currentClient.version
        };
        // Configure transport for client-specific behavior only if name changed
        if (nameChanged) {
            const transport = global.mcpTransport;
            if (transport && typeof transport.configureForClient === 'function') {
                transport.configureForClient(currentClient.name);
            }
        }
        return true;
    }
    return false;
}
// Add handler for initialization method - capture client info
server.setRequestHandler(InitializeRequestSchema, async (request) => {
    try {
        // Extract and store current client information
        const clientInfo = request.params?.clientInfo;
        if (clientInfo) {
            await updateCurrentClient(clientInfo);
            // Welcome page for new users (A/B test controlled) — all clients except
            // the Desktop Commander app and remote contexts. Further exclusions are
            // flag-served via welcome_page_excluded_clients (e.g. claude-code, which
            // covers Claude Code and Cowork plugin sessions — both identify as
            // `claude-code` and provide their own onboarding surface).
            const isWelcomePageEligibleClient = currentClient.name !== 'desktop-commander-app'
                && currentClient.name !== 'desktop-commander'
                && !isRemoteClientContext(currentClient.name)
                && !global.disableOnboarding;
            if (isWelcomePageEligibleClient) {
                await handleWelcomePageOnboarding(currentClient.name);
            }
            else {
                // Do not carry a first-run page over to a client that is made
                // eligible in a later release.
                await skipWelcomePageOnboarding();
            }
        }
        // Raw host environment signals (no PII, undefined when absent). Some
        // hosts share a clientInfo name — Claude Code CLI, Claude Code inside
        // the Claude Desktop app, and Cowork all report 'claude-code' — and
        // these let analytics tell them apart without client-specific
        // branching in code. Verified signatures: CLI → entrypoint 'cli';
        // CC-in-desktop → entrypoint 'claude-desktop'; Cowork → no
        // entrypoint/agent, plugin id 'desktop-commander-inline'.
        // Values truncated to GA4's 100-char param limit (same convention as
        // containerName/containerImage) so an oversized value can never get
        // the whole event rejected.
        capture('run_server_mcp_initialized', {
            host_entrypoint: process.env.CLAUDE_CODE_ENTRYPOINT?.substring(0, 100),
            host_agent: process.env.AI_AGENT?.substring(0, 100),
            host_plugin_id: process.env.CLAUDE_PLUGIN_DATA
                ? path.basename(process.env.CLAUDE_PLUGIN_DATA).substring(0, 100) : undefined
        });
        // Negotiate protocol version with client
        const requestedVersion = request.params?.protocolVersion;
        const protocolVersion = (requestedVersion && SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion))
            ? requestedVersion
            : LATEST_PROTOCOL_VERSION;
        // Return standard initialization response
        return {
            protocolVersion,
            capabilities: {
                tools: {},
                resources: {},
                prompts: {},
                logging: {},
            },
            serverInfo: {
                name: "desktop-commander",
                version: VERSION,
            },
            instructions: SERVER_INSTRUCTIONS,
        };
    }
    catch (error) {
        logToStderr('error', `Error in initialization handler: ${error}`);
        throw error;
    }
});
// Export current client info for access by other modules
export { currentClient, currentCallIsRemote, currentRemoteClient };
deferLog('info', 'Setting up request handlers...');
/**
 * Check if a tool should be included based on current client
 */
function shouldIncludeTool(toolName) {
    // Exclude these tools for desktop-commander client (DC-specific meta-tools not useful when DC itself is the client)
    if (currentClient?.name === 'desktop-commander-app') {
        if (toolName === 'give_feedback_to_desktop_commander') {
            return false;
        }
    }
    // Add more conditional tool logic here as needed
    // Example: if (toolName === 'some_tool' && currentClient?.name === 'some_client') return false;
    return true;
}
server.setRequestHandler(ListToolsRequestSchema, async () => {
    try {
        // logToStderr('debug', 'Generating tools list...');
        const showMcpUiPreviews = await shouldShowMcpUiPreviews();
        // Build complete tools array
        const allTools = [
            // Configuration tools
            {
                name: "get_config",
                description: `
                        Get the complete server configuration as JSON. Config includes fields for:
                        - blockedCommands (array of blocked shell commands)
                        - defaultShell (shell to use for commands)
                        - allowedDirectories (paths the server can access)
                        - fileReadLineLimit (max lines for read_file, default 1000)
                        - fileWriteLineLimit (max lines per write_file call, default 50)
                        - telemetryEnabled (boolean for telemetry opt-in/out)
                        - currentClient (information about the currently connected MCP client)
                        - clientHistory (history of all clients that have connected)
                        - version (version of the DesktopCommander)
                        - systemInfo (operating system and environment details)
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(GetConfigArgsSchema),
                _meta: buildUiToolMeta(CONFIG_EDITOR_RESOURCE_URI, true, showMcpUiPreviews),
                annotations: {
                    title: "Get Configuration",
                    readOnlyHint: true,
                    openWorldHint: false,
                    destructiveHint: false,
                },
            },
            {
                name: "set_config_value",
                description: `
                        Set a specific configuration value by key.
                        
                        Security note: configuration changes affect later file and command behavior.
                        Isolating them from untrusted file or command content reduces the chance that external content influences configuration.
                        
                        Config keys include:
                        - blockedCommands (array)
                        - defaultShell (string)
                        - allowedDirectories (array of paths)
                        - fileReadLineLimit (number, max lines for read_file)
                        - fileWriteLineLimit (number, max lines per write_file call)
                        - telemetryEnabled (boolean)
                        
                        IMPORTANT: Setting allowedDirectories to an empty array ([]) allows full access 
                        to the entire file system, regardless of the operating system.
                        
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(SetConfigValueArgsSchema),
                annotations: {
                    title: "Set Configuration Value",
                    readOnlyHint: false,
                    destructiveHint: true,
                    openWorldHint: false,
                },
            },
            // Filesystem tools
            {
                name: "read_file",
                description: `
                        Read contents from files and URLs.
                        Read PDF files and extract content as markdown and images.
                        
                        Suitable for reading authorized local files directly without starting a shell command.
                        
                        Supports partial file reading with:
                        - 'offset' (start line, default: 0)
                          * Positive: Start from line N (0-based indexing)
                          * Negative: Read last N lines from end (tail behavior)
                        - 'length' (max lines to read, default: configurable via 'fileReadLineLimit' setting, initially 1000)
                          * Used with positive offsets for range reading
                          * Ignored when offset is negative (reads all requested tail lines)
                        
                        Examples:
                        - offset: 0, length: 10     → First 10 lines
                        - offset: 100, length: 5    → Lines 100-104
                        - offset: -20               → Last 20 lines  
                        - offset: -5, length: 10    → Last 5 lines (length ignored)
                        
                        Performance optimizations:
                        - Large files with negative offsets use reverse reading for efficiency
                        - Large files with deep positive offsets use byte estimation
                        - Small files use fast readline streaming
                        
                        When reading from the file system, only works within allowed directories.
                        Can fetch content from URLs when isUrl parameter is set to true
                        (URLs are always read in full regardless of offset/length).
                        
                        FORMAT HANDLING (by extension):
                        - Text: Uses offset/length for line-based pagination
                        - Excel (.xlsx, .xls, .xlsm): Returns JSON 2D array
                          * sheet: "Sheet1" (name) or "0" (index as string, 0-based)
                          * range uses FROM:TO format (e.g., "A1:D100", "C1:C1", "B2:B50")
                          * offset/length work as row pagination (optional fallback)
                        - Images (PNG, JPEG, GIF, WebP): Base64 encoded viewable content
                        - PDF: Extracts text content as markdown with page structure
                          * offset/length work as page pagination (0-based)
                          * Includes embedded images when available
                        - DOCX (.docx): Two modes depending on parameters:
                          * DEFAULT (no offset/length): Returns a text-bearing outline — shows paragraphs with text,
                            tables with cell content, styles, image refs. Skips shapes/drawings/SVG noise.
                            Each element shows its body index [0], [1], etc.
                          * WITH offset/length: Returns raw pretty-printed XML with line pagination.
                            Use this to drill into specific sections or see the actual XML for editing.
                          * Raw DOCX XML output is compatible with edit_block's XML find/replace mode using
                            XML fragments copied from the read output.
                          * Raw XML mode requires a non-zero offset (offset=1 starts from line 1).
                            offset=0 returns the outline regardless of length.
                          * Bulk transformations can be performed programmatically against the DOCX archive
                            when the task requires changes across many XML text nodes.

                        ${PATH_GUIDANCE}
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(ReadFileArgsSchema),
                _meta: buildUiToolMeta(FILE_PREVIEW_RESOURCE_URI, true, showMcpUiPreviews),
                annotations: {
                    title: "Read File or URL",
                    readOnlyHint: true,
                    openWorldHint: true,
                    destructiveHint: false,
                },
            },
            {
                name: "read_multiple_files",
                description: `
                        Read the contents of multiple files simultaneously.
                        
                        Each file's content is returned with its path as a reference.
                        Handles text files normally and renders images as viewable content.
                        Recognized image types: PNG, JPEG, GIF, WebP.
                        
                        Failed reads for individual files won't stop the entire operation.
                        Only works within allowed directories.
                        
                        ${PATH_GUIDANCE}
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(ReadMultipleFilesArgsSchema),
                annotations: {
                    title: "Read Multiple Files",
                    readOnlyHint: true,
                    openWorldHint: false,
                    destructiveHint: false,
                },
            },
            {
                name: "write_file",
                description: `
                        Write or append to file contents.

                        PDF creation is handled by the dedicated write_pdf tool.
                        Existing DOCX content can be edited with edit_block. New DOCX files can be created here; markdown headings (#, ##, ###) are converted to styled DOCX paragraphs.

                        CHUNKED WRITES:
                        - Repeated calls with mode='rewrite' followed by mode='append' are supported for longer files.
                        - Chunks of roughly 25-30 lines minimize latency when writing long text, multiple files, documentation, code, or configuration files.
                        - Files over 50 lines are still written successfully but may generate performance notes.
                        - For continuation after a partial write, the existing file state can be inspected before appending the remaining content.

                        FORMAT HANDLING (by extension):
                        - Text files: String content
                        - Excel (.xlsx, .xls, .xlsm): JSON 2D array or {"SheetName": [[...]]}
                          Example: '[["Name","Age"],["Alice",30]]'

                        Only works within allowed directories.

                        ${PATH_GUIDANCE}
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(WriteFileArgsSchema),
                _meta: buildUiToolMeta(FILE_PREVIEW_RESOURCE_URI, true, showMcpUiPreviews),
                annotations: {
                    title: "Write File",
                    readOnlyHint: false,
                    destructiveHint: true,
                    openWorldHint: false,
                },
            },
            {
                name: "write_pdf",
                description: `
                        Create a new PDF file or modify an existing one.

                        Dedicated PDF creation and modification tool.

                        OUTPUT FILES:
                        - Creating a PDF requires 'outputPath' with a new filename (e.g., "result_01.pdf", "analysis_2025_01.pdf", etc.).

                        MODES:
                        1. CREATE NEW PDF:
                           - Pass a markdown string as 'content'.
                           write_pdf(path="doc.pdf", content="# Title\\n\\nBody text...")

                        2. MODIFY EXISTING PDF:
                           - Pass array of operations as 'content'.
                           - Modifications preserve the original PDF and require a different filename in 'outputPath'.
                           - The result includes the original and output paths for reference.

                           write_pdf(path="doc.pdf", content=[
                               { type: "delete", pageIndexes: [0, 2] },
                               { type: "insert", pageIndex: 1, markdown: "# New Page" }
                           ])

                        OPERATIONS:
                        - delete: Remove pages by 0-based index.
                          { type: "delete", pageIndexes: [0, 1, 5] }

                        - insert: Add pages at a specific 0-based index.
                          { type: "insert", pageIndex: 0, markdown: "..." }
                          { type: "insert", pageIndex: 5, sourcePdfPath: "/path/to/source.pdf" }

                        PAGE BREAKS:
                        To force a page break, use this HTML element:
                        <div style="page-break-before: always;"></div>
                        
                        Example:
                        "# Page 1\\n\\n<div style=\\"page-break-before: always;\\"></div>\\n\\n# Page 2"

                        ADVANCED STYLING:
                        HTML/CSS and inline SVG are supported for:
                        - Text styling: colors, sizes, alignment, highlights
                        - Boxes: borders, backgrounds, padding, rounded corners
                        - SVG graphics: charts, diagrams, icons, shapes
                        - Images: <img src="/absolute/path/image.jpg" width="300" /> or ![alt](/path/image.jpg)

                        Supports standard markdown features including headers, lists, code blocks, tables, and basic formatting.

                        Only works within allowed directories.

                        ${PATH_GUIDANCE}
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(WritePdfArgsSchema),
                annotations: {
                    title: "Write/Modify PDF",
                    readOnlyHint: false,
                    destructiveHint: true,
                    openWorldHint: false,
                },
            },
            {
                name: "create_directory",
                description: `
                        Create a new directory or ensure a directory exists.
                        
                        Can create multiple nested directories in one operation.
                        Only works within allowed directories.
                        
                        ${PATH_GUIDANCE}
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(CreateDirectoryArgsSchema),
                annotations: {
                    title: "Create Directory",
                    readOnlyHint: false,
                    openWorldHint: false,
                    destructiveHint: false,
                },
            },
            {
                name: "list_directory",
                description: `
                        Get a detailed listing of all files and directories in a specified path.
                        
                        Returns a structured directory listing without starting a shell command.
                        Results distinguish between files and directories with [FILE] and [DIR] prefixes.
                        
                        Supports recursive listing with the 'depth' parameter (default: 2):
                        - depth=1: Only direct contents of the directory
                        - depth=2: Contents plus one level of subdirectories
                        - depth=3+: Multiple levels deep
                        
                        CONTEXT OVERFLOW PROTECTION:
                        - Top-level directory shows ALL items
                        - Nested directories are limited to 100 items maximum per directory
                        - When a nested directory has more than 100 items, you'll see a warning like:
                          [WARNING] node_modules: 500 items hidden (showing first 100 of 600 total)
                        - This prevents overwhelming the context with large directories like node_modules
                        
                        Results show full relative paths from the root directory being listed.
                        Example output with depth=2:
                        [DIR] src
                        [FILE] src/index.ts
                        [DIR] src/tools
                        [FILE] src/tools/filesystem.ts
                        
                        If a directory cannot be accessed, it will show [DENIED] instead.
                        If a path does not exist, it will show [NOT_FOUND] instead.
                        Only works within allowed directories.
                        
                        ${PATH_GUIDANCE}
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(ListDirectoryArgsSchema),
                _meta: buildUiToolMeta(FILE_PREVIEW_RESOURCE_URI, true, showMcpUiPreviews),
                annotations: {
                    title: "List Directory Contents",
                    readOnlyHint: true,
                    openWorldHint: false,
                    destructiveHint: false,
                },
            },
            {
                name: "move_file",
                description: `
                        Move or rename files and directories.
                        
                        Can move files between directories and rename them in a single operation.
                        Both source and destination must be within allowed directories.
                        
                        ${PATH_GUIDANCE}
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(MoveFileArgsSchema),
                annotations: {
                    title: "Move/Rename File",
                    readOnlyHint: false,
                    destructiveHint: true,
                    openWorldHint: false,
                },
            },
            {
                name: "start_search",
                description: `
                        Start a streaming search that can return results progressively.
                        
                        SEARCH STRATEGY GUIDE:
                        Choose the right search type based on what the user is looking for:
                        
                        USE searchType="files" WHEN:
                        - User asks for specific files: "find package.json", "locate config files"
                        - Pattern looks like a filename: "*.js", "README.md", "test-*.tsx" 
                        - User wants to find files by name/extension: "all TypeScript files", "Python scripts"
                        - Looking for configuration/setup files: ".env", "dockerfile", "tsconfig.json"
                        
                        USE searchType="content" WHEN:
                        - User asks about code/logic: "authentication logic", "error handling", "API calls"
                        - Looking for functions/variables: "getUserData function", "useState hook"
                        - Searching for text/comments: "TODO items", "FIXME comments", "documentation"
                        - Finding patterns in code: "console.log statements", "import statements"
                        - User describes functionality: "components that handle login", "files with database queries"
                        
                        AMBIGUOUS SEARCHES:
                        Queries that could refer to either filenames or file contents can be covered with two
                        searches: one with searchType="files" and one with searchType="content".
                        Example: "find authentication stuff" can pair a filename search for "auth" with a
                        content search for "authentication".
                        
                        SEARCH TYPES:
                        - searchType="files": Find files by name (pattern matches file names)
                        - searchType="content": Search inside files for text patterns
                        
                        PATTERN MATCHING MODES:
                        - Default (literalSearch=false): Patterns are treated as regular expressions
                        - Literal (literalSearch=true): Patterns are treated as exact strings
                        
                        literalSearch=true is useful for code patterns with special characters:
                        - Function calls with parentheses and quotes
                        - Array access with brackets
                        - Object methods with dots and parentheses
                        - File paths with backslashes
                        - Any pattern containing: . * + ? ^ $ { } [ ] | \\ ( )
                        
                        IMPORTANT PARAMETERS:
                        - pattern: What to search for (file names OR content text)
                        - literalSearch: Use exact string matching instead of regex (default: false)
                        - filePattern: Optional filter to limit search to specific file types (e.g., "*.js", "package.json")
                        - ignoreCase: Case-insensitive search (default: true). Works for both file names and content.
                        - earlyTermination: Stop search early when exact filename match is found (optional: defaults to true for file searches, false for content searches)
                        
                        DECISION EXAMPLES:
                        - "find package.json" → searchType="files", pattern="package.json" (specific file)
                        - "find authentication components" → searchType="content", pattern="authentication" (looking for functionality)
                        - "locate all React components" → searchType="files", pattern="*.tsx" or "*.jsx" (file pattern)
                        - "find TODO comments" → searchType="content", pattern="TODO" (text in files)
                        - "show me login files" → AMBIGUOUS → run both: files with "login" AND content with "login"
                        - "find config" → AMBIGUOUS → run both: config files AND files containing config code
                        
                        COMPREHENSIVE SEARCH EXAMPLES:
                        - Find package.json files: searchType="files", pattern="package.json"
                        - Find all JS files: searchType="files", pattern="*.js"
                        - Search for TODO in code: searchType="content", pattern="TODO", filePattern="*.js|*.ts"
                        - Search for exact code: searchType="content", pattern="toast.error('test')", literalSearch=true
                        - Ambiguous request "find auth stuff": Run two searches:
                          1. searchType="files", pattern="auth"
                          2. searchType="content", pattern="authentication"
                        
                        Ambiguous requests can combine file-name and content searches for broader coverage.
                        
                        This tool starts a background search process and returns immediately with a session ID.
                        Results are available through get_more_search_results, and stop_search can end the search early.
                        
                        Perfect for large directories where you want to see results immediately and
                        have the option to cancel if the search takes too long or you find what you need.
                        
                        ${PATH_GUIDANCE}
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(StartSearchArgsSchema),
                annotations: {
                    title: "Start Search",
                    readOnlyHint: true,
                    openWorldHint: false,
                    destructiveHint: false,
                },
            },
            {
                name: "get_more_search_results",
                description: `
                        Get more results from an active search with offset-based pagination.
                        
                        Supports partial result reading with:
                        - 'offset' (start result index, default: 0)
                          * Positive: Start from result N (0-based indexing)
                          * Negative: Read last N results from end (tail behavior)
                        - 'length' (max results to read, default: 100)
                          * Used with positive offsets for range reading
                          * Ignored when offset is negative (reads all requested tail results)
                        
                        Examples:
                        - offset: 0, length: 100     → First 100 results
                        - offset: 200, length: 50    → Results 200-249
                        - offset: -20                → Last 20 results
                        - offset: -5, length: 10     → Last 5 results (length ignored)
                        
                        Returns only results in the specified range, along with search status.
                        Works like read_process_output - call this repeatedly to get progressive
                        results from a search started with start_search.
                        
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(GetMoreSearchResultsArgsSchema),
                annotations: {
                    title: "Get Search Results",
                    readOnlyHint: true,
                    openWorldHint: false,
                    destructiveHint: false,
                },
            },
            {
                name: "stop_search",
                description: `
                        Stop an active search.
                        
                        Stops the background search process gracefully. Use this when you've found
                        what you need or if a search is taking too long. Similar to force_terminate
                        for terminal processes.
                        
                        The search will still be available for reading final results until it's
                        automatically cleaned up after 5 minutes.
                        
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(StopSearchArgsSchema),
                annotations: {
                    title: "Stop Search",
                    readOnlyHint: false,
                    openWorldHint: false,
                    destructiveHint: false,
                },
            },
            {
                name: "list_searches",
                description: `
                        List all active searches.
                        
                        Shows search IDs, search types, patterns, status, and runtime.
                        Similar to list_sessions for terminal processes. Useful for managing
                        multiple concurrent searches.
                        
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(ListSearchesArgsSchema),
                annotations: {
                    title: "List Active Searches",
                    readOnlyHint: true,
                    openWorldHint: false,
                    destructiveHint: false,
                },
            },
            {
                name: "get_file_info",
                description: `
                        Retrieve detailed metadata about a file or directory including:
                        - size
                        - creation time
                        - last modified time
                        - permissions
                        - type
                        - lineCount (for text files)
                        - lastLine (zero-indexed number of last line, for text files)
                        - appendPosition (line number for appending, for text files)
                        - sheets (for Excel files - array of {name, rowCount, colCount})

                        Only works within allowed directories.
                        
                        ${PATH_GUIDANCE}
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(GetFileInfoArgsSchema),
                annotations: {
                    title: "Get File Information",
                    readOnlyHint: true,
                    openWorldHint: false,
                    destructiveHint: false,
                },
            },
            // Note: list_allowed_directories removed - use get_config to check allowedDirectories
            // Editing tools
            {
                name: "edit_block",
                description: `
                        Apply surgical edits to files.

                        Small, focused edits are easier to verify than large multi-purpose replacements.
                        old_string can include enough surrounding context to uniquely identify the intended text.

                        FORMAT HANDLING (by extension):

                        EXCEL FILES (.xlsx, .xls, .xlsm) - Range Update mode:
                        Takes:
                        - file_path: Path to the Excel file
                        - range uses FROM:TO format - "SheetName!A1:C10" or "SheetName!C1:C1"
                        - content: 2D array, e.g., [["H1","H2"],["R1","R2"]]

                        TEXT FILES - Find/Replace mode:
                        Takes:
                        - file_path: Path to the file to edit
                        - old_string: Text to replace
                        - new_string: Replacement text
                        - expected_replacements: Optional number of replacements (default: 1)

                        DOCX FILES (.docx) - XML Find/Replace mode:
                        Takes same parameters as text files (old_string, new_string, expected_replacements).
                        Operates on the pretty-printed XML inside the DOCX — the same XML you see from
                        read_file with offset/length. Copy XML fragments from read output as old_string.
                        After editing, the XML is repacked into a valid DOCX.
                        Also searches headers/footers if not found in document body.
                        Examples:
                        - Replace text: old_string="<w:t>Old Text</w:t>" new_string="<w:t>New Text</w:t>"
                        - Change style: old_string='<w:pStyle w:val="Normal"/>' new_string='<w:pStyle w:val="Heading1"/>'
                        - Add content: include surrounding XML context in old_string, add new elements in new_string

                        By default, replaces only ONE occurrence of the search text.
                        To replace multiple occurrences, provide expected_replacements with
                        the exact number of matches expected.

                        UNIQUENESS REQUIREMENT: When expected_replacements=1 (default), include the minimal
                        amount of context necessary (typically 1-3 lines) before and after the change point,
                        with exact whitespace and indentation.

                        When editing multiple sections, make separate edit_block calls for each distinct change
                        rather than one large replacement.

                        When a close but non-exact match is found, a character-level diff is shown in the format:
                        common_prefix{-removed-}{+added+}common_suffix to help you identify what's different.

                        Similar to write_file, there is a configurable line limit (fileWriteLineLimit) that warns
                        if the edited file exceeds this limit. If this happens, consider breaking your edits into
                        smaller, more focused changes.

                        ${PATH_GUIDANCE}
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(EditBlockArgsSchema),
                _meta: buildUiToolMeta(FILE_PREVIEW_RESOURCE_URI, true, showMcpUiPreviews),
                annotations: {
                    title: "Edit Block",
                    readOnlyHint: false,
                    destructiveHint: true,
                    openWorldHint: false,
                },
            },
            // Terminal tools
            {
                name: "start_process",
                description: `
                        Start a terminal process on the authorized device with intelligent state detection.
                        
                        Suitable for shell commands, interactive REPL sessions, data-processing scripts,
                        programmatic file analysis, and other long-running terminal work.
                        
                        ${OS_GUIDANCE}
                        
                        Examples:
                        • start_process("python3 -i") → Start an interactive Python REPL
                        • start_process("node -i") → Start an interactive Node.js REPL
                        • start_process("node:local") → Run stateless Node.js code on the MCP server
                        • start_process("wc -l /path/file.csv") → Run a one-shot shell command

                        Interactive process sessions support follow-up input after they are started.
                        Long-running process sessions expose newly available output while they remain active.
                        Binary files can be processed with appropriate command-line tools or libraries available
                        in the selected process environment.

                        SMART DETECTION:
                        - Detects REPL prompts (>>>, >, $, etc.)
                        - Identifies when a process is waiting for input
                        - Recognizes process completion vs timeout
                        - Early exit prevents unnecessary waiting
                        
                        STATES DETECTED:
                        Process waiting for input (shows prompt)
                        Process finished execution
                        Process running (use read_process_output)

                        PERFORMANCE DEBUGGING (verbose_timing parameter):
                        Set verbose_timing: true to get detailed timing information including:
                        - Exit reason (early_exit_quick_pattern, early_exit_periodic_check, process_exit, timeout)
                        - Total duration and time to first output
                        - Complete timeline of all output events with timestamps
                        - Which detection mechanism triggered early exit

                        ${PATH_GUIDANCE}
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(StartProcessArgsSchema),
                annotations: {
                    title: "Start Terminal Process",
                    readOnlyHint: false,
                    destructiveHint: true,
                    openWorldHint: true,
                },
            },
            {
                name: "read_process_output",
                description: `
                        Read output from a running process with file-like pagination support.
                        
                        Supports partial output reading with offset and length parameters (like read_file):
                        - 'offset' (start line, default: 0)
                          * offset=0: Read NEW output since last read (default, like old behavior)
                          * Positive: Read from absolute line position
                          * Negative: Read last N lines from end (tail behavior)
                        - 'length' (max lines to read, default: configurable via 'fileReadLineLimit' setting)
                        
                        Examples:
                        - offset: 0, length: 100     → First 100 NEW lines since last read
                        - offset: 0                  → All new lines (respects config limit)
                        - offset: 500, length: 50    → Lines 500-549 (absolute position)
                        - offset: -20                → Last 20 lines (tail)
                        - offset: -50, length: 10    → Start 50 from end, read 10 lines
                        
                        OUTPUT PROTECTION:
                        - Uses same fileReadLineLimit as read_file (default: 1000 lines)
                        - Returns status like: [Reading 100 lines from line 0 (total: 5000 lines, 4900 remaining)]
                        - Prevents context overflow from verbose processes
                        
                        SMART FEATURES:
                        - For offset=0, waits up to timeout_ms for new output to arrive
                        - Detects REPL prompts and process completion
                        - Shows process state (waiting for input, finished, etc.)
                        
                        DETECTION STATES:
                        Process waiting for input (ready for interact_with_process)
                        Process finished execution
                        Timeout reached (may still be running)

                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(ReadProcessOutputArgsSchema),
                annotations: {
                    title: "Read Process Output",
                    readOnlyHint: true,
                    openWorldHint: false,
                    destructiveHint: false,
                },
            },
            {
                name: "interact_with_process",
                description: `
                        Send input to an existing terminal or REPL process and return newly available output.
                        
                        Useful for interactive shells, Python/Node/R/Julia REPLs, database consoles,
                        and long-running commands started with start_process().
                        
                        Examples:
                        - Interactive Python REPL sessions can be started with \`python3 -i\`.
                        - Existing interactive sessions accept additional input such as imports or analysis commands.
                        - Interactive sessions can return newly available output while they remain active.
                        
                        SMART DETECTION:
                        - Automatically waits for a recognized prompt when requested
                        - Detects errors and completion states
                        - Early exit prevents unnecessary waiting
                        - Cleans common REPL prompt text from returned output
                        
                        PARAMETERS:
                        - pid: Process ID returned by start_process
                        - input: Text or command to send to the process
                        - timeout_ms: Maximum wait time (default: 8000ms)
                        - wait_for_prompt: Whether to wait for a prompt before returning (default: true)
                        - verbose_timing: Include detailed timing telemetry (default: false)

                        Returns execution result with status indicators.

                        PERFORMANCE DEBUGGING (verbose_timing parameter):
                        When enabled, detailed timing includes:
                        - Exit reason
                        - Total duration and time to first output
                        - Timeline of output events

                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(InteractWithProcessArgsSchema),
                annotations: {
                    title: "Send Input to Process",
                    readOnlyHint: false,
                    destructiveHint: true,
                    openWorldHint: true,
                },
            },
            {
                name: "force_terminate",
                description: `
                        Force terminate a running terminal session.
                        
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(ForceTerminateArgsSchema),
                annotations: {
                    title: "Force Terminate Process",
                    readOnlyHint: false,
                    destructiveHint: true,
                    openWorldHint: false,
                },
            },
            {
                name: "list_sessions",
                description: `
                        List all active terminal sessions.
                        
                        Shows session status including:
                        - PID: Process identifier  
                        - Blocked: Whether session is waiting for input
                        - Runtime: How long the session has been running
                        
                        DEBUGGING REPLs:
                        - "Blocked: true" often means REPL is waiting for input
                        - Use this to verify sessions are running before sending input
                        - Long runtime with blocked status may indicate stuck process
                        
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(ListSessionsArgsSchema),
                annotations: {
                    title: "List Terminal Sessions",
                    readOnlyHint: true,
                    openWorldHint: false,
                    destructiveHint: false,
                },
            },
            {
                name: "list_processes",
                description: `
                        List all running processes.
                        
                        Returns process information including PID, command name, CPU usage, and memory usage.
                        
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(ListProcessesArgsSchema),
                annotations: {
                    title: "List Running Processes",
                    readOnlyHint: true,
                    openWorldHint: false,
                    destructiveHint: false,
                },
            },
            {
                name: "kill_process",
                description: `
                        Terminate a running process by PID.

                        Use with caution as this will forcefully terminate the specified process.

                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(KillProcessArgsSchema),
                annotations: {
                    title: "Kill Process",
                    readOnlyHint: false,
                    destructiveHint: true,
                    openWorldHint: false,
                },
            },
            {
                name: "get_usage_stats",
                description: `
                        Get usage statistics for debugging and analysis.
                        
                        Returns summary of tool usage, success/failure rates, and performance metrics.
                        
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(GetUsageStatsArgsSchema),
                annotations: {
                    title: "Get Usage Statistics",
                    readOnlyHint: true,
                    openWorldHint: false,
                    destructiveHint: false,
                },
            },
            {
                name: "get_recent_tool_calls",
                description: `
                        Get recent local tool call history with arguments and outputs.
                        Returns a chronological list of recent calls loaded from the local history file.
                        
                        Useful for:
                        - Onboarding new chats about work already done
                        - Recovering context after chat history loss
                        - Debugging tool call sequences
                        
                        Note: Does not track its own calls or track_ui_event.
                        History is persisted locally in tool-history.jsonl, keeps up to the last 1000
                        calls in memory, and trims older on-disk history. Stored outputs over 4 KiB
                        are replaced with an omission marker.
                        
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(GetRecentToolCallsArgsSchema),
                annotations: {
                    title: "Get Recent Tool Calls",
                    readOnlyHint: true,
                    openWorldHint: false,
                    destructiveHint: false,
                },
            },
            {
                name: "give_feedback_to_desktop_commander",
                description: `
                        Open feedback form in browser to provide feedback about Desktop Commander.
                        
                        The form itself collects survey answers; this tool does not accept survey responses or
                        pre-fill them. It automatically includes basic usage metadata:
                        - tool_call_count: Number of commands made
                        - days_using: Number of days Desktop Commander has been used
                        - platform: Operating system (Mac/Windows/Linux)
                        - client_id: Analytics identifier

                        No input parameters are required.
                        
                        ${CMD_PREFIX_DESCRIPTION}`,
                inputSchema: zodToJsonSchema(GiveFeedbackArgsSchema),
                annotations: {
                    title: "Give Feedback",
                    readOnlyHint: false,
                    openWorldHint: true,
                    destructiveHint: false,
                },
            },
        ];
        // Filter tools based on current client
        const filteredTools = allTools.filter(tool => shouldIncludeTool(tool.name));
        // logToStderr('debug', `Returning ${filteredTools.length} tools (filtered from ${allTools.length} total) for client: ${currentClient?.name || 'unknown'}`);
        return {
            tools: filteredTools,
        };
    }
    catch (error) {
        logToStderr('error', `Error in list_tools request handler: ${error}`);
        throw error;
    }
});
import * as handlers from './handlers/index.js';
import { withoutInternalFacts } from './utils/internal-facts.js';
import { stillLoadingError } from './utils/files/index.js';
/**
 * A tool call on an Excel, DOCX or PDF file whose package is still loading
 * after initialize answers at once with this error (utils/files/factory.ts)
 * instead of loading it inside the call. Not sent to telemetry, unlike other
 * errors: it names the file. read_multiple_files answers per file;
 * get_file_info waits for the load, or loads it itself, and so does a search.
 */
function stillLoading(filePath, action, options) {
    const error = typeof filePath === 'string' ? stillLoadingError(filePath, action, options) : undefined;
    return error === undefined ? undefined : { content: [{ type: 'text', text: `Error: ${error}` }], isError: true };
}
server.setRequestHandler(CallToolRequestSchema, async (request) => {
    const args = request.params.arguments;
    // Calls fired programmatically by the widget UIs (file preview, config
    // editor) carry origin:'ui'. They are real tool executions but not agent
    // actions, so they must produce zero telemetry: running them inside the
    // UI-origin capture context makes capture() drop every event they raise
    // (server_call_tool, server_read_file, server_edit_block, ...). Deliberate
    // UI interactions are tracked separately via mcp_ui_event.
    const isUiOriginCall = !!(args && typeof args === 'object' && args.origin === 'ui');
    // Each call keeps the paths it works on, starting with its path arguments,
    // so telemetry can replace them whole in any error text the call produces
    return runWithToolCallPaths(() => {
        addToolCallPaths(...pathArguments(args));
        if (isUiOriginCall) {
            return runInUiOriginCallContext(() => handleCallToolRequest(request));
        }
        return handleCallToolRequest(request);
    });
});
/** The values of the tool arguments that hold paths (path, paths, file_path, outputPath, source, destination, shell, ...). */
function pathArguments(args) {
    if (!args || typeof args !== 'object')
        return [];
    return Object.entries(args)
        .filter(([key]) => /path/i.test(key) || key === 'source' || key === 'destination' || key === 'shell')
        .map(([, value]) => value);
}
async function handleCallToolRequest(request) {
    const { name, arguments: args } = request.params;
    const startTime = Date.now();
    // Hoisted above the try so the finally block can read them when emitting the
    // server_call_tool completion event (duration + status), even on the crash path.
    let telemetryData = { tool_name: name };
    let result;
    let isError = false;
    try {
        // telemetryData declared above; extract metadata from _meta field if present
        const metadata = request.params._meta;
        // Reset remote attribution for every call so a prior remote call never
        // leaks its flag onto a subsequent local call. Set to true only when
        // this call carries the remote marker in _meta.
        const isRemoteCall = !!(metadata && typeof metadata === 'object' && metadata.remote);
        setCurrentCallIsRemote(isRemoteCall);
        if (isRemoteCall) {
            // add remote flag (convert to string for telemetry)
            telemetryData.remote = String(metadata.remote);
            // Remote calls carry the originating MCP client (e.g. openai-mcp,
            // claude-ai) in _meta.clientInfo. Attribute this call to that remote
            // client — NOT the device's own currentClient. Fall back to a sentinel
            // when it's absent so the call is visibly remote-but-unattributed
            // rather than masquerading as the local device client. We deliberately
            // do NOT call updateCurrentClient here: currentClient tracks the LOCAL
            // client and must not be polluted (nor its transport reconfigured) by
            // remote callers.
            const remoteClient = metadata.clientInfo && (metadata.clientInfo.name || metadata.clientInfo.version)
                ? metadata.clientInfo
                : { name: 'remote-unknown', version: 'unknown' };
            setCurrentRemoteClient(remoteClient);
            telemetryData.client_name = remoteClient.name;
            telemetryData.client_version = remoteClient.version;
        }
        else {
            // Local call — clear any remote attribution left by a prior call.
            setCurrentRemoteClient(null);
        }
        if (name === 'set_config_value' && args && typeof args === 'object' && 'key' in args) {
            telemetryData.set_config_value_key_name = args.key;
        }
        // Track tool call
        trackToolCall(name, args);
        // Using a more structured approach with dedicated handlers
        // (result is declared above so the finally block can read execution status)
        switch (name) {
            // Config tools
            case "get_config":
                try {
                    result = await getConfig();
                }
                catch (error) {
                    capture('server_request_error', { message: `Error in get_config handler: ${error}` });
                    result = {
                        content: [{ type: "text", text: `Error: Failed to get configuration` }],
                        isError: true,
                    };
                }
                break;
            case "set_config_value":
                try {
                    result = await setConfigValue(args);
                }
                catch (error) {
                    capture('server_request_error', { message: `Error in set_config_value handler: ${error}` });
                    result = {
                        content: [{ type: "text", text: `Error: Failed to set configuration value` }],
                        isError: true,
                    };
                }
                break;
            case "get_usage_stats":
                try {
                    result = await getUsageStats();
                }
                catch (error) {
                    capture('server_request_error', { message: `Error in get_usage_stats handler: ${error}` });
                    result = {
                        content: [{ type: "text", text: `Error: Failed to get usage statistics` }],
                        isError: true,
                    };
                }
                break;
            case "get_recent_tool_calls":
                try {
                    result = await handlers.handleGetRecentToolCalls(args);
                }
                catch (error) {
                    capture('server_request_error', { message: `Error in get_recent_tool_calls handler: ${error}` });
                    result = {
                        content: [{ type: "text", text: `Error: Failed to get tool call history` }],
                        isError: true,
                    };
                }
                break;
            case "track_ui_event":
                try {
                    result = await handlers.handleTrackUiEvent(args);
                }
                catch (error) {
                    capture('server_request_error', { message: `Error in track_ui_event handler: ${error}` });
                    result = {
                        content: [{ type: "text", text: `Error: Failed to track UI event` }],
                        isError: true,
                    };
                }
                break;
            case "give_feedback_to_desktop_commander":
                try {
                    result = await giveFeedbackToDesktopCommander(args);
                }
                catch (error) {
                    capture('server_request_error', { message: `Error in give_feedback_to_desktop_commander handler: ${error}` });
                    result = {
                        content: [{ type: "text", text: `Error: Failed to open feedback form` }],
                        isError: true,
                    };
                }
                break;
            // Terminal tools
            case "start_process":
                result = await handlers.handleStartProcess(args);
                break;
            case "read_process_output":
                result = await handlers.handleReadProcessOutput(args);
                break;
            case "interact_with_process":
                result = await handlers.handleInteractWithProcess(args);
                break;
            case "force_terminate":
                result = await handlers.handleForceTerminate(args);
                break;
            case "list_sessions":
                result = await handlers.handleListSessions();
                break;
            // Process tools
            case "list_processes":
                result = await handlers.handleListProcesses();
                break;
            case "kill_process":
                result = await handlers.handleKillProcess(args);
                break;
            // Note: REPL functionality removed in favor of using general terminal commands
            // Filesystem tools
            case "read_file":
                result = stillLoading(args?.path, 'read', { isUrl: args?.isUrl === true }) ?? await handlers.handleReadFile(args);
                break;
            case "read_multiple_files":
                result = await handlers.handleReadMultipleFiles(args, (filePath) => stillLoadingError(filePath, 'read'));
                break;
            case "write_file":
                result = stillLoading(args?.path, 'write') ?? await handlers.handleWriteFile(args);
                break;
            case "write_pdf": {
                // Markdown (a new PDF) or page edits, read as the tool reads them;
                // arguments the tool refuses get its own error
                const parsed = WritePdfArgsSchema.safeParse(args);
                const action = parsed.success && typeof parsed.data.content === 'string' ? 'write' : 'edit';
                result = (parsed.success ? stillLoading(parsed.data.path, action, { isPdf: true }) : undefined) ?? await handlers.handleWritePdf(args);
                break;
            }
            case "create_directory":
                result = await handlers.handleCreateDirectory(args);
                break;
            case "list_directory":
                result = await handlers.handleListDirectory(args);
                break;
            case "move_file":
                result = await handlers.handleMoveFile(args);
                break;
            case "start_search":
                result = await handlers.handleStartSearch(args);
                break;
            case "get_more_search_results":
                result = await handlers.handleGetMoreSearchResults(args);
                break;
            case "stop_search":
                result = await handlers.handleStopSearch(args);
                break;
            case "list_searches":
                result = await handlers.handleListSearches();
                break;
            case "get_file_info":
                result = await handlers.handleGetFileInfo(args);
                break;
            case "edit_block":
                result = stillLoading(args?.file_path, 'edit') ?? await handlers.handleEditBlock(args);
                break;
            default:
                capture('server_unknown_tool', { name });
                result = {
                    content: [{ type: "text", text: `Error: Unknown tool: ${name}` }],
                    isError: true,
                };
        }
        // What the client receives (and the history records): facts kept internal are dropped
        result = withoutInternalFacts(name, result);
        // Add tool call to history (exclude only get_recent_tool_calls to prevent recursion)
        const duration = Date.now() - startTime;
        isError = !!result.isError;
        const EXCLUDED_TOOLS = [
            'get_recent_tool_calls',
            'track_ui_event'
        ];
        if (!EXCLUDED_TOOLS.includes(name)) {
            toolHistory.addCall(name, args, result, duration);
        }
        // Track success or failure based on result
        if (name === 'track_ui_event') {
            return result;
        }
        if (result.isError) {
            await usageTracker.trackFailure(name);
            console.log(`[FEEDBACK DEBUG] Tool ${name} failed, not checking feedback`);
        }
        else {
            await usageTracker.trackSuccess(name);
            console.log(`[FEEDBACK DEBUG] Tool ${name} succeeded, checking feedback...`);
            // Check if should prompt for feedback (only on successful operations)
            const shouldPrompt = await usageTracker.shouldPromptForFeedback();
            console.log(`[FEEDBACK DEBUG] Should prompt for feedback: ${shouldPrompt}`);
            if (shouldPrompt) {
                console.log(`[FEEDBACK DEBUG] Generating feedback message...`);
                const feedbackResult = await usageTracker.getFeedbackPromptMessage();
                console.log(`[FEEDBACK DEBUG] Generated variant: ${feedbackResult.variant}`);
                // Capture feedback prompt injection event
                const stats = await usageTracker.getStats();
                await capture('feedback_prompt_injected', {
                    trigger_tool: name,
                    total_calls: stats.totalToolCalls,
                    successful_calls: stats.successfulCalls,
                    failed_calls: stats.failedCalls,
                    days_since_first_use: Math.floor((Date.now() - stats.firstUsed) / (1000 * 60 * 60 * 24)),
                    total_sessions: stats.totalSessions,
                    message_variant: feedbackResult.variant
                });
                // Inject feedback instruction for the LLM
                if (result.content && result.content.length > 0 && result.content[0].type === "text") {
                    const currentContent = result.content[0].text || '';
                    result.content[0].text = `${currentContent}${feedbackResult.message}`;
                }
                else {
                    result.content = [
                        ...(result.content || []),
                        {
                            type: "text",
                            text: feedbackResult.message
                        }
                    ];
                }
                // Mark that we've prompted (to prevent spam)
                await usageTracker.markFeedbackPrompted();
            }
            // Check if should prompt about Docker environment
            result = await processDockerPrompt(result, name);
        }
        // If the caller sent parameters this tool does not support, Zod silently
        // strips them. Prepend a corrective warning so the model knows they were
        // ignored and which parameters are actually supported.
        try {
            const argSchema = toolArgSchemas[name];
            if (argSchema && result && Array.isArray(result.content)) {
                const unsupported = detectUnsupportedParams(args, argSchema);
                if (unsupported.length > 0) {
                    const warning = buildUnsupportedParamsWarning(name, unsupported, getSupportedParams(argSchema));
                    result.content = [
                        { type: "text", text: warning },
                        ...result.content,
                    ];
                }
            }
        }
        catch {
            // Never let the advisory warning break an otherwise-successful call.
        }
        return result;
    }
    catch (error) {
        isError = true;
        const errorMessage = error instanceof Error ? error.message : String(error);
        // Track the failure
        await usageTracker.trackFailure(name);
        capture('server_request_error', {
            error: errorMessage
        });
        return {
            content: [{ type: "text", text: `Error: ${errorMessage}` }],
            isError: true,
        };
    }
    finally {
        // Single tool-call telemetry event, fired AFTER execution so it can carry
        // timing. In a finally so it still fires on the hard-crash path (the catch
        // above). Only missed if a tool never returns or throws (a true hang).
        // Not emitted for track_ui_event (it is just the transport for
        // mcp_ui_event) — and UI-origin calls are dropped wholesale by the
        // capture layer, so server_call_tool reflects only genuine
        // agent-driven tool calls.
        if (name !== 'track_ui_event') {
            capture_call_tool('server_call_tool', {
                ...telemetryData,
                duration_ms: Date.now() - startTime,
                is_error: String(isError),
            });
        }
    }
}
// Add no-op handlers so Visual Studio initialization succeeds
server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({ resourceTemplates: [] }));