Smart File Reader MCP Server
# Smart File Reader MCP Server
An intermediate-level, production-grade Model Context Protocol (MCP) server built with **Python 3.12+**, **FastMCP**, and **Asyncio**. It enables AI assistants (such as Claude Desktop, Cursor, or custom agents) to securely read, search, inspect, and analyze files across local directories on **Windows**, **macOS**, and **Linux**.
---
## Features
- **10 Modular MCP Tools**:
- `read_file(path)`: Read text files with UTF-8 encoding checks and configurable size limits.
- `read_file_lines(path, start_line, end_line)`: Read 1-based line ranges with bounds validation.
- `list_files(directory)`: List files and subdirectories with sizes, types, and extensions.
- `search_files(directory, pattern)`: Wildcard filename matching (`*.py`, `*.json`, `test_*`).
- `search_file_content(directory, query)`: Search text inside files, returning matching line numbers and text.
- `get_file_info(path)`: Detailed file metadata (size, human-readable size, timestamps in UTC, read status).
- `get_file_preview(path, max_chars)`: Content preview with truncation indicators.
- `get_directory_tree(directory, max_depth)`: Formatted ASCII directory hierarchy visualization.
- `get_directory_size(directory)`: Aggregated byte size, file counts, and directory counts.
- `find_large_files(directory, min_size_mb)`: Scan and list large files sorted descending by size.
- **3 MCP Resources**:
- `filesystem://info`: Server metadata, platform information, and operational bounds.
- `filesystem://allowed-roots`: List of configured allowed directory roots and their accessibility.
- `filesystem://statistics`: Aggregated file, directory, and byte counts across all allowed roots.
- **2 MCP Prompts**:
- `file_analysis_assistant`: Guides the AI to inspect, read, review, and evaluate a specific file.
- `directory_analysis_assistant`: Guides the AI to analyze directory layout, architecture, and project organization.
- **Security by Default**:
- Strict path traversal protection (`../`, unauthorized absolute paths).
- Configurable allowed root directories (supports `~` for user home, `.` for project root, `*` for root drive).
- Symlink escape detection.
- Configurable hidden-file filtering.
- **Read-only**: no file modifications, moves, or deletions are permitted.
- **Asynchronous & Non-blocking**:
- All disk I/O operations are offloaded using `asyncio.to_thread()` to prevent blocking the event loop.
---
## Project Structure
```
smart-file-reader-mcp/
├── .env # Local environment configuration
├── .env.example # Template for environment configuration
├── .gitignore # Git ignore rules
├── pyproject.toml # Build config, tools, and dependencies (uv / hatchling)
├── uv.lock # Locked dependency tree
├── README.md # Complete documentation & usage guide
│
├── sample_files/ # Sample directory for immediate testing
│ ├── README.md
│ ├── config.json
│ └── math_sample.py
│
├── src/
│ └── file_reader/
│ ├── __init__.py # Package exports and version
│ ├── server.py # FastMCP server instantiation and CLI entry point
│ ├── config.py # Pydantic Settings configuration loader
│ ├── tools.py # 10 MCP tool definitions and parameter schemas
│ ├── resources.py # 3 MCP resource endpoints
│ ├── prompts.py # 2 MCP reusable prompts
│ ├── file_service.py # Pure filesystem logic offloaded via asyncio.to_thread
│ ├── security.py # Path validation, traversal guards, and symlink checks
│ └── schemas.py # Pydantic data models for structured outputs
│
└── tests/
├── __init__.py
├── test_security.py # Security & path traversal tests
├── test_file_service.py # File service operations unit tests
├── test_tools.py # MCP tool handler unit tests
├── test_resources_prompts.py # Resources and prompts tests
└── test_server.py # End-to-end FastMCP server integration tests
```
---
## Async Programming Explained
1. **What `async def` does**: Defines a coroutine function. When called, it does not immediately execute to completion; instead, it returns a coroutine object that can be cooperatively scheduled and resumed on the Python `asyncio` event loop.
2. **When `await` is needed**: `await` pauses execution of the current coroutine until the awaited asynchronous task or coroutine finishes, relinquishing control back to the event loop so other concurrent operations (such as incoming JSON-RPC requests) can proceed.
3. **Why filesystem operations can block**: Python's standard file APIs (`open()`, `read()`, `os.walk()`, `scandir()`) perform synchronous operating system calls. When reading a large file or traversing a massive directory tree, the OS thread is blocked waiting for disk I/O. In an asynchronous server, this halts the entire event loop, freezing all client requests.
4. **How to avoid blocking the event loop**: We isolate all disk operations inside synchronous helper methods in `file_service.py` and invoke them with `await asyncio.to_thread(...)`. This dispatches the blocking filesystem call to a separate worker thread from Python's thread pool, keeping the main event loop completely responsive.
---
## Installation & Setup
1. **Clone or navigate to the repository**:
```bash
cd smart-file-reader-mcp
```
2. **Install dependencies with uv**:
```bash
uv sync
```
3. **Configure Environment Variables**:
Copy `.env.example` to `.env` or edit `.env` directly:
```bash
cp .env.example .env
```
---
## Configuration
Settings are managed via `pydantic-settings` in `src/file_reader/config.py`:
| Variable | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `ALLOWED_ROOTS` | `str` | `~,.` | Comma-separated list of permitted paths (`~` for user home, `.` for project, `*` for root drive). |
| `MAX_FILE_SIZE_MB` | `int` | `0` | Maximum file size in MB (`0` = unlimited). |
| `MAX_SEARCH_RESULTS` | `int` | `100000` | Maximum number of search results returned per query. |
| `MAX_DIRECTORY_DEPTH` | `int` | `20` | Maximum recursion depth for directory tree generation. |
| `ENABLE_HIDDEN_FILES`| `bool`| `true` | Whether to allow access to hidden files (`.env`, `.gitignore`, etc.). |
| `LOG_LEVEL` | `str` | `INFO` | Logging level (`DEBUG`, `INFO`, `WARNING`, `ERROR`). |
> **Note**: Server logs are strictly routed to `sys.stderr` so they do not interfere with standard input/output (`stdio`) JSON-RPC messages.
---
## Running the Server
### Directly via uv:
```bash
uv run python -m file_reader.server
```
### Or using the registered script:
```bash
uv run smart-file-reader
```
### Running with the Web MCP Inspector:
```bash
CLIENT_PORT=5174 SERVER_PORT=3001 npx @modelcontextprotocol/inspector .venv/bin/python -m file_reader.server
```
---
## Client Integration Guide
### 1. Claude Desktop Integration
Add the server to your `claude_desktop_config.json`:
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
- **Linux**: `~/.config/Claude/claude_desktop_config.json`
```json
{
"mcpServers": {
"smart-file-reader": {
"command": "/ABSOLUTE/PATH/TO/smart-file-reader-mcp/.venv/bin/python",
"args": [
"-m",
"file_reader.server"
],
"env": {
"ALLOWED_ROOTS": "~,.",
"MAX_FILE_SIZE_MB": "0",
"MAX_SEARCH_RESULTS": "100000",
"ENABLE_HIDDEN_FILES": "true",
"LOG_LEVEL": "INFO"
}
}
}
}
```
### 2. Cursor IDE Integration
1. Open **Cursor Settings** (`Cmd + ,` or `Ctrl + ,`).
2. Navigate to **Features** > **MCP Servers**.
3. Click **Add New MCP Server**.
4. Configure:
- **Name**: `smart-file-reader`
- **Type**: `command`
- **Command**: `/ABSOLUTE/PATH/TO/smart-file-reader-mcp/.venv/bin/python -m file_reader.server`
### 3. Programmatic Python Client Integration
```python
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
server_params = StdioServerParameters(
command=".venv/bin/python",
args=["-m", "file_reader.server"],
env={"ALLOWED_ROOTS": "~,."},
)
async def main():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# Call read_file tool
result = await session.call_tool("read_file", {"path": "README.md"})
print(result.content[0].text)
if __name__ == "__main__":
asyncio.run(main())
```
---
## MCP Tools Reference
| Tool Name | Parameters | Description |
| :--- | :--- | :--- |
| `read_file` | `path: str` | Reads full UTF-8 text file content. |
| `read_file_lines` | `path: str, start_line: int, end_line: int` | Reads specific line range (1-based). |
| `list_files` | `directory: str = "."` | Lists directory contents with sizes and types. |
| `search_files` | `directory: str, pattern: str` | Searches filenames by wildcard pattern (e.g., `*.py`). |
| `search_file_content` | `directory: str, query: str` | Searches text inside files and returns line numbers. |
| `get_file_info` | `path: str` | Returns metadata, human-readable size, and timestamps. |
| `get_file_preview` | `path: str, max_chars: int = 500` | Returns content preview and truncation flag. |
| `get_directory_tree` | `directory: str = ".", max_depth: int = 3` | Generates formatted ASCII directory hierarchy tree. |
| `get_directory_size` | `directory: str = "."` | Computes total folder byte size and file counts. |
| `find_large_files` | `directory: str = ".", min_size_mb: float = 1.0` | Finds files exceeding size threshold sorted descending. |
---
## Testing & Quality Verification
Run the full test suite with `pytest`:
```bash
uv run pytest -v
```
Check linting and formatting with `ruff`:
```bash
uv run ruff check src/ tests/
uv run ruff format --check src/ tests/
```
---
## License
MIT License.
TDQS
Scored across 10 tools
Most tools target clearly distinct operations (tree, size, listing, pattern search, content search, metadata, large-file scan). The only overlap is the trio read_file / read_file_lines / get_file_preview, which all return file content; descriptions help but an agent may still hesitate over which to pick.
All ten tools follow a strict verb_noun snake_case pattern (get_directory_tree, find_large_files, read_file_lines, search_file_content, etc.). No camelCase or vague single-word names appear.
Ten tools is well within the ideal range and each corresponds to a concrete read/inspect operation. No redundant or filler tools pad the surface.
The read-only file inspection domain is well covered: navigation, listing, size, metadata, pattern and content search, full/partial reads. Minor gaps exist (no multi-file read, no regex search option, no write/copy operations if the scope is meant to extend beyond reading), but agents can work around them.