Skip to main content
Glama
Filesystem MCP Server

Filesystem MCP Server

by rajareddykr
README.md
# Filesystem MCP Server
**$env:MCP_HTTP="1"; $env:MCP_PORT="3000"; node build/fastmcp-server.js

A Model Context Protocol (MCP) server implementation providing comprehensive file system operations, analysis, and manipulation capabilities through a standardized tool interface.

**Transport Protocol**: HTTP/HTTPS, TCP, stdio  
**Application Protocol**: Model Context Protocol (MCP) over JSON-RPC 2.0

## Features

✨ **29 Filesystem Tools** - Complete file system operations suite  
šŸš€ **Multiple Transports** - stdio, HTTP/SSE, and raw TCP support  
⚔ **FastMCP Integration** - Modern MCP server framework with automatic transport handling  
šŸ”’ **Type-Safe** - Full TypeScript implementation with strict typing  
šŸ“Š **Streaming Support** - Server-Sent Events (SSE) for real-time communication  
šŸŽÆ **MCP Protocol Compliant** - Full JSON-RPC 2.0 and MCP specification support

## Architecture

The server is built with multiple transport layers and organized into distinct operational layers:

```mermaid
graph TD
    A[Client: Claude Desktop / Postman / MCP Client] --> B{Transport Layer}
    B -->|stdio| C[StdioServerTransport]
    B -->|HTTP/SSE| D[FastMCP HTTP Transport]
    B -->|HTTP| E[Custom HTTP Transport]
    B -->|TCP| F[Custom TCP Transport]
    C --> G[MCP Server Layer]
    D --> G
    E --> G
    F --> G
    G --> H[Tool Registry]
    H --> I[Operations Layer]
    I --> J[File System Operations]
    I --> K[Analysis Operations]
    I --> L[Stream Operations]
    I --> M[Compression Operations]
    I --> N[Monitoring Operations]
```

### Components
- **Transport Layer**: Multiple transport options (stdio, HTTP/SSE, TCP)
- **MCP Server Layer**: Handles MCP protocol communication and tool dispatch
- **Tool Registry**: Manages 29 tools registration and execution
- **Operations Layer**: Implements core functionality across 8 categories
- **File System Interface**: Provides safe and efficient file system access

## Installation

1. Clone the repository:
```bash
git clone <repository-url>
cd mcp-filesystem-server
```

2. Install dependencies:
```bash
npm install
```

3. Build the server:
```bash
npm run build
```

## Build Process

This project is written in TypeScript. To build the server, run:

```bash
npm run build
```

This command uses the TypeScript compiler (`tsc`) to compile all source files from the `src/` directory into JavaScript in the `build/` directory. If you encounter any TypeScript errors, resolve them before running the build again.

- The build output will be placed in the `build/` directory.
- Make sure all dependencies are installed with `npm install` before building.

## Running the Server

### Option 1: FastMCP Server (Recommended)

**For Claude Desktop (stdio transport):**
```bash
npm run fastmcp
```

**For HTTP/SSE (Postman, web clients):**
```bash
# Windows PowerShell
$env:MCP_HTTP="1"; $env:MCP_PORT="3000"; npm run fastmcp

# Linux/Mac
MCP_HTTP=1 MCP_PORT=3000 npm run fastmcp
```

**FastMCP Endpoints:**
- `GET http://localhost:3000/sse` - Server-Sent Events endpoint
- `POST http://localhost:3000/message` - JSON-RPC message endpoint

### Option 2: Original Server with Custom Transports

**For stdio transport:**
```bash
npm start
```

**For HTTP transport:**
```bash
# Windows PowerShell
$env:MCP_HTTP="1"; $env:MCP_PORT="3000"; npm start

# Linux/Mac
MCP_HTTP=1 MCP_PORT=3000 npm start
```

**Original Server Endpoints:**
- `POST http://localhost:3000/mcp` - JSON-RPC endpoint
- `GET http://localhost:3000/sse` - Server-Sent Events
- `GET http://localhost:3000/tools` - List all tools
- `GET http://localhost:3000/health` - Health check

### Option 3: TCP Transport (Raw Socket)

```bash
# Windows PowerShell
$env:MCP_TCP="1"; $env:MCP_PORT="3000"; npm start

# Linux/Mac
MCP_TCP=1 MCP_PORT=3000 npm start
```

## MCP Protocol Usage

### Using with Claude Desktop

Configure in your Claude Desktop MCP settings file:

