MCP Filesystem Agent v3
Click on "Install 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., "@MCP Filesystem Agent v3list all Python files in the src directory"
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.
๐ MCP Filesystem Agent v3
Token-Optimized File Management for AI Models
A production-ready Model Context Protocol (MCP) server enabling Claude and other LLMs to perform intelligent file operations with minimal token usage. Built for efficiency, security, and ease of use.
Quick Start โข Features โข Installation โข Usage โข Deployment
โจ Features
๐ฏ Core Capabilities
25+ File Operations - Read, write, edit, search, analyze
Token-Optimized - Designed for minimal token usage with LLMs
Chunked Reading - Handle files larger than context window with proper pagination
Smart Searching - Content search, filename search, regex patterns, code structure analysis
Code Intelligence - AST-based analysis for Python (extensible to other languages)
Safe Operations - Dry-run mode for dangerous modifications, path validation, symlink safety
๐ค LLM-Friendly Design
Standardized Responses - All tools return consistent
DictstructureClear Descriptions - Every tool optimized for LLM understanding
Error Handling - Informative error messages guide LLM behavior
Context Awareness - Tools provide metadata (file size, line count, progress) for informed decisions
Rate Limiting - Prevents token waste with configurable limits
๐ Security
Path Validation - Prevents directory traversal attacks (../../etc/passwd)
Symlink Safety - Resolves symlinks securely within BASE_DIR
Binary Detection - Avoids reading binary files as text
Size Limits - Prevents memory overload from accidental large file reads
Restricted Access - All operations confined to BASE_DIR
Related MCP server: file-system-mcp-server
๐ Table of Contents
๐ Quick Start
1๏ธโฃ Install
pip install -r requirements.txt2๏ธโฃ Configure Base Directory
export MCP_BASE_DIR="/path/to/your/projects"
# or on Windows:
# set MCP_BASE_DIR=C:\Users\YourName\Projects3๏ธโฃ Run Server
python server_v3.py4๏ธโฃ Connect to Claude
In Claude.ai Settings โ Developer โ Add MCP Server:
Name:
filesystem-agentScript path:
/full/path/to/server_v3.pyEnvironment:
MCP_BASE_DIR=/your/base/dir
โ Done! All file tools now available in Claude.
๐ฆ Installation
Requirements
Python 3.8+
pip
Steps
# Clone or download the repository
cd mcp-fs-agent
# Install dependencies
pip install -r requirements.txt
# Set your base directory (optional, defaults to ~/Data/Repos)
export MCP_BASE_DIR="$HOME/projects"
# Start the server
python server_v3.pyVerify Installation
$ python server_v3.py
==============================================================================
๐ TOKEN-OPTIMIZED MCP FILESYSTEM AGENT v3 (PRODUCTION-READY)
==============================================================================
๐ BASE_DIR: /home/user/projects
โจ Features:
โ
25+ file operations (read, write, search, edit)
โ
Standardized Dict return types (LLM-friendly)
โ
Proper chunked reading with pagination
...
๐ Ready to use with Claude.ai or any MCP-compatible LLM
==============================================================================๐ฏ Features in Detail
๐ Directory Operations
Why LLMs Need This: Navigate projects, understand structure without loading full files
list_directory()- List files with metadata (size, type)get_tree()- Compact directory tree (configurable depth)create_directory()- Create folders recursively
LLM Benefit: Get full project overview in one token-efficient call
๐ Smart File Reading
Why LLMs Need This: Handle files larger than context window, preview before full read
read_file()- Full read OR preview-only (first N lines)read_file_chunked()- NEW v3: Proper pagination for huge filesSpecify
chunk_indexto jump to any positionReturns progress (e.g., "3/100 chunks")
Never loads entire file into memory
batch_read_files()- Read multiple files in one callfile_summary()- Get file info without reading (ultra-token-efficient)
LLM Benefit: preview_lines=50 = 50 lines read instead of 1000 = 95% token savings
๐ง Safe File Editing
Why LLMs Need This: Modify files safely with preview before commit
write_file()- Create/overwriteappend_file()- Add to endreplace_text()- NEW v3:dry_run=Trueshows changes firstinsert_at_line()- Insert at specific linedelete_lines()- Delete range
LLM Benefit: dry_run=True prevents accidental file corruption
๐ Intelligent Search
Why LLMs Need This: Find what you need without scanning entire codebase
search_files()- Find by filenamesearch_files_by_ext()- Find by type (.py, .txt, etc)search_content()- NEW v3: Supports regex patterns + context around matchessearch_code_structure()- NEW v3: Functions, classes, imports with line numbers
LLM Benefit: Regex pattern ^def .*_handler finds all handlers instantly vs scanning entire code
๐ Code Intelligence
Why LLMs Need This: Understand code structure without reading files
Python AST parsing for functions, classes, imports
Returns signatures and metadata
Extensible to JavaScript, Go, Rust, etc. (see below)
LLM Benefit: "Show me all functions that start with 'handle'" = instant code map
๐ ๏ธ Tool Reference
Quick Lookup Table
Category | Tool | Use When | LLM Efficiency |
Read |
| Need full file content | ๐ Good with |
Read |
| File > 2MB | ๐ Excellent (pagination) |
Read |
| Need multiple files | ๐ Good (one call vs many) |
Info |
| Need size/lines only | ๐ Best (no content read) |
Write |
| Create/overwrite | ๐ Safe |
Edit |
| Find & replace | ๐ Good with |
Search |
| Find by name | ๐ Best (simple substring) |
Search |
| Find by content | ๐ Good with limits |
Code |
| Find functions/classes | ๐ Best (AST, not text) |
Complete Tools List
Basic
ping() -> Dict
get_base_dir() -> DictDirectory Operations
list_directory(path: str = ".") -> Dict
get_tree(path: str = ".", max_depth: int = 2) -> Dict
create_directory(path: str) -> DictFile Reading
read_file(path: str, preview_lines: int = 0) -> Dict
read_file_chunked(path: str, chunk_index: int = 0, chunk_size_kb: int = 50) -> Dict
batch_read_files(paths: List[str]) -> Dict
file_summary(path: str) -> DictFile Writing
write_file(path: str, content: str) -> Dict
append_file(path: str, content: str) -> DictFile Editing
replace_text(path: str, old_text: str, new_text: str, count: int = -1, dry_run: bool = False) -> Dict
insert_at_line(path: str, line_number: int, text: str) -> Dict
delete_lines(path: str, start_line: int, end_line: int) -> DictSearch
search_files(query: str, path: str = ".", max_results: int = 20) -> Dict
search_content(query: str, path: str = ".", max_results: int = 15,
extensions: List[str] = None, use_regex: bool = False) -> Dict
search_files_by_ext(extension: str, path: str = ".", max_results: int = 30) -> DictCode Analysis
search_code_structure(path: str = ".", search_type: str = "functions", max_results: int = 25) -> Dict๐ก Usage Examples
Example 1: Preview Before Full Read (Token-Efficient)
User: Read the first 50 lines of app/main.py
Claude uses: read_file(path="app/main.py", preview_lines=50)
Response:
{
"status": "success",
"action": "read_file",
"mode": "preview",
"preview_lines": 50,
"total_lines": 450,
"content": "#!/usr/bin/env python3\n..."
}
โ
Only 50 lines loaded, not 450!Example 2: Large File with Pagination
User: My app.log is huge. Read it in chunks starting from the beginning.
Claude uses: read_file_chunked(
path="logs/app.log",
chunk_index=0,
chunk_size_kb=100
)
Response:
{
"status": "success",
"chunk_index": 0,
"total_chunks": 25,
"progress": "1/25",
"file_size": "2.5MB",
"content": "2024-01-15 10:00:00 INFO ...\n..."
}
โ
Can request chunk 5, 10, 20, etc without reloading!Example 3: Safe Replace with Dry-Run
User: Change all "console.log" to "logger.debug" in src/util.js - but show me first!
Claude uses: replace_text(
path="src/util.js",
old_text="console.log",
new_text="logger.debug",
dry_run=True
)
Response:
{
"status": "success",
"mode": "dry_run",
"would_replace": 12,
"preview": "const logger = require('./logger');\nlogger.debug('Debug message');\n...",
"ready_to_commit": true
}
User: Looks good, do it!
Claude uses: replace_text(..., dry_run=False)
โ
No surprises, changes committed safely!Example 4: Code Structure Analysis
User: Show me all functions in the project
Claude uses: search_code_structure(search_type="functions", max_results=30)
Response:
{
"status": "success",
"found": 8,
"results": [
{
"type": "function",
"name": "handle_request",
"file": "app/handlers.py",
"line": 45,
"signature": "def handle_request(req, resp)",
"args": 2
},
...
]
}
โ
Understand entire codebase structure without reading any files!Example 5: Regex Search
User: Find all TODO comments in Python files
Claude uses: search_content(
query=r"#\s*TODO",
extensions=[".py"],
use_regex=True
)
Response:
{
"status": "success",
"found": 5,
"results": [
{
"file": "app/main.py",
"line": 127,
"match": "# TODO: Refactor authentication logic"
},
...
]
}
โ
Powerful pattern matching without manual code review!๐ค LLM Integration
With Claude.ai
Go to Settings โ Developer โ Add MCP Server
Fill in:
Name:
filesystem-agentScript command:
python /path/to/server_v3.pyEnvironment variables:
MCP_BASE_DIR=/home/user/projects
Click Test Connection (server must be running)
Use in any chat!
Example Claude Conversation
User: Analyze my Flask app's structure
Claude: I'll examine your Flask app...
[Uses search_code_structure to find routes, models, handlers]
[Uses file_summary to check file sizes]
[Uses read_file with preview_lines on key files]
Here's what I found:
- 3 route handlers in app/routes.py
- 2 database models in app/models.py
- Configuration in config.py (45 lines)
...Response Format All LLMs Understand
Every tool returns standardized Dict:
{
"status": "success|error|info", # Always present
"action": "tool_name", # What was called
"path": "relative/path", # If applicable
# ... tool-specific fields ...
}This makes LLMs reliable at:
โ Checking if operation succeeded
โ Understanding what was attempted
โ Handling errors gracefully
โ Chaining multiple operations
โ๏ธ Configuration
Edit server_v3.py to customize (all at the top):
# Base directory (default: ~/Data/Repos, override with MCP_BASE_DIR env var)
BASE_DIR = Path(os.getenv("MCP_BASE_DIR", str(Path.home() / "Data/Repos"))).resolve()
# Token optimization settings
MAX_FILE_SIZE_KB = 2000 # Max single file (2MB)
MAX_RESULTS = 50 # Max search results
DEFAULT_CHUNK_SIZE_KB = 50 # Chunk size for large files
TOTAL_BATCH_SIZE_KB = 5000 # Max total for batch_read_files (5MB)
CONTEXT_WIDTH = 80 # Chars around search match
MAX_LINES_TO_SEARCH = 10000 # Stop after this many lines
# Ignore directories
IGNORE_DIRS = {".git", "node_modules", "__pycache__", "venv", ...}
# Ignore binary files
BINARY_EXTENSIONS = {".exe", ".pdf", ".zip", ".so", ...}๐ข Deployment
Development (Local Machine)
export MCP_BASE_DIR="$HOME/projects"
python server_v3.py
# Leave running, connect from ClaudeDocker
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY server_v3.py .
ENV MCP_BASE_DIR=/workspace
CMD ["python", "server_v3.py"]Build & run:
docker build -t mcp-fs-agent .
docker run -e MCP_BASE_DIR=/projects -v ~/projects:/projects mcp-fs-agentLinux Systemd Service
Create /etc/systemd/system/mcp-fs.service:
[Unit]
Description=MCP Filesystem Agent
After=network.target
[Service]
Type=simple
User=yourusername
Environment="MCP_BASE_DIR=/home/yourusername/projects"
ExecStart=/usr/bin/python3 /home/yourusername/server_v3.py
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.targetEnable & start:
sudo systemctl daemon-reload
sudo systemctl enable mcp-fs
sudo systemctl start mcp-fs
sudo systemctl status mcp-fs๐ Troubleshooting
Issue | Solution |
"Access denied: Path outside base directory" | Set |
"File too large" error | Use |
Tools not showing in Claude | Restart Claude/reload page; ensure server is running |
Server won't start | Check Python 3.8+, install requirements: |
Can't find file | Verify file is under |
๐ Security
Path Validation
# โ
These work (within BASE_DIR)
"/projects/my_app/main.py"
"./src/app.py"
"config/settings.json"
# โ These are blocked (outside BASE_DIR)
"../../etc/passwd"
"/etc/passwd"
"/home/other_user/file.txt"Symlink Safety
# Symlinks are resolved and validated
# Even if they point outside BASE_DIR, they're rejectedBinary File Protection
# Automatically skipped for:
.exe, .dll, .so, .pdf, .zip, .jpg, .png, etc.
# Prevents text decode errors and token waste๐ Performance Tips
For Large Projects
# โ
Good: Narrow down with file type first
search_files_by_ext(".py")
# โ
Good: Limit search scope
search_content(query="TODO", extensions=[".py", ".txt"])
# โ
Good: Preview first, full read later
read_file(path="large_file.py", preview_lines=50)For Huge Files (500MB+)
# โ
Only way to handle huge files
read_file_chunked(path="huge.log", chunk_index=0, chunk_size_kb=500)
# โ Never use read_file() on huge filesFor Complex Searches
# โ
Use regex for complex patterns
search_content(query=r"def [a-z_]+_handler", use_regex=True)
# โ
Limit max_results to avoid token waste
search_content(query="import", max_results=10)๐ What's New in v3
Feature | v2 | v3 |
Standardized return types | โ | โ |
Chunked reading with pagination | โ | โ |
Dry-run mode for edits | โ | โ |
Regex search support | โ | โ |
Multi-language code analysis | โ | โ (Python + extensible) |
Better tool descriptions | โ ๏ธ | โ |
Token optimization | โ | โ |
Code structure analysis | โ | โ |
Path security | โ | โ |
๐งช Testing
Run with a sample project:
# Create test directory
mkdir -p ~/test_mcp/{src,tests}
echo "def hello(): pass" > ~/test_mcp/src/app.py
# Set and run
export MCP_BASE_DIR="$HOME/test_mcp"
python server_v3.py
# In another terminal, test with Claude or manually:
curl -X POST http://localhost:8000/search_files \
-H "Content-Type: application/json" \
-d '{"query": ".py"}'๐ Contributing
Want to add support for JavaScript, Go, or Rust code analysis?
Edit
search_code_structure()inserver_v3.pyAdd language detection and parsing
Return same format as Python results
Example for JavaScript:
# Add to imports
import re
# Add to search_code_structure() function
elif file.endswith(".js"):
# Use regex to find function definitions
matches = re.findall(r'(?:function|const|async)\s+(\w+)', content)
# Convert to same format as Python๐ License
MIT License - Free to use, modify, and distribute.
See LICENSE file for details.
๐ About
Built as a modern file management interface for AI models, emphasizing:
Token Efficiency - Every API choice minimizes token usage
LLM Friendliness - Standardized responses, clear semantics
Safety First - Path validation, size limits, dry-run modes
Developer Experience - Clear docs, easy integration, extensible code
๐ค Support
๐ Check SETUP_GUIDE.md for detailed setup
๐ See Troubleshooting section above
๐ฌ Open an issue for bugs or feature requests
โญ Star this repo if it helps you!
Made with โค๏ธ for AI developers
Transform how AI manages your files
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Latest Blog Posts
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/Mdskun/MCP-Filesystem-Agent'
If you have feedback or need assistance with the MCP directory API, please join our Discord server