# Desktop Commander Tool Specifications

## 📋 TOOL CATALOG

Detailed specifications for all 31 Desktop Commander tools to be absorbed into KERNL V2.0.

**Purpose**: Implementation guide for each tool  
**Usage**: Reference during Phase 2-6 implementation

---

## 🎯 PHASE 2: REVOLUTIONARY TOOLS (6 tools)

### 1. `edit_block` ⭐ HIGHEST PRIORITY

**Category**: System Control  
**New Name**: `sys_edit_block`  
**Value**: Game-changer for code editing

**Description**: Surgical find/replace editing of files. Much more precise than full rewrites.

**Parameters**:
```typescript
interface EditBlockParams {
  file_path: string;           // Path to file
  old_string: string;          // Text to find (must be unique)
  new_string: string;          // Replacement text
  expected_replacements?: number; // Expected match count (default: 1)
}
```

**Capabilities**:
- Find exact text match in file
- Replace with new text
- Verify expected number of replacements
- Character-level diff on near-matches
- Works with any text file

**Use Cases**:
- Fix specific function without rewriting file
- Update configuration values precisely
- Modify imports/dependencies
- Correct specific bugs

**Implementation Notes**:
- Read file content
- Search for exact match
- Validate replacement count
- Write back modified content
- Show diff on success
- Error on multiple unexpected matches

**Testing**:
- Test with single match
- Test with multiple matches
- Test with no matches
- Test with near matches (diff display)
- Test with large files

---

### 2. `write_pdf` ⭐ HIGH PRIORITY

**Category**: System Control  
**New Name**: `sys_write_pdf`  
**Value**: Enable PDF creation/modification

**Description**: Create new PDFs from markdown or modify existing PDFs.

**Parameters**:
```typescript
interface WritePdfParams {
  path: string;                // Output PDF path
  content: string | PdfOperation[]; // Markdown or operations
  outputPath?: string;         // For modifications (new filename)
  options?: PdfOptions;        // PDF options (margins, etc.)
}

interface PdfOperation {
  type: 'insert' | 'delete';
  pageIndex?: number;          // For insert
  pageIndexes?: number[];      // For delete
  markdown?: string;           // For insert
  sourcePdfPath?: string;      // For insert from PDF
}
```

**Capabilities**:
- Create PDFs from markdown
- Insert pages at specific positions
- Delete pages by index
- Merge PDFs
- Force page breaks with HTML
- Advanced styling with HTML/CSS
- Inline SVG support
- Image embedding

**Use Cases**:
- Generate reports from markdown
- Create documentation PDFs
- Modify existing PDFs (add/remove pages)
- Merge multiple PDFs
- Style reports with HTML/CSS

**Implementation Notes**:
- Use `pdf-lib` (already in dependencies)
- Support markdown → HTML → PDF pipeline
- Handle page breaks properly
- Validate page indexes
- Never overwrite originals (use outputPath)

**Testing**:
- Create simple PDF from markdown
- Create multi-page PDF
- Insert pages
- Delete pages
- Test page breaks
- Test styling

---

### 3. `start_process` ⭐ HIGH PRIORITY

**Category**: Process Management  
**New Name**: `sys_start_process`  
**Value**: Enable REPL integration and command execution

**Description**: Start terminal process with smart state detection.

**Parameters**:
```typescript
interface StartProcessParams {
  command: string;             // Command to execute
  timeout_ms: number;          // Max wait time
  shell?: string;              // Shell override (powershell/cmd/bash)
  verbose_timing?: boolean;    // Debug timing info
}
```

**Capabilities**:
- Detect REPL prompts (>>>, >, $, etc.)
- Identify when process waiting for input
- Recognize process completion
- Early exit prevents timeout delays
- Support for Python, Node.js, R, Julia, shell

**States Detected**:
- Process waiting for input (shows prompt)
- Process finished execution
- Process running (use read_process_output)