**Windows**: `%APPDATA%\Claude\claude_desktop_config.json`  
**macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`  
**Linux**: `~/.config/Claude/claude_desktop_config.json`

```json
{
  "mcpServers": {
    "filesystem": {
      "command": "node",
      "args": ["D:/MCP-Servers/mcp-filesystem-server/build/fastmcp-server.js"]
    }
  }
}
```

### Using with Postman (HTTP/MCP Protocol)

**1. List All Available Tools**

```http
POST http://localhost:3000/message
Content-Type: application/json

{
  "jsonrpc": "2.0",
  "method": "tools/list",
  "id": 1
}
```

**Response:**
```json
{
  "jsonrpc": "2.0",
  "result": {
    "tools": [
      {
        "name": "list_directory",
        "description": "List directory contents with metadata",
        "inputSchema": { ... }
      },
      ...29 tools total...
    ]
  },
  "id": 1
}
```

**2. Call a Tool (Example: Read File)**

```http
POST http://localhost:3000/message
Content-Type: application/json

{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "read_file",
    "arguments": {
      "path": "D:\\test.txt"
    }
  },
  "id": 2
}
```

**3. Call a Tool (Example: List Directory)**

```http
POST http://localhost:3000/message
Content-Type: application/json

{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "list_directory",
    "arguments": {
      "path": "D:\\MCP-Servers",
      "recursive": false
    }
  },
  "id": 3
}
```

**4. Using SSE Endpoint (Server-Sent Events)**

```http
GET http://localhost:3000/sse
```

This establishes a persistent connection for streaming MCP messages.

## Configuration

### Environment Variables

| Variable | Description | Default | Example |
|----------|-------------|---------|---------|
| `MCP_HTTP` | Enable HTTP transport | `0` | `1` |
| `MCP_TCP` | Enable TCP transport | `0` | `1` |
| `MCP_PORT` | Server port | `3000` | `3001` |

### Transport Selection

The server automatically selects transport based on environment variables:

```bash
# stdio (default)
npm run fastmcp

# HTTP/SSE
MCP_HTTP=1 npm run fastmcp

# TCP (original server only)
MCP_TCP=1 npm start
```

## Tool Reference

### Complete Tool List (29 Tools)

The server provides 29 comprehensive filesystem tools organized into 8 categories:

#### šŸ—‚ļø System Operations (2 tools)
- `list_drives` - List all available drives/volumes
- `list_directory` - List directory contents with metadata

#### šŸ“ Directory Operations (3 tools)
- `make_directory` - Create a new directory
- `remove_directory` - Remove a directory
- `copy_directory` - Copy a directory recursively

#### šŸ“„ File Operations (6 tools)
- `read_file` - Read file content with encoding support
- `write_file` - Write content to a file
- `append_file` - Append content to a file
- `copy_file` - Copy a file
- `move_file` - Move/rename a file
- `delete_file` - Delete a file
- `touch_file` - Update file timestamps or create empty file

#### šŸ” Search & Analysis (4 tools)
- `search_in_files` - Search for text/regex pattern in files
- `calculate_hash` - Calculate file hash (MD5, SHA256, etc.)
- `analyze_text` - Analyze text file properties
- `find_duplicates` - Find duplicate files in directory

#### šŸ—œļø Compression (2 tools)
- `create_zip` - Create ZIP archive from files
- `extract_zip` - Extract ZIP archive

#### šŸ‘ļø Monitoring (2 tools)
- `watch_directory` - Start watching a directory for changes
- `unwatch_directory` - Stop watching a directory

#### šŸ” Permissions & Metadata (4 tools)
- `get_permissions` - Get file permissions
- `set_permissions` - Set file permissions
- `make_executable` - Make file executable
- `get_metadata` - Get extended file metadata

#### šŸ”— Advanced Operations (6 tools)
- `compare_files` - Compare two files
- `create_symlink` - Create a symbolic link
- `stream_copy` - Copy file using streams
- `write_chunks` - Write data chunks to a file with streaming
- `transform_file` - Transform file contents line by line

---

### Detailed Tool Documentation

#### list_drives
Lists all available drives/volumes on the system.

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "list_drives",
    "arguments": {}
  },
  "id": 1
}
```

**Response:**
```typescript
{
  drives: string[];  // e.g., ["C:", "D:", "E:"]
}
```
#### list_directory
Lists directory contents with detailed metadata.

**Parameters:**
```typescript
interface ListDirectoryParams {
    path: string;       // Directory path
    recursive?: boolean; // List recursively (default: false)
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "list_directory",
    "arguments": {
      "path": "D:\\Projects",
      "recursive": false
    }
  },
  "id": 2
}
```

