Skip to main content
Glama
Smart File Reader MCP Server

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.


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 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:

    cd smart-file-reader-mcp
  2. Install dependencies with uv:

    uv sync
  3. Configure Environment Variables: Copy .env.example to .env or edit .env directly:

    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:

uv run python -m file_reader.server

Or using the registered script:

uv run smart-file-reader

Running with the Web MCP Inspector:

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

{
  "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

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:

uv run pytest -v

Check linting and formatting with ruff:

uv run ruff check src/ tests/
uv run ruff format --check src/ tests/

License

MIT License.

Available Tools

10 tools
find_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

    B3.4/5.0

    Scored across 10 tools

    Disambiguation4/5

    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.

    Naming Consistency5/5

    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.

    Tool Count5/5

    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.

    Completeness4/5

    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

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables 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
    • F
      license
      B
      quality
      D
      maintenance
      Provides 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
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides 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.
      5
      MIT