**Use Cases**:
- Start Python REPL for data analysis
- Start Node.js REPL for calculations
- Execute long-running commands
- Launch interactive shells

**Implementation Notes**:
- Use Node.js `child_process`
- Implement prompt detection patterns
- Track process state in database
- Return process ID for future interactions
- Handle shell differences (PowerShell vs bash)

**Testing**:
- Start Python REPL
- Start Node.js REPL
- Execute simple command
- Test timeout
- Test shell override

---

### 4. `interact_with_process` ⭐ HIGH PRIORITY

**Category**: Process Management  
**New Name**: `sys_interact_with_process`  
**Value**: Primary tool for data analysis with local files

**Description**: Send input to running process and receive response.

**Parameters**:
```typescript
interface InteractParams {
  pid: number;                 // Process ID
  input: string;               // Command/code to send
  timeout_ms?: number;         // Max wait (default: 8000ms)
  wait_for_prompt?: boolean;   // Auto-wait for REPL prompt (default: true)
  verbose_timing?: boolean;    // Debug timing
}
```

**Capabilities**:
- Send commands to REPL
- Auto-wait for prompt
- Detect errors/completion
- Clean output formatting
- Works with Python, Node, R, Julia, shells

**Use Cases**:
- Load CSV files in Python: `import pandas as pd; df = pd.read_csv('file.csv')`
- Analyze data: `print(df.describe())`
- Run calculations: `Math.sqrt(16)`
- Execute multi-line code

**Implementation Notes**:
- Send input to stdin
- Monitor stdout/stderr
- Detect prompt patterns
- Strip prompt from output
- Handle timing carefully (early exit)

**Testing**:
- Python: import library, read CSV, analyze
- Node.js: calculations, JSON processing
- Shell: simple commands
- Error handling
- Timeout behavior

---

### 5. `read_process_output` ⭐ HIGH PRIORITY

**Category**: Process Management  
**New Name**: `sys_read_process_output`  
**Value**: Monitor long-running processes

**Description**: Read output from running process with pagination.

**Parameters**:
```typescript
interface ReadProcessOutputParams {
  pid: number;                 // Process ID
  offset?: number;             // Start line (default: 0 = new output)
  length?: number;             // Max lines (default: config limit)
  timeout_ms?: number;         // Wait time for new output
  verbose_timing?: boolean;    // Debug timing
}
```

**Capabilities**:
- Read new output since last read (offset=0)
- Read absolute position (offset > 0)
- Read last N lines (offset < 0)
- Pagination support
- Detect process state (waiting/finished)

**Use Cases**:
- Monitor long-running command
- Read incremental output
- Get latest logs
- Check process status

**Implementation Notes**:
- Track read position per process
- Support pagination
- Detect REPL prompts
- Show process state
- Respect config line limits

**Testing**:
- Read new output (offset=0)
- Read specific range
- Read last N lines (offset < 0)
- Test pagination
- Test with large output

---

### 6. `copy_file_user_to_claude` ⭐ HIGH PRIORITY

**Category**: System Control  
**New Name**: `sys_copy_file_user_to_claude`  
**Value**: Bridge between user and Claude filesystems

**Description**: Copy file from user's filesystem to Claude's filesystem.

**Parameters**:
```typescript
interface CopyFileParams {
  path: string;                // User filesystem path
}
```

**Capabilities**:
- Copy files from user's D:\ drive to Claude's /home/claude
- Enable analysis of user files with Claude's tools
- Automatic path mapping

**Use Cases**:
- User uploads file, Claude needs to process
- Large files that can't fit in context
- Binary files needing special processing
- Cross-filesystem operations

**Implementation Notes**:
- Read from user filesystem
- Write to Claude filesystem
- Handle path translation
- Preserve file attributes
- Return Claude-side path

**Testing**:
- Copy text file
- Copy binary file
- Copy large file
- Test path translation
- Verify file integrity

---

## 🔧 PHASE 3: ENHANCED FILE OPERATIONS (5 enhancements)