**Response:**
```typescript
{
  entries: {
    name: string;
    path: string;
    isDirectory: boolean;
    size: number;
    created: string;      // ISO 8601 timestamp
    modified: string;     // ISO 8601 timestamp
    accessed: string;     // ISO 8601 timestamp
    mode: string;         // File permissions (octal)
  }[];
}
```

#### make_directory
Creates a new directory with optional recursive parent creation.

**Parameters:**
```typescript
interface CreateDirectoryParams {
    path: string;       // Directory path
    recursive?: boolean; // Create parent directories (default: true)
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "make_directory",
    "arguments": {
      "path": "D:\\Projects\\NewFolder",
      "recursive": true
    }
  },
  "id": 3
}
```

#### remove_directory
Removes a directory with optional recursive deletion.

**Parameters:**
```typescript
interface RemoveDirectoryParams {
    path: string;       // Directory path
    recursive?: boolean; // Remove contents recursively (default: false)
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "remove_directory",
    "arguments": {
      "path": "D:\\Projects\\OldFolder",
      "recursive": true
    }
  },
  "id": 4
}
```

#### copy_directory
Copies a directory recursively to a new location.

**Parameters:**
```typescript
interface CopyDirectoryParams {
    source: string;      // Source directory path
    destination: string; // Destination directory path
    overwrite?: boolean; // Overwrite existing (default: false)
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "copy_directory",
    "arguments": {
      "source": "D:\\Projects\\Source",
      "destination": "D:\\Backup\\Source",
      "overwrite": false
    }
  },
  "id": 5
}
```
### File Operations

#### read_file
Reads file content with encoding support.

**Parameters:**
```typescript
interface ReadFileParams {
    path: string;     // File path
    encoding?: string; // File encoding (default: 'utf8')
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "read_file",
    "arguments": {
      "path": "D:\\Projects\\config.json",
      "encoding": "utf8"
    }
  },
  "id": 6
}
```

**Response:**
```typescript
{
  content: string;  // File content as string
}
```

#### write_file
Writes content to a file (overwrites existing content).

**Parameters:**
```typescript
interface WriteFileParams {
    path: string;     // File path
    content: string;  // Content to write
    encoding?: string; // File encoding (default: 'utf8')
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "write_file",
    "arguments": {
      "path": "D:\\Projects\\output.txt",
      "content": "Hello, World!",
      "encoding": "utf8"
    }
  },
  "id": 7
}
```

#### append_file
Appends content to an existing file.

**Parameters:**
```typescript
interface AppendFileParams {
    path: string;     // File path
    content: string;  // Content to append
    encoding?: string; // File encoding (default: 'utf8')
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "append_file",
    "arguments": {
      "path": "D:\\Projects\\log.txt",
      "content": "\\nNew log entry",
      "encoding": "utf8"
    }
  },
  "id": 8
}
```

#### copy_file
Copies a file to a new location.

**Parameters:**
```typescript
interface CopyFileParams {
    source: string;      // Source file path
    destination: string; // Destination file path
    overwrite?: boolean; // Overwrite existing (default: false)
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "copy_file",
    "arguments": {
      "source": "D:\\Projects\\file.txt",
      "destination": "D:\\Backup\\file.txt",
      "overwrite": true
    }
  },
  "id": 9
}
```

#### move_file
Moves or renames a file.

**Parameters:**
```typescript
interface MoveFileParams {
    source: string;      // Source file path
    destination: string; // Destination file path
    overwrite?: boolean; // Overwrite existing (default: false)
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "move_file",
    "arguments": {
      "source": "D:\\Projects\\old_name.txt",
      "destination": "D:\\Projects\\new_name.txt",
      "overwrite": false
    }
  },
  "id": 10
}
```

#### delete_file
Deletes a file.

**Parameters:**
```typescript
interface DeleteFileParams {
    path: string;  // File path to delete
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "delete_file",
    "arguments": {
      "path": "D:\\Projects\\temp.txt"
    }
  },
  "id": 11
}
```

#### touch_file
Updates file timestamps or creates an empty file if it doesn't exist.

**Parameters:**
```typescript
interface TouchFileParams {
    path: string;  // File path
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "touch_file",
    "arguments": {
      "path": "D:\\Projects\\empty.txt"
    }
  },
  "id": 12
}
```
### Analysis Operations

#### analyze_text
Analyzes text file properties including line count, word count, character count, encoding, and MIME type.

