MCP HubMCP Hub
tumf

mcp-text-editor

by: tumf

mcp text editor

73created 11/12/2024
Visit
editor
text

πŸ“ŒOverview

Purpose: To provide a standardized API for line-oriented text file editing within a Model Context Protocol (MCP) framework that minimizes token usage for efficient operations.

Overview: The MCP Text Editor Server facilitates safe and efficient text file operations in a client-server model. By utilizing the Model Context Protocol, it allows multiple processes to modify text files concurrently while ensuring data integrity through robust conflict detection and validation. This server is especially tailored for integration with LLM tools, enabling efficient access to necessary file parts, thus optimizing resource consumption.

Key Features:

  • Line-oriented Editing: Enables precise manipulation of text files through line-based operations that streamline collaborative and automated editing tasks.

  • Token-efficient Access: Supports partial file access with line-range specifications, crucial for reducing token usage in LLM applications.

  • Concurrent Editing Support: Implements hash-based validation to ensure safe multi-user editing, preventing conflicts through reliable error handling.

  • Encoding Flexibility: Comprehensive support for various character encodings (UTF-8, Shift-JIS, Latin1, etc.), facilitating diverse text file interactions.


MCP Text Editor Server

A Model Context Protocol (MCP) server that provides line-oriented text file editing capabilities through a standardized API. Optimized for LLM tools with efficient partial file access to minimize token usage.

Quick Start for Claude.app Users

To use this editor with Claude.app, add the following configuration to your prompt:

code ~/Library/Application\ Support/Claude/claude_desktop_config.json
{
  "mcpServers": {
    "text-editor": {
      "command": "uvx",
      "args": [
        "mcp-text-editor"
      ]
    }
  }
}

or with docker:

{
  "mcpServers": {
    "text-editor": {
      "command": "docker",
      "args": [
          "run",
          "-i",
          "--rm",
          "--mount",
          "type=bind,src=/some/path/src,dst=/some/path/dst",
          "mcp/text-editor"
      ]
    }
  }
}

Overview

MCP Text Editor Server enables safe and efficient line-based text file operations in a client-server architecture. It implements the Model Context Protocol for reliable file editing, robust conflict detection, and resolution. The line-oriented approach suits synchronized file access in collaborative editing, automated text processing, or multiple concurrent modification scenarios. Partial file access is especially valuable for LLM-based tools, minimizing token consumption by loading only necessary file portions.

Key Benefits

  • Line-based editing operations
  • Token-efficient partial file access with line-range specifications
  • Optimized for LLM tool integration
  • Safe concurrent editing with hash-based validation
  • Atomic multi-file operations
  • Robust error handling with custom error types
  • Comprehensive encoding support (utf-8, shift_jis, latin1, etc.)

Features

  • Line-oriented text file editing and reading
  • Smart partial file access to minimize token usage in LLM applications
  • Retrieve text file contents with line range specification
  • Read multiple ranges from multiple files in one operation
  • Line-based patch application with correct handling of line number shifts
  • Edit text file contents with conflict detection
  • Flexible character encoding support
  • Support for multiple file operations
  • Proper handling of concurrent edits with hash-based validation
  • Memory-efficient processing of large files

Requirements

  • Python 3.13 or higher
  • POSIX-compliant OS (Linux, macOS, etc.) or Windows
  • File system permissions for read/write operations

Installation

Run via uvx

uvx mcp-text-editor

Installing via Smithery

To automatically install Text Editor Server for Claude Desktop via Smithery:

npx -y @smithery/cli install mcp-text-editor --client claude

Manual Installation

  1. Install Python 3.13+
pyenv install 3.13.0
pyenv local 3.13.0
  1. Install uv (recommended) or pip
curl -LsSf https://astral.sh/uv/install.sh | sh
  1. Create virtual environment and install dependencies
uv venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
uv pip install -e ".[dev]"

Docker Installation

docker build --network=host -t mcp/text-editor .

Usage

Start the server:

python -m mcp_text_editor

Start the server with Docker:

docker run -i --rm --mount "type=bind,src=/some/path/src,dst=/some/path/dst" mcp/text-editor

With inspector:

npx @modelcontextprotocol/inspector docker run -i --rm --mount "type=bind,src=/some/path/src,dst=/some/path/dst" mcp/text-editor

MCP Tools

get_text_file_contents

Retrieve contents of one or more text files with line range specification.

Single Range Request Example:

{
  "file_path": "path/to/file.txt",
  "line_start": 1,
  "line_end": 10,
  "encoding": "utf-8"
}

Multiple Ranges Request Example:

{
  "files": [
    {
      "file_path": "file1.txt",
      "ranges": [
        {"start": 1, "end": 10},
        {"start": 20, "end": 30}
      ],
      "encoding": "shift_jis"
    },
    {
      "file_path": "file2.txt",
      "ranges": [
        {"start": 5, "end": 15}
      ]
    }
  ]
}

Parameters:

  • file_path: Path to the text file
  • line_start/start: Line number to start from (1-based)
  • line_end/end: Line number to end at (inclusive); null means end of file
  • encoding: File encoding (default: "utf-8")

Single Range Response:

{
  "contents": "File contents",
  "line_start": 1,
  "line_end": 10,
  "hash": "sha256-hash-of-contents",
  "file_lines": 50,
  "file_size": 1024
}

