file-reader-mcp

file-reader-mcp

Enables LLM agents to securely explore, read, search, and analyze text-based files within a sandboxed environment.

Category
访问服务器

README

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

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:

c
.venv\Scripts\activate

On macOS/Linux:

python3 -m venv .venv
source .venv/bin/activate

2. Install Dependencies

Install the required Python SDK and dependencies listed in requirements.txt:

pip install -r requirements.txt

3. Configure the Environment

Create your .env file from the example template:

copy .env.example .env

Review or modify .env as needed:

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

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

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:

{
  "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:
    [
      {
        "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:
    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:
    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:
    [
      "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:
    {
      "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:
    {
      "words": 62,
      "characters": 482,
      "lines": 17
    }
    

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选