**Parameters:**
```typescript
interface AnalyzeTextParams {
    path: string; // File path
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "analyze_text",
    "arguments": {
      "path": "D:\\Projects\\document.txt"
    }
  },
  "id": 13
}
```

**Response:**
```typescript
{
  lineCount: number;
  wordCount: number;
  charCount: number;
  encoding: string;      // e.g., "UTF-8", "ASCII"
  mimeType: string;      // e.g., "text/plain"
}
```

#### calculate_hash
Calculates file hash using specified algorithm.

**Parameters:**
```typescript
interface CalculateHashParams {
    path: string;           // File path
    algorithm?: 'md5' | 'sha1' | 'sha256' | 'sha512'; // Hash algorithm (default: 'sha256')
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "calculate_hash",
    "arguments": {
      "path": "D:\\Projects\\file.zip",
      "algorithm": "sha256"
    }
  },
  "id": 14
}
```

**Response:**
```typescript
{
  hash: string;          // Hexadecimal hash string
  algorithm: string;     // Algorithm used
}
```

#### search_in_files
Searches for text or regex pattern in files within a directory.

**Parameters:**
```typescript
interface SearchInFilesParams {
    path: string;       // Directory path to search in
    pattern: string;    // Regular expression pattern
    recursive?: boolean; // Search recursively (default: true)
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "search_in_files",
    "arguments": {
      "path": "D:\\Projects",
      "pattern": "TODO",
      "recursive": true
    }
  },
  "id": 15
}
```

**Response:**
```typescript
{
  matches: {
    file: string;      // File path
    line: number;      // Line number
    content: string;   // Line content
    match: string;     // Matched text
  }[];
}
```

#### find_duplicates
Identifies duplicate files in a directory based on content hash.

**Parameters:**
```typescript
interface FindDuplicatesParams {
    path: string; // Directory path
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "find_duplicates",
    "arguments": {
      "path": "D:\\Downloads"
    }
  },
  "id": 16
}
```

**Response:**
```typescript
{
  duplicates: {
    hash: string;      // Content hash
    size: number;      // File size in bytes
    files: string[];   // Array of duplicate file paths
  }[];
}
```

### Compression Operations

#### create_zip
Creates a ZIP archive from specified files.

**Parameters:**
```typescript
interface CreateZipParams {
    files: string[];  // Array of file paths to include
    output: string;   // Output ZIP file path
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "create_zip",
    "arguments": {
      "files": [
        "D:\\Projects\\file1.txt",
        "D:\\Projects\\file2.txt"
      ],
      "output": "D:\\Backup\\archive.zip"
    }
  },
  "id": 17
}
```

#### extract_zip
Extracts contents of a ZIP archive.

**Parameters:**
```typescript
interface ExtractZipParams {
    path: string;    // ZIP file path
    output: string;  // Output directory path
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "extract_zip",
    "arguments": {
      "path": "D:\\Downloads\\archive.zip",
      "output": "D:\\Extracted"
    }
  },
  "id": 18
}
```

### Monitoring Operations

#### watch_directory
Starts monitoring a directory for file system changes (create, modify, delete).

**Parameters:**
```typescript
interface WatchDirectoryParams {
    path: string;       // Directory path to watch
    recursive?: boolean; // Watch subdirectories (default: false)
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "watch_directory",
    "arguments": {
      "path": "D:\\Projects\\src",
      "recursive": true
    }
  },
  "id": 19
}
```

#### unwatch_directory
Stops monitoring a previously watched directory.

**Parameters:**
```typescript
interface UnwatchDirectoryParams {
    path: string;  // Directory path to stop watching
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "unwatch_directory",
    "arguments": {
      "path": "D:\\Projects\\src"
    }
  },
  "id": 20
}
```

### Permissions & Metadata Operations

#### get_permissions
Retrieves file or directory permissions.

**Parameters:**
```typescript
interface GetPermissionsParams {
    path: string;  // File or directory path
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "get_permissions",
    "arguments": {
      "path": "D:\\Projects\\script.sh"
    }
  },
  "id": 21
}
```

**Response:**
```typescript
{
  owner: {
    read: boolean;
    write: boolean;
    execute: boolean;
  };
  group: {
    read: boolean;
    write: boolean;
    execute: boolean;
  };
  others: {
    read: boolean;
    write: boolean;
    execute: boolean;
  };
}
```

#### set_permissions
Sets file or directory permissions.