### 7-11. Enhanced File Operations

These are MERGES, not new tools. Enhance existing KERNL tools with DC capabilities.

#### 7. Enhance `pm_read_file` ⚠️ MERGE

**Add from DC**:
- `offset` parameter - Start line (positive/negative for tail)
- `length` parameter - Max lines to read
- Excel support - Read .xlsx/.xls/.xlsm files
- PDF support - Read .pdf files as markdown
- Image support - Base64 encode images

**New Signature**:
```typescript
interface PmReadFileParams {
  project: string;             // KERNL addition
  path: string;
  offset?: number;             // DC addition
  length?: number;             // DC addition  
  sheet?: string;              // DC addition (Excel)
  range?: string;              // DC addition (Excel)
}
```

---

#### 8. Enhance `pm_write_file` ⚠️ MERGE

**Add from DC**:
- Automatic chunking for large files
- Excel support - Write .xlsx files
- `mode` parameter - 'rewrite' or 'append'

**New Signature**:
```typescript
interface PmWriteFileParams {
  project: string;             // KERNL addition
  path: string;
  content: string | ExcelData;
  mode?: 'rewrite' | 'append'; // DC addition
}
```

---

#### 9. Enhance `pm_list_files` ⚠️ MERGE

**Add from DC**:
- `depth` parameter - Recursive listing depth
- Per-directory item limits (100 max)
- [DIR] and [FILE] prefixes

**New Signature**:
```typescript
interface PmListFilesParams {
  project: string;             // KERNL addition
  path: string;
  depth?: number;              // DC addition (default: 2)
}
```

---

#### 10. Enhance `pm_get_file_info` ⚠️ MERGE

**Add from DC**:
- `lineCount` - Total lines in file
- `lastLine` - Zero-indexed last line number
- `appendPosition` - Line number for appending
- `sheets` - For Excel files

**Enhanced Return**:
```typescript
interface FileInfo {
  // Existing fields...
  lineCount?: number;          // DC addition
  lastLine?: number;           // DC addition
  appendPosition?: number;     // DC addition
  sheets?: SheetInfo[];        // DC addition
}
```

---

#### 11. Merge `pm_batch_read` + `read_multiple_files` ⚠️ MERGE

**Strategy**: Keep `pm_batch_read`, enhance with DC capabilities

**No signature change** - just improve implementation

---

## 🔍 PHASE 4: SEARCH CAPABILITIES (4 tools)

### 12. `start_search`

**Category**: Advanced Search  
**New Name**: `sys_start_search`

**Description**: Start streaming search (files or content) with pagination.

**Parameters**:
```typescript
interface StartSearchParams {
  path: string;                // Search root
  pattern: string;             // Search pattern
  searchType?: 'files' | 'content'; // Default: 'files'
  filePattern?: string;        // File filter (*.js)
  literalSearch?: boolean;     // Exact match vs regex
  ignoreCase?: boolean;        // Case-insensitive (default: true)
  includeHidden?: boolean;     // Include hidden files
  maxResults?: number;         // Result limit
  timeout_ms?: number;         // Search timeout
  contextLines?: number;       // Lines of context (content search)
  earlyTermination?: boolean;  // Stop on exact filename match
}
```

**Returns**: Session ID for pagination

---

### 13. `get_more_search_results`

**Category**: Advanced Search  
**New Name**: `sys_get_more_search_results`

**Description**: Get paginated results from active search.

**Parameters**:
```typescript
interface GetMoreResultsParams {
  sessionId: string;           // From start_search
  offset?: number;             // Start result index (default: 0)
  length?: number;             // Max results (default: 100)
}
```

---

### 14. `stop_search`

**Category**: Advanced Search  
**New Name**: `sys_stop_search`

**Description**: Cancel active search.

**Parameters**:
```typescript
interface StopSearchParams {
  sessionId: string;
}
```

---

### 15. `list_searches`

**Category**: Advanced Search  
**New Name**: `sys_list_searches`