Multiple Ranges Response:

{
  "file1.txt": [
    {
      "content": "Lines 1-10 content",
      "start": 1,
      "end": 10,
      "hash": "sha256-hash-1",
      "total_lines": 50,
      "content_size": 512
    },
    {
      "content": "Lines 20-30 content",
      "start": 20,
      "end": 30,
      "hash": "sha256-hash-2",
      "total_lines": 50,
      "content_size": 512
    }
  ],
  "file2.txt": [
    {
      "content": "Lines 5-15 content",
      "start": 5,
      "end": 15,
      "hash": "sha256-hash-3",
      "total_lines": 30,
      "content_size": 256
    }
  ]
}

patch_text_file_contents

Apply patches to text files with robust error handling and conflict detection. Supports editing multiple files in a single operation.

Request Example:

{
  "files": [
    {
      "file_path": "file1.txt",
      "hash": "sha256-hash-from-get-contents",
      "encoding": "utf-8",
      "patches": [
        {
          "start": 5,
          "end": 8,
          "range_hash": "sha256-hash-of-content-being-replaced",
          "contents": "New content for lines 5-8\n"
        },
        {
          "start": 15,
          "end": null,
          "range_hash": "sha256-hash-of-content-being-replaced",
          "contents": "Content to append\n"
        }
      ]
    }
  ]
}

Important Notes:

  • Always get current hash and range_hash using get_text_file_contents before editing
  • Apply patches from bottom to top to handle line number shifts
  • Patches must not overlap within the same file
  • Line numbers are 1-based
  • end: null appends content to end of file
  • File encoding must match encoding used in get_text_file_contents

Success Response:

{
  "file1.txt": {
    "result": "ok",
    "hash": "sha256-hash-of-new-contents"
  }
}

Error Response with Hints:

{
  "file1.txt": {
    "result": "error",
    "reason": "Content hash mismatch",
    "suggestion": "get",
    "hint": "Please run get_text_file_contents first to get current content and hashes"
  }
}

Common Usage Pattern

  1. Get current content and hash:
contents = await get_text_file_contents({
    "files": [
        {
            "file_path": "file.txt",
            "ranges": [{"start": 1, "end": null}]
        }
    ]
})
  1. Edit file content:
result = await edit_text_file_contents({
    "files": [
        {
            "path": "file.txt",
            "hash": contents["file.txt"][0]["hash"],
            "encoding": "utf-8",
            "patches": [
                {
                    "line_start": 5,
                    "line_end": 8,
                    "contents": "New content\n"
                }
            ]
        }
    ]
})
  1. Handle conflicts:
if result["file.txt"]["result"] == "error":
    if "hash mismatch" in result["file.txt"]["reason"]:
        # File was modified by another process: get new content and retry
        pass

Error Handling

The server manages errors including:

  • File not found
  • Permission errors
  • Hash mismatches (concurrent edit detection)
  • Invalid patch ranges
  • Overlapping patches
  • Encoding errors
  • Line number out of bounds

Security Considerations

  • File path validation to prevent directory traversal attacks
  • Access control via file system permissions
  • Hash validation prevents race conditions
  • Proper input sanitization and validation
  • Sensitive information is not exposed in error messages

Troubleshooting

Common Issues

  1. Permission Denied

    • Verify file and directory permissions
    • Ensure server process has necessary read/write access
  2. Hash Mismatch and Range Hash Errors

    • File modified by another process
    • Content replaced has changed
    • Run get_text_file_contents for fresh hashes
  3. Encoding Issues

    • Verify file encoding matches specified encoding
    • Use UTF-8 for new files
    • Check for BOM markers
  4. Connection Issues

    • Ensure server is running and accessible
    • Check network and firewall settings
  5. Performance Issues

    • Use smaller line ranges for large files
    • Monitor system resources
    • Choose appropriate encoding for file type

Development

Setup

  1. Clone the repository
  2. Create and activate a Python virtual environment
  3. Install development dependencies:
uv pip install -e ".[dev]"
  1. Run tests:
make all

Code Quality Tools

  • Ruff for linting
  • Black for code formatting
  • isort for import sorting
  • mypy for type checking
  • pytest-cov for test coverage

Testing

Tests are located in the tests directory and run with pytest:

pytest                # Run all tests
pytest --cov=mcp_text_editor --cov-report=term-missing   # Run tests with coverage report
pytest tests/test_text_editor.py -v   # Run specific test file

Current test coverage: 90%

Project Structure

mcp-text-editor/
β”œβ”€β”€ mcp_text_editor/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ __main__.py      # Entry point
β”‚   β”œβ”€β”€ models.py        # Data models
β”‚   β”œβ”€β”€ server.py        # MCP Server implementation
β”‚   β”œβ”€β”€ service.py       # Core service logic
β”‚   └── text_editor.py   # Text editor functionality
β”œβ”€β”€ tests/               # Test files
└── pyproject.toml       # Project configuration

License

MIT

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run tests and code quality checks
  5. Submit a pull request

Type Hints

This project uses Python type hints throughout the codebase. Please maintain this in contributions.

Error Handling

Handle all error cases appropriately with meaningful error messages. The server should never crash due to invalid input or file operations.

Testing

New features should include appropriate tests. Maintain or improve current test coverage.

Code Style

All code should be formatted with Black and pass Ruff linting. Import sorting should be handled by isort.