Smart File Reader MCP Server
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Smart File Reader MCP Server read the first 20 lines of src/file_reader/server.py"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
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.
Related MCP server: Local Code MCP Server
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 testsAsync Programming Explained
What
async defdoes: 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 Pythonasyncioevent loop.When
awaitis needed:awaitpauses 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.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.How to avoid blocking the event loop: We isolate all disk operations inside synchronous helper methods in
file_service.pyand invoke them withawait 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
Clone or navigate to the repository:
cd smart-file-reader-mcpInstall dependencies with uv:
uv syncConfigure Environment Variables: Copy
.env.exampleto.envor edit.envdirectly:cp .env.example .env
Configuration
Settings are managed via pydantic-settings in src/file_reader/config.py:
Variable | Type | Default | Description |
|
|
| Comma-separated list of permitted paths ( |
|
|
| Maximum file size in MB ( |
|
|
| Maximum number of search results returned per query. |
|
|
| Maximum recursion depth for directory tree generation. |
|
|
| Whether to allow access to hidden files ( |
|
|
| Logging level ( |
Note: Server logs are strictly routed to
sys.stderrso they do not interfere with standard input/output (stdio) JSON-RPC messages.
Running the Server
Directly via uv:
uv run python -m file_reader.serverOr using the registered script:
uv run smart-file-readerRunning with the Web MCP Inspector:
CLIENT_PORT=5174 SERVER_PORT=3001 npx @modelcontextprotocol/inspector .venv/bin/python -m file_reader.serverClient Integration Guide
1. Claude Desktop Integration
Add the server to your claude_desktop_config.json:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.jsonLinux:
~/.config/Claude/claude_desktop_config.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
Open Cursor Settings (
Cmd + ,orCtrl + ,).Navigate to Features > MCP Servers.
Click Add New MCP Server.
Configure:
Name:
smart-file-readerType:
commandCommand:
/ABSOLUTE/PATH/TO/smart-file-reader-mcp/.venv/bin/python -m file_reader.server
3. Programmatic Python Client Integration
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 |
|
| Reads full UTF-8 text file content. |
|
| Reads specific line range (1-based). |
|
| Lists directory contents with sizes and types. |
|
| Searches filenames by wildcard pattern (e.g., |
|
| Searches text inside files and returns line numbers. |
|
| Returns metadata, human-readable size, and timestamps. |
|
| Returns content preview and truncation flag. |
|
| Generates formatted ASCII directory hierarchy tree. |
|
| Computes total folder byte size and file counts. |
|
| Finds files exceeding size threshold sorted descending. |
Testing & Quality Verification
Run the full test suite with pytest:
uv run pytest -vCheck linting and formatting with ruff:
uv run ruff check src/ tests/
uv run ruff format --check src/ tests/License
MIT License.
Available Tools
10 toolsfind_large_filesA
Find files larger than min_size_mb sorted in descending order by size.
Args:
directory: Directory to scan.
min_size_mb: Minimum file size in megabytes to include.
Inputs: directory, min_size_mb. Returns: result
get_directory_sizeC
Calculate total folder size and return file and folder counts.
Args:
directory: Directory path to measure.
Inputs: directory. Returns: result
get_directory_treeB
Generate a formatted ASCII tree structure of a directory up to max_depth.
Args:
directory: Directory to visualize.
max_depth: Maximum recursion depth (default 3).
Inputs: directory, max_depth. Returns: result
get_file_infoB
Get metadata about a file (name, extension, size, formatted size, timestamps).
Args:
path: Relative or absolute path to the file.
Inputs: path (required). Returns: result
get_file_previewA
Return a limited preview of file contents and whether content was truncated.
Args:
path: Relative or absolute path to the file.
max_chars: Maximum characters to return (default 500).
Inputs: path (required), max_chars. Returns: result
list_filesC
List files and subdirectories in a directory with names, sizes, and types.
Args:
directory: Directory path to list (defaults to current root directory).
Inputs: directory. Returns: result
read_fileC
Read the full text content of a file within allowed directories.
Args:
path: Relative or absolute path to the file.
Inputs: path (required). Returns: result
read_file_linesA
Read a specific range of lines from a text file (1-based line indexing).
Args:
path: Relative or absolute path to the file.
start_line: 1-based start line index.
end_line: 1-based end line index (inclusive).
Inputs: path (required), end_line (required), start_line (required). Returns: result
search_file_contentC
Search for text inside supported UTF-8 files in a directory.
Args:
directory: Directory to search within.
query: Text string to search for.
Inputs: query (required), directory (required). Returns: result
search_filesB
Search for files and folders matching a wildcard pattern (e.g. '.py', 'test_').
Args:
directory: Directory to search inside.
pattern: Wildcard search pattern.
Inputs: pattern (required), directory (required). Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
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.
Maintenance
Related MCP Connectors
Read and search folders on your own computer with explicit consent. Files are never uploaded.
Safe folder access for ChatGPT and Claude: read, write and search files, risky tools opt-in.
Read-only context from your desktop activity, so your AI assistant knows what you worked on.
- DNS-DATA RemoteDeprecatedcom.dns-data
Connect AI assistants to authorized Windows and macOS devices for files, commands, and management.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to read, search, and analyze local file systems with tools for reading file contents, listing directories, searching by patterns, and analyzing folder structures for context-aware queries.MIT
- FlicenseBqualityDmaintenanceProvides LLMs with safe, read-only access to local codebases for searching, reading files, and finding function definitions. All source code remains local, ensuring privacy while enabling AI assistants to explore project structures and functionality.4-
- AlicenseNot gradedqualityDmaintenanceProvides AI agents with secure, read-only file system access to analyze and understand project codebases, enabling multi-repository context aggregation and cross-project code tracing.5MIT
- AlicenseAqualityDmaintenanceEnables AI assistants to read, write, and manage files on the local system with security features like path restrictions and optional read-only mode.92MIT