Skip to main content
Glama
Filesystem MCP Server

Filesystem MCP Server

by rajareddykr

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

Related MCP server: Filesystem MCP Server

Architecture

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

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:

git clone <repository-url>
cd mcp-filesystem-server
  1. Install dependencies:

npm install
  1. Build the server:

npm run build

Build Process

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

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

For Claude Desktop (stdio transport):

npm run fastmcp

For HTTP/SSE (Postman, web clients):

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

npm start

For HTTP transport:

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

# 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

{
  "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

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

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

Response:

{
  "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)

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)

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)

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:

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

{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "list_drives",
    "arguments": {}
  },
  "id": 1
}

Response:

{
  drives: string[];  // e.g., ["C:", "D:", "E:"]
}

list_directory

Lists directory contents with detailed metadata.

Parameters:

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

MCP Request:

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

Response:

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

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

MCP Request:

{
  "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:

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

MCP Request:

{
  "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:

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

MCP Request:

{
  "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:

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

MCP Request:

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

Response:

{
  content: string;  // File content as string
}

write_file

Writes content to a file (overwrites existing content).

Parameters:

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

MCP Request:

{
  "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:

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

MCP Request:

{
  "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:

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

MCP Request:

{
  "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:

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

MCP Request:

{
  "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:

interface DeleteFileParams {
    path: string;  // File path to delete
}

MCP Request:

{
  "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:

interface TouchFileParams {
    path: string;  // File path
}

MCP Request:

{
  "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:

interface AnalyzeTextParams {
    path: string; // File path
}

MCP Request:

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

Response:

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

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

MCP Request:

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

Response:

{
  hash: string;          // Hexadecimal hash string
  algorithm: string;     // Algorithm used
}

search_in_files

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

Parameters:

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

MCP Request:

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

Response:

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

interface FindDuplicatesParams {
    path: string; // Directory path
}

MCP Request:

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

Response:

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

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

MCP Request:

{
  "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:

interface ExtractZipParams {
    path: string;    // ZIP file path
    output: string;  // Output directory path
}

MCP Request:

{
  "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:

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

MCP Request:

{
  "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:

interface UnwatchDirectoryParams {
    path: string;  // Directory path to stop watching
}

MCP Request:

{
  "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:

interface GetPermissionsParams {
    path: string;  // File or directory path
}

MCP Request:

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

Response:

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

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:

{
  "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:

interface MakeExecutableParams {
    path: string;  // File path
}

MCP Request:

{
  "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:

interface GetMetadataParams {
    path: string;  // File or directory path
}

MCP Request:

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

Response:

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

interface CompareFilesParams {
    file1: string;  // First file path
    file2: string;  // Second file path
}

MCP Request:

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

Response:

{
  identical: boolean;
  differences?: {
    line: number;
    file1Content: string;
    file2Content: string;
  }[];
}

Creates a symbolic link to a file or directory.

Parameters:

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

MCP Request:

{
  "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:

interface StreamCopyParams {
    source: string;      // Source file path
    destination: string; // Destination file path
}

MCP Request:

{
  "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:

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:

{
  "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:

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

MCP Request:

{
  "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:

// 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

// 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)

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

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:

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:

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:

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:

npm run fastmcp  # or npm start

Schema Conversion

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

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

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:

{
  "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)

{
  "jsonrpc": "2.0",
  "error": {
    "code": -32602,
    "message": "ENOENT: no such file or directory, open 'D:\\missing.txt'"
  },
  "id": 1
}

Permission Denied (InternalError: -32603)

{
  "jsonrpc": "2.0",
  "error": {
    "code": -32603,
    "message": "EACCES: permission denied, access 'D:\\protected\\file.txt'"
  },
  "id": 1
}

Tool Not Found (MethodNotFound: -32601)

{
  "jsonrpc": "2.0",
  "error": {
    "code": -32601,
    "message": "Unknown tool: invalid_tool_name"
  },
  "id": 1
}

Invalid JSON (ParseError: -32700)

{
  "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

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

npm test

Run with coverage:

npm run test:coverage

Run specific test file:

npm test -- basic.test.ts

Watch mode:

npm test -- --watch

Code Quality

Lint the codebase:

npm run lint

Type check:

npm run type-check

Adding New Tools

  1. Create Operation Function (src/operations/yourfile.ts):

export async function yourOperation(params: YourParams): Promise<YourResult> {
    // Implementation
}
  1. Define Tool (src/tools/yourtools.ts):

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)
            }]
        };
    }
};
  1. Register Tool (src/tools/index.ts):

import { yourTool } from './yourtools.js';

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

// Register in registry
toolRegistry.registerTool(yourTool);
  1. Rebuild:

npm run build

Manual Testing

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

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

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

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:

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

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

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

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables file system operations such as listing directories, reading, writing, creating, and deleting files or directories through MCP.
      21 npm
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      MCP server for filesystem operations, enabling reading, writing, editing, moving, and searching files with dynamic directory access control via MCP Roots.
      -
    • A
      license
      Not graded
      quality
      B
      maintenance
      A local filesystem MCP server providing constrained file operations (read/write, directory management, search, metadata) within configurable directories, with read-only mode and zero runtime dependencies.
      4 npm
      MIT
    • F
      license
      B
      quality
      C
      maintenance
      Enables any MCP-compatible client to perform filesystem operations — reading, listing, writing, searching, watching directories, and batch processing files — over JSON-RPC 2.0 stdio transport. Includes resource discovery, metrics tracking, and security controls such as allowed roots, size limits, and format allowlists, with a LangGraph agent that accesses files exclusively through MCP.
      6
      -