Skip to main content
Glama
g-linville

File Server MCP

by g-linville
README.md
# File Server MCP

A hybrid REST + MCP file server built with Python, FastMCP, and UV. Provides both REST API endpoints (for web frontends) and MCP tools (for AI agents) to manage files with support for large file streaming.

## Features

- **Hybrid Interface**: Both REST API and MCP tools for maximum flexibility
- **Large File Support**: Streaming downloads with no size limits
- **Type Safety**: Full Pydantic validation across all interfaces
- **Security**: Path traversal prevention and configurable size limits
- **Async I/O**: Efficient file operations with aiofiles
- **Easy Configuration**: Environment-based settings

## Architecture

### MCP Tools (for AI Agents)

- `list_files_tool`: List all files with metadata
- `get_file_info_tool`: Get detailed file information
- `get_file_download_link_tool`: Get REST API download URL for large files
- `create_file_tool`: Create new files (text or base64 binary, 100MB limit)
- `delete_file_tool`: Delete files
- `replace_file_tool`: Replace file content (text or base64 binary, 100MB limit)

### REST API Endpoints

- `GET /api/files`: List all files
- `GET /api/files/{filename}`: Get file metadata
- `GET /api/files/{filename}/download`: Download file (streaming, no size limit)
- `DELETE /api/files/{filename}`: Delete file

### Utility Endpoints

- `GET /`: API information
- `GET /health`: Health check
- `GET /docs`: OpenAPI documentation

## Installation

### Prerequisites

- Python 3.11 or higher
- [UV](https://github.com/astral-sh/uv) package manager

### Install UV

```bash
# macOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh

# Windows
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
```

### Setup Project

```bash
# Clone or navigate to the project directory
cd file-server-mcp

# Install dependencies
uv sync

# Optional: Install development dependencies
uv sync --extra dev
```

## Configuration

Create a `.env` file in the project root (see `.env.example`):

```bash
FILE_SERVER_FILE_STORAGE_DIR=./file_storage
FILE_SERVER_MAX_UPLOAD_SIZE=104857600  # 100MB
FILE_SERVER_CHUNK_SIZE=1048576         # 1MB
```

### Environment Variables

- `FILE_SERVER_FILE_STORAGE_DIR`: Directory for file storage (default: `./file_storage`)
- `FILE_SERVER_MAX_UPLOAD_SIZE`: Maximum file size for uploads via MCP tools in bytes (default: 100MB)
- `FILE_SERVER_CHUNK_SIZE`: Chunk size for streaming downloads in bytes (default: 1MB)

## Usage

### Start the Server

```bash
# Run with UV
uv run python -m file_server_mcp

# Or with uvicorn directly
uv run uvicorn file_server_mcp.server:app --host 0.0.0.0 --port 8000 --reload
```

The server will start on `http://localhost:8000`.

### REST API Examples

```bash
# List all files
curl http://localhost:8000/api/files

# Get file info
curl http://localhost:8000/api/files/example.txt

# Download file
curl http://localhost:8000/api/files/example.txt/download -o downloaded.txt

# Delete file
curl -X DELETE http://localhost:8000/api/files/example.txt

# Health check
curl http://localhost:8000/health

# View OpenAPI docs
# Open http://localhost:8000/docs in your browser
```

### MCP Integration

#### Claude Desktop

Add to your `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "file-server": {
      "command": "uv",
      "args": [
        "--directory",
        "/absolute/path/to/file-server-mcp",
        "run",
        "python",
        "-m",
        "file_server_mcp"
      ],
      "env": {
        "FILE_SERVER_FILE_STORAGE_DIR": "/path/to/storage"
      }
    }
  }
}
```

#### MCP Inspector

```bash
# Install MCP Inspector
npm install -g @modelcontextprotocol/inspector

# Run the server with inspector
mcp-inspector uv --directory /path/to/file-server-mcp run python -m file_server_mcp
```

### Using MCP Tools

Once configured with Claude Desktop, you can ask Claude to:

```
"List all files in the file server"
"Get information about report.pdf"
"Create a new file called notes.txt with content 'Hello World'"
"Get a download link for large-video.mp4"
"Delete old-file.txt"
"Replace the content of config.json"
```

## Development

### Run Tests

```bash
# Run all tests
uv run pytest

# Run with coverage
uv run pytest --cov=file_server_mcp --cov-report=html

# Run specific test file
uv run pytest tests/test_storage.py

# Run with verbose output
uv run pytest -v
```

### Project Structure

```
file-server-mcp/
├── .python-version          # Python version
├── pyproject.toml           # UV configuration and dependencies
├── uv.lock                  # Auto-generated lockfile
├── .env.example             # Environment variable template
├── README.md                # This file
├── src/
│   └── file_server_mcp/
│       ├── __init__.py      # Package initialization
│       ├── __main__.py      # Entry point
│       ├── config.py        # Environment configuration
│       ├── models.py        # Pydantic schemas
│       ├── storage.py       # File operations
│       ├── rest_routes.py   # FastAPI REST endpoints
│       ├── mcp_tools.py     # MCP tool definitions
│       └── server.py        # Main hybrid server
└── tests/
    ├── __init__.py
    ├── conftest.py          # Pytest fixtures
    ├── test_storage.py      # Storage layer tests
    ├── test_rest_routes.py  # REST API tests
    └── test_mcp_tools.py    # MCP tools tests
```

## Large File Handling

### Strategy

- **REST Downloads**: Use streaming with `aiofiles` and `StreamingResponse` (no size limit)
- **MCP Tools**:
  - Direct content transfer limited to 100MB (configurable)
  - For larger files, use `get_file_download_link_tool` to get REST URL
  - AI agents can fetch large files via the REST endpoint

### Example: Handling Large PDFs

```python
# For small files (< 100MB), use MCP tool directly
create_file_tool(filename="small.pdf", content=base64_content, encoding="base64")

# For large files, use download link
link = get_file_download_link_tool(filename="large.pdf")
# Returns: {"filename": "large.pdf", "download_url": "/api/files/large.pdf/download"}
# Fetch via REST API using the download_url
```

## Security

### Path Traversal Prevention

All filenames are sanitized to prevent directory traversal attacks:

```python
# Input: "../../etc/passwd"
# Sanitized to: "passwd"
# Saved in: <storage_dir>/passwd
```

### Authentication

This is a prototype server without authentication. For production use:

- Add authentication middleware (e.g., API keys, OAuth)
- Implement authorization for file operations
- Use HTTPS for transport security
- Consider rate limiting

## Troubleshooting

### Server won't start

```bash
# Check Python version
python --version  # Should be 3.11+

# Reinstall dependencies
uv sync --reinstall

# Check storage directory permissions
ls -la ./file_storage
```

### MCP tools not appearing in Claude Desktop

1. Check `claude_desktop_config.json` is valid JSON
2. Verify the `command` path is absolute
3. Check Claude Desktop logs (Help → View Logs)
4. Restart Claude Desktop after config changes

### Tests failing

```bash
# Clear pytest cache
rm -rf .pytest_cache

# Run tests with verbose output
uv run pytest -vv

# Run a single test
uv run pytest tests/test_storage.py::test_sanitize_filename -v
```