**Description**: List all active searches.

**Parameters**: None

**Returns**: Array of search sessions with status

---

## ⚙️ PHASE 5: PROCESS MANAGEMENT (4 tools)

### 16-19. Process Control Suite

#### 16. `force_terminate`

**New Name**: `sys_force_terminate`

**Parameters**:
```typescript
interface ForceTerminateParams {
  pid: number;
}
```

---

#### 17. `list_sessions`

**New Name**: `sys_list_sessions`

**Parameters**: None

**Returns**: Active terminal sessions with status

---

#### 18. `list_processes`

**New Name**: `sys_list_processes`

**Parameters**: None

**Returns**: System processes (PID, name, CPU, memory)

---

#### 19. `kill_process`

**New Name**: `sys_kill_process`

**Parameters**:
```typescript
interface KillProcessParams {
  pid: number;
}
```

---

## 🎛️ PHASE 6: CONFIGURATION (4 tools)

### 20-23. Configuration Suite

#### 20. `get_config`

**New Name**: `sys_get_config`

**Parameters**: None

**Returns**: Complete server configuration

---

#### 21. `set_config_value`

**New Name**: `sys_set_config_value`

**Parameters**:
```typescript
interface SetConfigParams {
  key: string;                 // Config key
  value: any;                  // New value
}
```

---

#### 22. `get_usage_stats`

**New Name**: `sys_get_usage_stats`

**Parameters**: None

**Returns**: Tool usage statistics

---

#### 23. `get_recent_tool_calls`

**New Name**: `sys_get_recent_tool_calls`

**Parameters**:
```typescript
interface GetRecentToolCallsParams {
  maxResults?: number;         // Default: 50
  toolName?: string;           // Filter by tool
  since?: string;              // ISO datetime
}
```

---

## 📦 PHASE 6: REMAINING TOOLS (8 tools)

### 24-31. Utility Tools

#### 24. `list_allowed_directories`

**New Name**: `sys_list_allowed_directories`

**Parameters**: None

**Returns**: Array of accessible paths

---

#### 25. `create_directory`

**New Name**: `sys_create_directory` (or enhance existing)

**Parameters**:
```typescript
interface CreateDirParams {
  path: string;
}
```

---

#### 26. `move_file`

**New Name**: `sys_move_file`

**Parameters**:
```typescript
interface MoveFileParams {
  source: string;
  destination: string;
}
```

---

#### 27. `get_prompts`

**New Name**: `sys_get_prompts`

**Parameters**:
```typescript
interface GetPromptsParams {
  action: 'get_prompt';
  promptId: string;
}
```

---

## 📝 IMPLEMENTATION CHECKLIST

For each tool:

- [ ] Read this specification
- [ ] Create tool definition in appropriate file
- [ ] Implement handler function
- [ ] Register in mcp-server.ts
- [ ] Add to database schema if needed
- [ ] Write unit tests
- [ ] Write integration tests
- [ ] Update TOOL_REFERENCE.md
- [ ] Test manually
- [ ] Verify TypeScript compiles
- [ ] Create examples
- [ ] Document edge cases

---

## 🎯 PRIORITY ORDER

**Implement in this order** (highest value first):

1. ⭐ `edit_block` - Revolutionary editing
2. ⭐ `write_pdf` - PDF capabilities
3. ⭐ `start_process` - REPL foundation
4. ⭐ `interact_with_process` - REPL control
5. ⭐ `read_process_output` - Process monitoring
6. ⭐ `copy_file_user_to_claude` - Filesystem bridge
7. 📁 Enhanced file operations (5 merges)
8. 🔍 Search suite (4 tools)
9. ⚙️ Process suite (4 tools)
10. 🎛️ Configuration suite (4 tools)
11. 📦 Utility tools (remaining)

---

*Tool Specifications v1.0*  
*Created: January 7, 2026*  
*Purpose: Implementation guide for V2.0 absorption*
