file-reader-mcp
README.md
# File Reader MCP Server
A professional, production-ready **Model Context Protocol (MCP)** server built in Python that allows LLM agents (like Claude Desktop) to securely explore, read, search, and analyze text-based files within a restricted sandbox environment.
---
## Architecture Overview
```mermaid
graph TD
Client[MCP Client e.g., Claude Desktop] <-->|JSON-RPC over stdio| Server[server.py / MCPServer]
Server <--> Tools[tools/ folder]
Tools --> Validator[utils/validators.py]
Tools --> FileUtils[utils/file_utils.py]
Validator -->|Security Check| Sandbox[(sample_files/ Sandbox)]
FileUtils -->|Read/Scan| Sandbox
Logger[utils/logger.py] -->|Log execution & time| stderr[sys.stderr]
```
### Modular Structure
- **`server.py`**: The entry point. Initializes `MCPServer` and registers the tools.
- **`config.py`**: Loads environment variables and configures parameters like the sandbox directory, allowed extensions, and size thresholds.
- **`utils/validators.py`**: Path traversal checker (preventing `../` escapes), null byte detector, file size validator, and extension filter.
- **`utils/file_utils.py`**: Low-level filesystem operations (encoding fallback loop, file stats, recursive filename search, stream line reader).
- **`utils/logger.py`**: Standard error logger setup (ensures `stdout` remains unpolluted) and execution timer decorator.
- **`tools/`**: Domain-specific implementation wrappers for each API action.
---
## Safety Features & Validation Rules
1. **Strict Sandboxing**: The server converts all user-supplied paths to absolute paths and verifies that they fall within the configured `SANDBOX_DIR` using `Path.relative_to()`. Any attempt to escape using parent directory constructs (e.g. `../`) will trigger a traversal warning and block execution.
2. **Nullable Byte Check**: Paths containing null characters (`\x00`) are immediately rejected to prevent truncate injection attacks on OS-level calls.
3. **Safe File Extensions**: Standard configuration whitelists text-based files (`.txt`, `.md`, `.json`, `.csv`, `.log`, `.xml`, `.yaml`, `.yml`, `.ini`, `.conf`). Binary files or system executables are blocked.
4. **Memory Exhaustion Safeguard**: A file size limit of **5 MB** is enforced by default to prevent LLM agents from loading massive log files or SQL dumps into system memory.
5. **Early-Exit Line Streaming**: The `read_lines` tool opens a file context stream and exits as soon as the requested line threshold is met, preventing high memory consumption.
---
## Installation & Setup
This project requires **Python 3.11** or newer.
### 1. Create a Virtual Environment
Navigate to the root directory and create a virtual environment to isolate the project packages:
**On Windows:**
```bash
c
.venv\Scripts\activate
```
**On macOS/Linux:**
```bash
python3 -m venv .venv
source .venv/bin/activate
```
### 2. Install Dependencies
Install the required Python SDK and dependencies listed in `requirements.txt`:
```bash
pip install -r requirements.txt
```
### 3. Configure the Environment
Create your `.env` file from the example template:
```bash
copy .env.example .env
```
Review or modify `.env` as needed:
```env
# Verbosity options: DEBUG, INFO, WARNING, ERROR, CRITICAL
LOG_LEVEL=INFO
# Relative or absolute path to the sandbox folder
SANDBOX_DIR=sample_files
```
---
## Running the Server
MCP servers run locally on your machine and communicate using Standard Input/Output (`stdio`).
### Running in Development Mode
You can use the official MCP command-line tool `mcp dev` to run the server in developer mode with an interactive inspector interface. This is the recommended way to test during development:
```bash
# Install mcp-cli globally if you haven't already
npm install -g @modelcontextprotocol/inspector
# Run the dev server
mcp dev server.py
```
This command opens an inspector window in your browser (usually at `http://localhost:5173`) allowing you to manually trigger tools and view outputs.
### Starting Directly via Python
You can also run the script directly:
```bash
python server.py
```
*Note: The command-line will seem to hang and wait, because it is waiting for JSON-RPC messages via stdin.*
---
## MCP Integration Examples
To use this server with **Claude Desktop**, add its configuration in the Claude Desktop configuration file (typically located at `%APPDATA%\Claude\claude_desktop_config.json` on Windows or `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS).
Replace paths below with your actual project location:
```json
{
"mcpServers": {
"file-reader-mcp": {
"command": "python",
"args": [
"d:/Projects/file-reader-mcp/server.py"
],
"env": {
"SANDBOX_DIR": "d:/Projects/file-reader-mcp/sample_files",
"LOG_LEVEL": "INFO"
}
}
}
}
```
---
## Tool API and Example Requests/Responses
### 1. `list_files`
List files inside a folder in the sandbox, with an optional extension filter.
- **Request Parameters**:
- `directory` (string, optional): Folder relative to sandbox root. Defaults to `"."`.
- `extension_filter` (string, optional): Filter by suffix (e.g. `txt` or `.md`).
- **Response**:
```json
[
{
"name": "notes.txt",
"relative_path": "notes.txt",
"size_bytes": 482
},
{
"name": "todo.md",
"relative_path": "todo.md",
"size_bytes": 354
}
]
```
### 2. `read_file`
Read a complete text file inside the sandbox.
- **Request Parameters**:
- `path` (string, required): File path relative to sandbox.
- **Response**:
```text
Meeting Notes - Project Kickoff
Date: 2026-07-29
Participants: Alice, Bob, Charlie
...
```
### 3. `read_lines`
Read a slice of lines from a text file.
- **Request Parameters**:
- `path` (string, required): File path relative to sandbox.
- `start_line` (integer, required): Starting line (1-indexed).
- `end_line` (integer, required): End line (inclusive).
- **Response**:
```text
Agenda:
1. Define project scope and deliverables.
2. Setup Model Context Protocol (MCP) server integration.
```
### 4. `search_file`
Search files inside the sandbox recursively by name matching a keyword.
- **Request Parameters**:
- `keyword` (string, required): Case-insensitive keyword to locate.
- **Response**:
```json
[
"notes.txt",
"report.txt"
]
```
### 5. `file_info`
Get file size, type, creation, and modified times.
- **Request Parameters**:
- `path` (string, required): File path relative to sandbox.
- **Response**:
```json
{
"filename": "notes.txt",
"extension": ".txt",
"size_bytes": 482,
"created_at": "2026-07-29T20:32:00.123456",
"modified_at": "2026-07-29T20:34:10.789123"
}
```
### 6. `count_words`
Calculate characters, words, and lines.
- **Request Parameters**:
- `path` (string, required): File path relative to sandbox.
- **Response**:
```json
{
"words": 62,
"characters": 482,
"lines": 17
}
```
This server cannot be deployed
Maintenance
ActivityStale
ResponsivenessNo issues