**Parameters:**
```typescript
interface SetPermissionsParams {
    path: string;
    permissions: {
        owner?: { read?: boolean; write?: boolean; execute?: boolean; };
        group?: { read?: boolean; write?: boolean; execute?: boolean; };
        others?: { read?: boolean; write?: boolean; execute?: boolean; };
    };
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "set_permissions",
    "arguments": {
      "path": "D:\\Projects\\script.sh",
      "permissions": {
        "owner": { "read": true, "write": true, "execute": true }
      }
    }
  },
  "id": 22
}
```

#### make_executable
Makes a file executable (shorthand for setting execute permission).

**Parameters:**
```typescript
interface MakeExecutableParams {
    path: string;  // File path
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "make_executable",
    "arguments": {
      "path": "D:\\Projects\\script.sh"
    }
  },
  "id": 23
}
```

#### get_metadata
Retrieves extended file metadata including size, timestamps, and type.

**Parameters:**
```typescript
interface GetMetadataParams {
    path: string;  // File or directory path
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "get_metadata",
    "arguments": {
      "path": "D:\\Projects\\document.pdf"
    }
  },
  "id": 24
}
```

**Response:**
```typescript
{
  size: number;           // File size in bytes
  created: string;        // ISO 8601 timestamp
  modified: string;       // ISO 8601 timestamp
  accessed: string;       // ISO 8601 timestamp
  isDirectory: boolean;
  isFile: boolean;
  mimeType: string;
}
```

### Advanced Operations

#### compare_files
Compares two files byte-by-byte or line-by-line.

**Parameters:**
```typescript
interface CompareFilesParams {
    file1: string;  // First file path
    file2: string;  // Second file path
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "compare_files",
    "arguments": {
      "file1": "D:\\Projects\\version1.txt",
      "file2": "D:\\Projects\\version2.txt"
    }
  },
  "id": 25
}
```

**Response:**
```typescript
{
  identical: boolean;
  differences?: {
    line: number;
    file1Content: string;
    file2Content: string;
  }[];
}
```

#### create_symlink
Creates a symbolic link to a file or directory.

**Parameters:**
```typescript
interface CreateSymlinkParams {
    target: string;  // Target path (what the link points to)
    link: string;    // Link path (where to create the symlink)
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "create_symlink",
    "arguments": {
      "target": "D:\\Projects\\original",
      "link": "D:\\Links\\shortcut"
    }
  },
  "id": 26
}
```

#### stream_copy
Copies a file using Node.js streams for efficient large file handling.

**Parameters:**
```typescript
interface StreamCopyParams {
    source: string;      // Source file path
    destination: string; // Destination file path
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "stream_copy",
    "arguments": {
      "source": "D:\\Videos\\large-video.mp4",
      "destination": "D:\\Backup\\large-video.mp4"
    }
  },
  "id": 27
}
```

#### write_chunks
Writes data chunks to a file with streaming support, useful for incremental writes.

**Parameters:**
```typescript
interface WriteChunksParams {
    path: string;       // Destination file path
    chunks: string[];   // Array of data chunks to write
    encoding?: 'utf8' | 'base64' | 'hex' | 'ascii' | 'binary';  // Encoding (default: 'utf8')
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "write_chunks",
    "arguments": {
      "path": "D:\\Output\\data.txt",
      "chunks": ["chunk1", "chunk2", "chunk3"],
      "encoding": "utf8"
    }
  },
  "id": 28
}
```

#### transform_file
Transforms file contents line-by-line with a custom JavaScript function using streaming.

**Parameters:**
```typescript
interface TransformFileParams {
    source: string;       // Source file path
    destination: string;  // Destination file path
    transform: string;    // JavaScript function as string (receives line as parameter)
}
```

**MCP Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "transform_file",
    "arguments": {
      "source": "D:\\Input\\data.txt",
      "destination": "D:\\Output\\uppercase.txt",
      "transform": "line => line.toUpperCase()"
    }
  },
  "id": 29
}
```

**Examples of Transform Functions:**
```javascript
// Convert to uppercase
"line => line.toUpperCase()"

// Trim whitespace
"line => line.trim()"

// Add prefix
"line => '> ' + line"

// Filter lines (return empty string to exclude)
"line => line.startsWith('#') ? '' : line"

// Replace text
"line => line.replace(/old/g, 'new')"
```

## FastMCP Implementation Details

### What is FastMCP?

FastMCP is a modern TypeScript framework that simplifies building MCP (Model Context Protocol) servers. It provides:

- **Automatic Transport Handling**: Seamlessly switches between stdio and HTTP/SSE
- **Built-in HTTP Server**: Uses Hono web framework for high performance
- **Zod Schema Validation**: Type-safe parameter validation
- **OAuth Support**: Ready for authentication flows (extensible)
- **Streaming Support**: Native Server-Sent Events (SSE) implementation

### Architecture Comparison

#### Traditional MCP Server
```typescript
// Manual transport setup
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

