MCP-FileSystem

MCP-FileSystem

A Model Context Protocol server that gives AI assistants secure, sandboxed filesystem access with tools for reading, writing, searching, and managing files and directories.

Category
Visit Server

README

Python MCP Filesystem Server

Python MCP License

A comprehensive Model Context Protocol (MCP) server that provides AI assistants with secure, controlled filesystem access. Built with Python for easy customization and learning.

Overview

This MCP server enables AI assistants like Claude to interact with your filesystem through a secure, sandboxed interface. It provides 14 powerful tools for file operations, from basic read/write to advanced features like content search and directory tree visualization.

Features

šŸ“ File Operations

  • read_file - Read file contents
  • write_file - Create or overwrite files
  • append_file - Append to existing files
  • delete_file - Delete files

šŸ“‚ Directory Operations

  • list_files - List directory contents
  • list_directory_tree - Visualize directory structure
  • create_directory - Create new directories
  • delete_directory - Delete directories recursively

šŸ” Search & Discovery

  • search_files - Find files by name pattern (wildcards)
  • search_content - Search text within files
  • file_exists - Check file/directory existence
  • get_file_info - Get metadata (size, dates, type)

šŸ”§ File Management

  • rename_file - Rename files/directories
  • move_file - Move files/directories

šŸ”’ Security Features

  • Path validation - Prevents directory traversal attacks
  • Workspace sandboxing - All operations restricted to designated directory
  • Error handling - Comprehensive error messages for all operations

Quick Start

Prerequisites

  • Python 3.10 or higher
  • pip package manager

Installation

  1. Clone the repository

    git clone https://github.com/YOUR-USERNAME/mcp-filesystem-server-python.git
    cd mcp-filesystem-server-python
    
  2. Create virtual environment

    python -m venv venv
    
    # Windows
    venv\Scripts\activate
    
    # macOS/Linux
    source venv/bin/activate
    
  3. Install dependencies

    pip install -r requirements.txt
    
  4. Test the server (optional)

    python examples/demo.py
    

Configuration

Claude Desktop Setup

Add this configuration to Claude Desktop:

Windows: %APPDATA%\Claude\claude_desktop_config.json
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

{
  "mcpServers": {
    "filesystem": {
      "command": "python",
      "args": ["C:\\path\\to\\mcp-filesystem-server-python\\src\\server.py"],
      "env": {
        "WORKSPACE_DIR": "C:\\path\\to\\your\\workspace"
      }
    }
  }
}

Important:

  • Use absolute paths
  • On Windows, use double backslashes (\\) or forward slashes (/)
  • Set WORKSPACE_DIR to the directory you want Claude to access

Windows Store Claude Desktop

If using Windows Store version, use this location instead:

%LOCALAPPDATA%\Packages\Claude_pzs8sxrjxfjjc\LocalCache\Roaming\Claude\claude_desktop_config.json

Usage Examples

Basic File Operations

Ask Claude:

"List files in my workspace"

Claude will use: list_files tool


Ask Claude:

"Read the file report.txt"

Claude will use: read_file tool with path: "report.txt"


Ask Claude:

"Create a file called notes.txt with a bullet list of my tasks"

Claude will use: write_file tool


Advanced Operations

Search for files:

"Find all Python files in my workspace"

Uses: search_files with pattern "*.py"


Search content:

"Which files contain the word 'TODO'?"

Uses: search_content with text "TODO"


Directory tree:

"Show me the structure of my workspace"

Uses: list_directory_tree


File metadata:

"Get information about config.json"

Uses: get_file_info with path "config.json"


Project Structure

mcp-filesystem-server-python/
ā”œā”€ā”€ src/
│   └── server.py          # Main MCP server implementation
ā”œā”€ā”€ examples/
│   └── demo.py            # Standalone demo (test without Claude)
ā”œā”€ā”€ requirements.txt       # Python dependencies
ā”œā”€ā”€ README.md              # This file
ā”œā”€ā”€ LICENSE                # MIT License
└── .gitignore            # Git exclusions

Development

Running Standalone

Test the server without Claude Desktop:

python examples/demo.py

This simulates how Claude would interact with your server.

Manual Testing

Start the server manually to see debug output:

# Windows
set WORKSPACE_DIR=C:\path\to\workspace
python src\server.py

# macOS/Linux
WORKSPACE_DIR=/path/to/workspace python src/server.py

The server communicates via stdio and expects MCP protocol messages.

Adding New Tools

  1. Add tool definition in handle_list_tools() function
  2. Implement handler in handle_call_tool() function
  3. Follow existing patterns for error handling
  4. Test with examples/demo.py

How MCP Works

Architecture

ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”          ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│  Claude Desktop │ ◄──────► │   MCP Server     │
│    (Client)     │   stdio  │  (src/server.py) │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜          ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
                                      │
                                      ā–¼
                             ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
                             │  Your Workspace │
                             │     (Files)     │
                             ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Communication Flow

  1. Claude starts your server → Python process launches
  2. Claude asks: "What tools do you have?" → handle_list_tools()
  3. Your server responds → List of 14 tools
  4. User requests action → "List my files"
  5. Claude calls tool → handle_call_tool(name="list_files", ...)
  6. Your server executes → Reads directory, returns results
  7. Claude shows results → User sees file list

Key Concepts

  • stdio transport - Communication via standard input/output
  • Tools - Functions Claude can call with JSON parameters
  • Handlers - Your Python functions that implement tools
  • Types - MCP protocol message types (Tool, CallToolResult, etc.)

Troubleshooting

Claude doesn't see the tools

  1. Check config file path is correct
  2. Verify Python path in config is absolute
  3. Restart Claude Desktop completely
  4. Check Claude Desktop version supports MCP (requires Pro)

"Access denied" errors

  • Ensure WORKSPACE_DIR is set correctly
  • Check file/directory permissions
  • Verify paths are within workspace (security feature)

Server not starting

  • Test Python path: Run the command from config manually
  • Check dependencies: pip install -r requirements.txt
  • Verify Python version: python --version (need 3.10+)

Finding logs

Windows Store version logs may be in:

%LOCALAPPDATA%\Packages\Claude_pzs8sxrjxfjjc\LocalCache\Roaming\Claude\

Contributing

Contributions welcome! This is a learning-friendly project.

Ideas for improvements:

  • Add file copy tool
  • Add archive/zip tools
  • Add file watching/monitoring
  • Add binary file support
  • Add permission management
  • More sophisticated search (regex)

License

MIT License - see LICENSE file for details.


Resources


Acknowledgments

Built as a learning project to understand the Model Context Protocol. Perfect for:

  • Learning MCP server development
  • Understanding AI-filesystem interaction
  • Building custom AI tools
  • Educational purposes

Questions or issues? Open an issue on GitHub! }


**macOS/Linux:** `~/Library/Application Support/Claude/claude_desktop_config.json`

