CLAUDE.mdโข7.78 kB
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
This is an MCP (Model Context Protocol) server that provides cut, copy, paste, and undo operations for AI-assisted coding agents. The server is designed to be NPX-runnable and uses SQLite for session management and operation logging.
## Strict TDD Development Process
**This project MUST follow Test-Driven Development strictly.** All implementation follows the Red-Green-Refactor cycle:
1. **RED**: Write failing tests first
2. **GREEN**: Implement minimum code to pass tests
3. **REFACTOR**: Improve code while keeping tests green
**Never write implementation code before writing the test.** Refer to [TODO.md](TODO.md) for the detailed phase-by-phase TDD implementation plan.
## Development Commands
Since the project is not yet initialized, these commands will be needed once setup is complete:
```bash
# Install dependencies
npm install
# Run all tests
npm test
# Run tests in watch mode
npm test -- --watch
# Run specific test file
npm test -- path/to/test-file.test.ts
# Build TypeScript
npm run build
# Run linter
npm run lint
# Start MCP server (after build)
npx cut-copy-paste-mcp
```
## Architecture Overview
### Core Design Philosophy
The server follows a **layered architecture** with clear separation of concerns:
```
MCP Server Layer (protocol handling)
โ
Tool Handlers (copy, cut, paste, undo, show_clipboard, get_history)
โ
Business Logic Layer (SessionManager, ClipboardManager, FileHandler, OperationLogger)
โ
Data Layer (SQLite database)
```
### Key Components
**1. Session Manager**
- Creates and manages session lifecycle
- Tracks session activity timestamps
- Cleans up expired sessions (24h timeout)
- Session ID is cryptographically secure
**2. Clipboard Manager**
- One clipboard buffer per session (stored in SQLite)
- Stores content + metadata (source file, line range, operation type)
- Supports copy and cut operations
- Clipboard persists for session lifetime
**3. File Handler**
- Reads/writes file operations with 1-indexed line numbers (converts internally to 0-indexed)
- Atomic write operations with backup support
- Validates file permissions before operations
- Preserves original line endings
**4. Operation Logger**
- SQLite-based audit trail for all operations
- Links operations to sessions
- Stores content snapshots for undo capability
- Supports operation history queries
### Database Schema
Four main tables (see [TODO.md](TODO.md) for complete schema):
- `sessions`: Session tracking
- `clipboard_buffer`: Per-session clipboard state
- `operations_log`: Audit trail of all operations
- `paste_history`: Enables undo functionality (only paste operations are undoable)
### MCP Tools
Six tools exposed via MCP protocol:
1. `copy_lines`: Copy lines without modifying source
2. `cut_lines`: Cut lines (removes from source)
3. `paste_lines`: Paste to one or multiple targets
4. `show_clipboard`: View current clipboard contents
5. `undo_last_paste`: Revert most recent paste
6. `get_operation_history`: Retrieve operation audit trail
## Critical Design Decisions
1. **Line Numbers**: 1-indexed externally (matching editors), 0-indexed internally
2. **Undo Scope**: Only paste operations are undoable (v1 = single level undo)
3. **Transport**: stdio transport only (v1)
4. **File Types**: Text files only, reject binary files
5. **Clipboard Size**: 10MB maximum
6. **Session Timeout**: 24 hours default
7. **Concurrency**: File-level operation queuing to prevent conflicts
8. **Path Handling**: Support absolute and relative paths (resolve relative to working directory)
## TDD Implementation Workflow
When implementing any feature:
1. **Find your phase in TODO.md** - Each phase has RED/GREEN/REFACTOR steps
2. **RED Phase**: Write all tests listed, ensure they fail
3. **GREEN Phase**: Implement minimal code to pass all tests
4. **REFACTOR Phase**: Improve code quality while keeping tests green
5. **Never skip phases** - Always complete the full cycle
Example from Phase 1 (Session Manager):
```
Phase 1.1 (RED) โ Write failing tests for session creation
Phase 1.2 (GREEN) โ Implement SessionManager.createSession()
Phase 1.3 (REFACTOR) โ Optimize and extract utilities
```
## Documentation Requirements
**ARCHITECTURE.md**
- Document all major architectural decisions as they're implemented
- Include component interaction diagrams
- Explain data flow patterns
- Document any deviations from TODO.md plan
**README.md**
- Keep user-facing installation instructions updated
- Document MCP tool usage with examples
- Include quickstart guide
- Add troubleshooting section
Both files should be updated incrementally as features are completed, not at the end.
## Testing Standards
- Minimum 90% code coverage required
- Integration tests for complete workflows (copyโpasteโundo)
- Test edge cases: large files, concurrent operations, permission errors
- Mock file system operations where appropriate
- SQLite tests use in-memory databases
## Key Implementation Notes
**Multi-Target Paste**
- When pasting to same file multiple times, adjust line numbers to account for previous inserts
- Use transaction rollback if any target fails
- All pastes in one operation share same operation_log_id
**Error Handling**
- Return user-friendly error messages via MCP protocol
- Log detailed errors internally for debugging
- Validate all inputs before operations
- Handle file permission errors gracefully
**Path Security**
- Validate paths to prevent directory traversal attacks
- Normalize paths using Node's path module
- Reject operations on files outside allowed directories (if configured)
**Line Number Drift**
- Clipboard stores absolute content, not live line references
- Warn users when clipboard references may be stale after file modifications
- Source metadata is informational only after initial copy/cut
## Project Setup Checklist
When initializing the project (Phase 0):
1. Create package.json with MCP SDK dependency
2. Configure TypeScript (tsconfig.json)
3. Setup Jest with TypeScript support
4. Add ESLint + Prettier
5. Create SQLite schema file
6. Setup database initialization module
7. Configure build scripts (TypeScript compilation)
8. Add bin/cli.js entry point for NPX
## NPX Distribution
- Package must have `bin` field in package.json
- CLI file needs shebang: `#!/usr/bin/env node`
- Set executable permissions on bin file
- Test with `npx .` locally before publishing
- Use `prepublishOnly` script to build before publish
## Common Pitfalls to Avoid
1. **Don't implement before testing** - Strict TDD means tests always come first
2. **Don't skip refactor phase** - Code quality matters from the start
3. **Don't forget transaction rollback** - Multi-file operations must be atomic
4. **Don't ignore line ending preservation** - Different OSes use different line endings
5. **Don't assume file permissions** - Always check before write operations
6. **Don't log sensitive data** - File contents in error messages should be truncated
## Working with This Codebase
1. **Read TODO.md first** - It contains the complete implementation roadmap
2. **Follow phases sequentially** - Each phase builds on previous phases
3. **Update ARCHITECTURE.md** - Document decisions as you make them
4. **Keep README.md current** - Users need up-to-date instructions
5. **Run tests constantly** - Tests should always be green between commits
6. **Commit after each phase** - Small, focused commits with passing tests
## References
- [TODO.md](TODO.md) - Complete TDD implementation plan with 15 phases
- MCP SDK Documentation - https://modelcontextprotocol.io
- SQLite Documentation - For database schema implementation