const server = new Server({ name: 'my-server', version: '1.0.0' });
const transport = new StdioServerTransport();
await server.connect(transport);

// Manual tool registration with JSON Schema
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  // Handle tool calls manually
});
```

#### FastMCP Server (This Implementation)
```typescript
// Automatic transport and simpler API
import { FastMCP } from 'fastmcp';

const mcp = new FastMCP({
  name: 'my-server',
  version: '1.0.0'
});

// Clean tool registration with Zod schemas
mcp.addTool({
  name: 'my_tool',
  description: 'Tool description',
  parameters: z.object({ path: z.string() }),
  execute: async (params) => {
    return 'Result';
  }
});

// Start with automatic transport detection
await mcp.start({ transportType: 'httpStream', httpStream: { port: 3000 } });
```

### Transport Layer Architecture

This server implements three transport mechanisms:

#### 1. FastMCP HTTP/SSE Transport (Recommended)
**File**: `src/fastmcp-server.ts`

- Built on Hono web framework
- Native SSE support for streaming
- Automatic JSON-RPC handling
- Stateless session management

**Endpoints**:
- `POST /message` - JSON-RPC 2.0 messages
- `GET /sse` - Server-Sent Events stream

**Usage**:
```bash
MCP_HTTP=1 MCP_PORT=3000 npm run fastmcp
```

#### 2. Custom HTTP Transport
**File**: `src/http-transport.ts`

- Built on Express
- Custom MCP protocol implementation
- Additional REST endpoints for convenience

**Endpoints**:
- `POST /mcp` - JSON-RPC 2.0 endpoint
- `GET /sse` - Server-Sent Events
- `GET /tools` - List all tools (convenience endpoint)
- `GET /health` - Health check

**Usage**:
```bash
MCP_HTTP=1 npm start
```

#### 3. Custom TCP Transport
**File**: `src/tcp-transport.ts`

- Raw TCP socket communication
- Custom implementation of MCP over TCP
- Direct socket connection for clients

**Usage**:
```bash
MCP_TCP=1 MCP_PORT=3000 npm start
```

#### 4. stdio Transport
**Default transport for CLI tools and Claude Desktop**

- Standard input/output communication
- No network layer required
- Process-based communication

**Usage**:
```bash
npm run fastmcp  # or npm start
```

### Schema Conversion

The FastMCP server converts JSON Schema (used by the tool registry) to Zod schemas:

```typescript
// JSON Schema (Tool Registry)
{
  type: 'object',
  properties: {
    path: { type: 'string' },
    recursive: { type: 'boolean', default: false }
  },
  required: ['path']
}

// Converted to Zod Schema (FastMCP)
z.object({
  path: z.string(),
  recursive: z.boolean().default(false).optional()
})
```

This allows seamless integration between the existing tool definitions and FastMCP's type-safe parameter validation.

### Server Comparison

| Feature | FastMCP Server | Original Server |
|---------|---------------|-----------------|
| **Transport** | HTTP/SSE, stdio | HTTP, TCP, stdio |
| **Framework** | Hono (FastMCP) | Express (custom) |
| **Schema** | Zod (auto-converted) | JSON Schema |
| **Endpoint** | `/message`, `/sse` | `/mcp`, `/sse`, `/tools`, `/health` |
| **Setup Complexity** | Low (automatic) | Medium (manual) |
| **Maintenance** | Framework-managed | Custom code |
| **OAuth Ready** | Yes (built-in) | No |
| **Recommended For** | Production, Claude Desktop | Testing, custom integrations |

## Error Handling

The server uses standard MCP error codes following JSON-RPC 2.0 specification:

```typescript
enum ErrorCode {
    ParseError = -32700,       // Invalid JSON
    InvalidRequest = -32600,   // Invalid JSON-RPC request
    MethodNotFound = -32601,   // Method does not exist
    InvalidParams = -32602,    // Invalid method parameters
    InternalError = -32603     // Internal server error
}
```

### Error Response Format

**MCP Error Response:**
```json
{
  "jsonrpc": "2.0",
  "error": {
    "code": -32602,
    "message": "File not found: /path/to/file.txt",
    "data": {
      "path": "/path/to/file.txt",
      "operation": "read_file"
    }
  },
  "id": 1
}
```

### Common Errors

#### File Not Found (InvalidParams: -32602)
```json
{
  "jsonrpc": "2.0",
  "error": {
    "code": -32602,
    "message": "ENOENT: no such file or directory, open 'D:\\missing.txt'"
  },
  "id": 1
}
```

#### Permission Denied (InternalError: -32603)
```json
{
  "jsonrpc": "2.0",
  "error": {
    "code": -32603,
    "message": "EACCES: permission denied, access 'D:\\protected\\file.txt'"
  },
  "id": 1
}
```

#### Tool Not Found (MethodNotFound: -32601)
```json
{
  "jsonrpc": "2.0",
  "error": {
    "code": -32601,
    "message": "Unknown tool: invalid_tool_name"
  },
  "id": 1
}
```

#### Invalid JSON (ParseError: -32700)
```json
{
  "jsonrpc": "2.0",
  "error": {
    "code": -32700,
    "message": "Parse error: Unexpected token in JSON at position 15"
  },
  "id": null
}
```

## Development

### Project Structure

```
mcp-filesystem-server/
ā”œā”€ā”€ src/
│   ā”œā”€ā”€ index.ts                 # Original server entry point
│   ā”œā”€ā”€ fastmcp-server.ts        # FastMCP server entry point (recommended)
│   ā”œā”€ā”€ server.ts                # MCP server configuration
│   ā”œā”€ā”€ types.ts                 # TypeScript type definitions
│   ā”œā”€ā”€ utils.ts                 # Utility functions
│   ā”œā”€ā”€ tcp-transport.ts         # Custom TCP transport
│   ā”œā”€ā”€ http-transport.ts        # Custom HTTP transport
│   ā”œā”€ā”€ operations/              # Core filesystem operations
│   │   ā”œā”€ā”€ basic.ts            # Basic file operations
│   │   ā”œā”€ā”€ directory.ts        # Directory operations
│   │   ā”œā”€ā”€ analysis.ts         # File analysis tools
│   │   ā”œā”€ā”€ compression.ts      # ZIP operations
│   │   ā”œā”€ā”€ monitoring.ts       # File watching
│   │   ā”œā”€ā”€ permissions.ts      # Permission management
│   │   ā”œā”€ā”€ metadata.ts         # Metadata operations
│   │   └── streams.ts          # Streaming operations
│   ā”œā”€ā”€ tools/                   # Tool definitions and registry
│   │   ā”œā”€ā”€ index.ts            # Main registry export
│   │   ā”œā”€ā”€ registry.ts         # Tool registry implementation
│   │   ā”œā”€ā”€ types.ts            # Tool type definitions
│   │   ā”œā”€ā”€ files.ts            # File tool definitions
│   │   ā”œā”€ā”€ directories.ts      # Directory tool definitions
│   │   ā”œā”€ā”€ analysis.ts         # Analysis tool definitions
│   │   ā”œā”€ā”€ compression.ts      # Compression tool definitions
│   │   ā”œā”€ā”€ monitoring.ts       # Monitoring tool definitions
│   │   ā”œā”€ā”€ permissions.ts      # Permission tool definitions
│   │   ā”œā”€ā”€ metadata.ts         # Metadata tool definitions
│   │   ā”œā”€ā”€ streams.ts          # Stream tool definitions
│   │   └── system.ts           # System tool definitions
│   └── __tests__/               # Test files
│       ā”œā”€ā”€ setup.ts
│       └── operations/
│           ā”œā”€ā”€ basic.test.ts
│           ā”œā”€ā”€ directory.test.ts
│           ā”œā”€ā”€ analysis.test.ts
│           ā”œā”€ā”€ compression.test.ts
│           ā”œā”€ā”€ monitoring.test.ts
│           ā”œā”€ā”€ permissions.test.ts
│           ā”œā”€ā”€ metadata.test.ts
│           └── streams.test.ts
ā”œā”€ā”€ build/                       # Compiled JavaScript output
ā”œā”€ā”€ node_modules/               # Dependencies
ā”œā”€ā”€ package.json                # Project configuration
ā”œā”€ā”€ tsconfig.json               # TypeScript configuration
ā”œā”€ā”€ jest.config.js              # Jest test configuration
└── README.md                   # This file
```

### Building from Source

```bash
# Install dependencies
npm install

# Compile TypeScript to JavaScript
npm run build

# Watch mode (auto-rebuild on changes)
npm run dev
```

### Running Tests

Run the test suite:
```bash
npm test
```

Run with coverage:
```bash
npm run test:coverage
```

Run specific test file:
```bash
npm test -- basic.test.ts
```

Watch mode:
```bash
npm test -- --watch
```

### Code Quality

Lint the codebase:
```bash
npm run lint
```

Type check:
```bash
npm run type-check
```

### Adding New Tools

1. **Create Operation Function** (`src/operations/yourfile.ts`):
```typescript
export async function yourOperation(params: YourParams): Promise<YourResult> {
    // Implementation
}
```

2. **Define Tool** (`src/tools/yourtools.ts`):
```typescript
import { Tool } from './types.js';
import { yourOperation } from '../operations/yourfile.js';

export const yourTool: Tool = {
    name: 'your_tool',
    description: 'Tool description',
    inputSchema: {
        type: 'object',
        properties: {
            param: { type: 'string', description: 'Parameter description' }
        },
        required: ['param']
    },
    handler: async (args: any) => {
        const result = await yourOperation(args);
        return {
            content: [{
                type: 'text',
                text: JSON.stringify(result, null, 2)
            }]
        };
    }
};
```

3. **Register Tool** (`src/tools/index.ts`):
```typescript
import { yourTool } from './yourtools.js';

// Add to exports
export { yourTool } from './yourtools.js';

// Register in registry
toolRegistry.registerTool(yourTool);
```

4. **Rebuild**:
```bash
npm run build
```

### Manual Testing

**PowerShell:**
```powershell
$body = @{
    jsonrpc = "2.0"
    method = "tools/call"
    params = @{
        name = "list_directory"
        arguments = @{
            path = "D:\Projects"
            recursive = $false
        }
    }
    id = 1
} | ConvertTo-Json -Depth 10

Invoke-WebRequest -Uri "http://localhost:3000/message" `
  -Method POST `
  -Headers @{"Content-Type"="application/json"} `
  -Body $body `
  -UseBasicParsing | Select-Object -ExpandProperty Content
```

**curl (Linux/Mac):**
```bash
curl -X POST http://localhost:3000/message \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc":"2.0",
    "method":"tools/call",
    "params":{
      "name":"list_drives",
      "arguments":{}
    },
    "id":1
  }'
```

## Deployment

### Production Deployment with PM2

```bash
# Install PM2 globally
npm install -g pm2

# Start FastMCP server
pm2 start build/fastmcp-server.js \
  --name mcp-filesystem \
  -i 1 \
  --env production

# Set environment variables
pm2 restart mcp-filesystem --update-env \
  --env MCP_HTTP=1 \
  --env MCP_PORT=3000

# View logs
pm2 logs mcp-filesystem

# Monitor
pm2 monit

# Save configuration
pm2 save

# Setup startup script
pm2 startup
```

### Docker Deployment

**Dockerfile:**
```dockerfile
FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm ci --only=production

COPY build ./build

ENV NODE_ENV=production
ENV MCP_HTTP=1
ENV MCP_PORT=3000

EXPOSE 3000

CMD ["node", "build/fastmcp-server.js"]
```

**Build and Run:**
```bash
docker build -t mcp-filesystem-server .
docker run -d -p 3000:3000 --name mcp-filesystem mcp-filesystem-server
docker logs -f mcp-filesystem
```

### systemd Service (Linux)

**File**: `/etc/systemd/system/mcp-filesystem.service`
```ini
[Unit]
Description=MCP Filesystem Server
After=network.target

[Service]
Type=simple
User=mcpuser
WorkingDirectory=/opt/mcp-filesystem-server
Environment="NODE_ENV=production"
Environment="MCP_HTTP=1"
Environment="MCP_PORT=3000"
ExecStart=/usr/bin/node /opt/mcp-filesystem-server/build/fastmcp-server.js
Restart=on-failure
RestartSec=10s

[Install]
WantedBy=multi-user.target
```

**Commands:**
```bash
sudo systemctl daemon-reload
sudo systemctl enable mcp-filesystem
sudo systemctl start mcp-filesystem
sudo systemctl status mcp-filesystem
```

## Dependencies

Core dependencies:
- @modelcontextprotocol/sdk: MCP server implementation
- file-type: File type detection
- mime-types: MIME type lookup
- crypto-js: File hashing
- archiver: ZIP creation
- extract-zip: ZIP extraction
- iconv-lite: Text encoding
- chardet: Encoding detection

Development dependencies:
- typescript: Type system
- jest: Testing
- eslint: Linting
- prettier: Formatting
- ts-node: TypeScript execution
- nodemon: Development server

## Contributing

1. Fork the repository
2. Create your feature branch
3. Write tests for new features
4. Ensure all tests pass
5. Submit a pull request

## License

MIT