```json
{
  "mcpServers": {
    "filesystem": {
      "command": "/path/to/venv/bin/python",
      "args": ["/path/to/file-system-server-python/src/server.py"],
      "env": {
        "WORKSPACE_DIR": "/path/to/test-workspace"
      }
    }
  }
}

Then restart Claude Desktop and ask it to:

  • "List the files in my workspace"
  • "Read sample.txt"
  • "Create a new file called notes.txt with some content"

Option 2: Debug in VS Code

  1. Open this project in VS Code
  2. Install the Python extension
  3. Press F5 or go to Run > Start Debugging
  4. The server starts in debug mode - you can set breakpoints in src/server.py

Project Structure

file-system-server-python/
ā”œā”€ā”€ src/
│   └── server.py         # Main server implementation (READ THIS!)
ā”œā”€ā”€ requirements.txt      # Python dependencies
ā”œā”€ā”€ .vscode/
│   ā”œā”€ā”€ launch.json      # VS Code debug configuration
│   └── mcp.json         # VS Code MCP debug config
└── README.md            # This file

Understanding the Code

Open src/server.py and you'll see:

1. Server Creation (line ~27)

server = Server("simple-filesystem-server")

2. Input Validation with Pydantic (lines ~30-40)

class ReadFileInput(BaseModel):
    path: str = Field(description="Relative path to file")

Pydantic validates inputs automatically, similar to Zod in TypeScript.

3. Tool Registration with Decorators (lines ~43-73)

@server.call_tool()
async def read_file(arguments: dict[str, Any]) -> list[TextContent]:
    """Read the contents of a file"""
    # Implementation...

Python uses decorators (@server.call_tool()) instead of explicit registration.

4. Path Security (lines ~19-25)

def validate_path(file_path: str) -> Path:
    """Prevent path traversal attacks"""
    full_path = (WORKSPACE_DIR / file_path).resolve()
    if not str(full_path).startswith(str(WORKSPACE_DIR.resolve())):
        raise ValueError("Access denied")
    return full_path

5. Server Startup (lines ~132-146)

async with stdio_server() as (read_stream, write_stream):
    await server.run(read_stream, write_stream, ...)

Uses Python's async context manager for clean resource handling.

What You're Learning

This project teaches you:

  • āœ… MCP Server basics - Creating servers in Python
  • āœ… Tool decorators - Using @server.call_tool()
  • āœ… Async/await - Python async programming
  • āœ… Input validation - Using Pydantic models
  • āœ… Error handling - Try/except patterns
  • āœ… Path operations - Using pathlib
  • āœ… Security - Path validation and sandboxing

Development Tips

Virtual Environment

Always activate your virtual environment before working:

# Windows
venv\Scripts\activate

# macOS/Linux
source venv/bin/activate

Adding New Tools

Add a new tool by defining an input model and a decorated function:

class DeleteFileInput(BaseModel):
    path: str = Field(description="File to delete")

@server.call_tool()
async def delete_file(arguments: dict[str, Any]) -> list[TextContent]:
    """Delete a file from the workspace"""
    try:
        input_data = DeleteFileInput(**arguments)
        full_path = validate_path(input_data.path)
        full_path.unlink()
        return [TextContent(type="text", text=f"Deleted {input_data.path}")]
    except Exception as e:
        return [TextContent(type="text", text=f"Error: {str(e)}")]

Logging

Use print(..., file=sys.stderr) for logging:

print("Debug info", file=sys.stderr)  # Good
print("Debug info")  # Bad - interferes with stdio

Exercises to Try

  1. Add a file_info tool

    • Return file size, modification time, and type
    • Hint: Use full_path.stat()
  2. Add a search_files tool

    • Search for text within files
    • Return matching files and line numbers
  3. Improve error handling

    • Return specific error messages for different error types
    • FileNotFoundError, PermissionError, etc.

Python vs TypeScript Version

If you're comparing this to the TypeScript version:

Feature Python TypeScript
Input validation Pydantic Zod
Tool registration Decorators (@server.call_tool()) Method calls (server.registerTool())
Async async/await async/await
Path handling pathlib.Path path module
Type hints Native Python TypeScript types

Both versions do the same thing - choose the language you're more comfortable with!

Common Python-Specific Issues

  1. Wrong Python version

    # Check version
    python --version  # Should be 3.10+
    
  2. Virtual environment not activated

    # You should see (venv) in your prompt
    # If not, activate it
    venv\Scripts\activate  # Windows
    
  3. Module not found

    # Make sure you installed dependencies
    pip install -r requirements.txt
    
  4. Path separators on Windows

    # Use pathlib - it handles Windows/Unix automatically
    Path("folder") / "file.txt"  # Works everywhere
    

Next Steps

After mastering this project:

  1. Add more tools (delete, rename, search)
  2. Add resources (learn resource templates in Python)
  3. Move to Project #2 (Note-Taking Server with persistence)
  4. Try the TypeScript version to compare languages

Resources

Troubleshooting

ImportError? Make sure virtual environment is activated and dependencies are installed

Server not responding? Check that you're using stdio transport correctly

Path errors? Remember all paths are relative to WORKSPACE_DIR

Need help? Check the MCP Discord or GitHub Issues

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
E2B

E2B

Using MCP to run code via e2b.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured