How Desktop Commander MCP Detects Process States and REPL Prompts

Desktop Commander MCP detects process states by analyzing stdout/stderr output against a curated catalogue of REPL prompt strings, completion indicators, and error patterns to determine whether a spawned process is waiting for input, has finished, or is still running.

Desktop Commander MCP provides intelligent interaction with terminal processes by automatically detecting when a command-line tool is waiting for user input at a REPL prompt versus when it has completed execution. The process state detection engine, implemented in TypeScript, enables the Model Context Protocol (MCP) server to manage long-running interactive sessions without hanging or premature termination. According to the wonderwhy-er/DesktopCommanderMCP source code, the core logic resides in src/utils/process-detection.ts and integrates with the terminal manager to make real-time decisions about process lifecycle.

The REPL Prompt Detection Architecture

The detection system relies on pattern matching against known REPL signatures rather than OS-level process inspection. This approach works across languages and shells without requiring platform-specific APIs.

The Prompt Catalogue (REPL_PROMPTS)

At the heart of the detection system is a static map called REPL_PROMPTS that enumerates common prompt strings for popular interactive environments. Located in src/utils/process-detection.ts, this catalogue covers Python (>>>), Node.js (>), R (>), Julia (julia>), bash/zsh ($, #), MySQL (mysql>), PostgreSQL (postgres=#), Redis (127.0.0.1:6379>), MongoDB (>), and numerous other REPLs.

The system checks the last line (and last three lines) of process output to see if it ends with or contains any string from this catalogue. When matched, the process is marked as waiting for input.

Completion and Error Pattern Matching

Beyond prompt detection, the system maintains two additional pattern arrays in src/utils/process-detection.ts:

  • COMPLETION_INDICATORS: Regular expressions that match typical termination messages indicating a process has finished naturally
  • ERROR_COMPLETION_PATTERNS: Regular expressions that detect error traces and stack dumps that might signal completion even when exit codes aren't immediately available

These patterns enable Desktop Commander to detect process states even when dealing with complex error output that might otherwise confuse simple prompt detection.

The analyzeProcessState Algorithm

The exported function analyzeProcessState(output, pid?) implements the core state machine that evaluates captured stdout/stderr text. According to the source code, the algorithm follows this cascading decision tree:

  1. Empty output: If no output exists, the process is assumed to be running with no clear state
  2. Prompt detection: Examines the last line and last three lines for REPL_PROMPTS matches. A hit marks the state as waiting for input
  3. Completion check: If no prompt found, tests against COMPLETION_INDICATORS. A match marks the process as finished
  4. Error evaluation: Checks ERROR_COMPLETION_PATTERNS to determine if an error indicates the process is still at a prompt or has terminated
  5. Default fallback: When no patterns match, returns running

This multi-layered approach ensures accurate process state detection across diverse toolchains and output formats.

Output Sanitization and User Feedback

Before presenting process output to the user, Desktop Commander cleans raw stdout/stderr using cleanProcessOutput. This function removes echoed input and common prompt symbols to prevent redundant display of the REPL markers themselves.

For status reporting, formatProcessStateMessage generates human-readable strings based on the ProcessState object. For example, when Python's >>> prompt is detected, it produces messages like "Process 1234 is waiting for input (detected: ">>>")".

Integration with Terminal Management

The process detection logic integrates at two critical points in the codebase:

Terminal Manager (src/terminal-manager.ts): Reads child process output and calls analyzeProcessState to decide whether to pause for additional input or consider the command finished. This prevents the MCP server from returning prematurely when a REPL is waiting for the next line of code.

Improved Process Tools (src/tools/improved-process-tools.ts): Higher-level utilities like interact_with_process rely on the same detection function to feed REPL logic into interactive commands, enabling seamless conversation with database clients, language shells, and debugging tools.

Practical Implementation Example

Here's how to use the detection utilities when building custom process interactions:

import {
  analyzeProcessState,
  cleanProcessOutput,
  formatProcessStateMessage,
  ProcessState,
} from './utils/process-detection.js';

// Capture raw output from a child process (e.g., a Python REPL)
const rawOutput = await terminalManager.readProcessOutput(pid);

// Determine the current state
const state: ProcessState = analyzeProcessState(rawOutput, pid);

// Clean the output for presentation
const cleaned = cleanProcessOutput(rawOutput);

// Show a concise status message
console.log(formatProcessStateMessage(state, pid));

// Decision flow based on detected state
if (state.isWaitingForInput) {
  await terminalManager.sendInputToProcess(pid, userInput + '\n');
} else if (state.isFinished) {
  console.log('Process finished – no further input required.');
} else {
  console.log('Process still running…');
}

This pattern enables robust handling of interactive sessions where simple process exit monitoring would fail.

Summary

  • Desktop Commander MCP detects process states through text pattern analysis rather than OS signals, making it portable across platforms
  • The REPL_PROMPTS catalogue in src/utils/process-detection.ts recognizes over a dozen common interactive shells and tools by their distinctive prompt strings
  • The analyzeProcessState function implements a cascading decision tree: check for prompts first, then completion indicators, then error patterns, defaulting to "running" if none match
  • Integration points in src/terminal-manager.ts and src/tools/improved-process-tools.ts enable automatic detection of when to wait for user input versus when to return results to the LLM
  • Output cleaning via cleanProcessOutput ensures that echoed prompts don't clutter the final output presented to users

Frequently Asked Questions

How does Desktop Commander MCP distinguish between a REPL prompt and regular output?

Desktop Commander examines the last line (and last three lines) of stdout/stderr output to see if it ends with or contains strings defined in the REPL_PROMPTS map. If the output matches known patterns like Python's >>> or Node's >, the system marks the process as waiting for input. Regular command output that doesn't match these terminal-specific signatures is treated as either running or finished based on other completion indicators.

What happens if a process outputs text that looks like a prompt but isn't one?

The detection system uses a curated list of specific prompt strings rather than heuristic guessing, minimizing false positives. However, if ambiguous output occurs, the default fallback state is "running" rather than "waiting for input," ensuring the MCP server continues monitoring rather than hanging indefinitely. The multi-line context check (examining the last three lines) also helps reduce misidentification of mid-stream content as prompts.

Can the process detection handle errors that don't return standard exit codes?

Yes. The ERROR_COMPLETION_PATTERNS array in src/utils/process-detection.ts contains regular expressions designed to recognize stack traces and error messages that indicate a process has terminated, even when the exit code might not be immediately available to the parent process. This allows Desktop Commander to detect completion states in languages like Python or Node.js that may print exceptions to stderr before terminating.

Which file contains the core logic for detecting if a process is waiting for input?

The core detection logic resides in src/utils/process-detection.ts, specifically within the analyzeProcessState function. This file also exports cleanProcessOutput and formatProcessStateMessage for sanitizing output and generating status messages. The function is consumed by src/terminal-manager.ts and src/tools/improved-process-tools.ts to manage interactive sessions.

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 →