File System MCP
Enable AI models to read, write, and manage files across different storage systems
Overview
The File System MCP provides AI models with controlled access to file systems, enabling them to read documents, write reports, manage data files, and organize content while maintaining security boundaries and access controls.
This protocol is essential for AI models that need to work with local files, process documents, generate reports, or manage data across different storage systems and cloud providers.
Architecture Overview
Implementation Guide
1. File System MCP Server
import { Server } from '@modelcontextprotocol/sdk/server'
import { FileSystemTool } from './tools/FileSystemTool'
import path from 'path'
const server = new Server({
name: 'file-system-mcp',
version: '1.0.0'
})
// Register file system tool
server.tool(new FileSystemTool({
allowedPaths: [
path.join(process.cwd(), 'data'),
path.join(process.cwd(), 'uploads'),
path.join(process.cwd(), 'reports')
],
blockedPaths: [
path.join(process.cwd(), 'node_modules'),
path.join(process.cwd(), '.git'),
path.join(process.cwd(), 'config')
],
maxFileSize: 10 * 1024 * 1024, // 10MB
allowedExtensions: ['.txt', '.md', '.json', '.csv', '.log']
}))
server.listen({
port: 3000,
host: 'localhost'
})
2. File System Tool Implementation
import { Tool } from '@modelcontextprotocol/sdk/server'
import fs from 'fs/promises'
import path from 'path'
interface FileSystemConfig {
allowedPaths: string[]
blockedPaths: string[]
maxFileSize: number
allowedExtensions: string[]
}
export class FileSystemTool extends Tool {
private config: FileSystemConfig
constructor(config: FileSystemConfig) {
super({
name: 'file_system',
description: 'Read, write, and manage files with security controls',
inputSchema: {
type: 'object',
properties: {
operation: { type: 'string', enum: ['read', 'write', 'list', 'delete', 'move'] },
path: { type: 'string' },
content: { type: 'string' },
destination: { type: 'string' }
},
required: ['operation', 'path']
}
})
this.config = config
}
async execute(input: any) {
// Validate path security
if (!this.isPathAllowed(input.path)) {
throw new Error(`Path ${input.path} not allowed`)
}
// Check file size for write operations
if (input.operation === 'write' && input.content) {
if (Buffer.byteLength(input.content, 'utf8') > this.config.maxFileSize) {
throw new Error('File size exceeds maximum allowed size')
}
}
// Execute operation
switch (input.operation) {
case 'read':
return await this.readFile(input.path)
case 'write':
return await this.writeFile(input.path, input.content)
case 'list':
return await this.listDirectory(input.path)
case 'delete':
return await this.deleteFile(input.path)
case 'move':
return await this.moveFile(input.path, input.destination)
default:
throw new Error(`Unknown operation: ${input.operation}`)
}
}
private isPathAllowed(filePath: string): boolean {
const resolvedPath = path.resolve(filePath)
// Check if path is in allowed directories
const isAllowed = this.config.allowedPaths.some(allowedPath =>
resolvedPath.startsWith(path.resolve(allowedPath))
)
// Check if path is in blocked directories
const isBlocked = this.config.blockedPaths.some(blockedPath =>
resolvedPath.startsWith(path.resolve(blockedPath))
)
return isAllowed && !isBlocked
}
private async readFile(filePath: string) {
try {
const content = await fs.readFile(filePath, 'utf8')
const stats = await fs.stat(filePath)
return {
content,
metadata: {
size: stats.size,
modified: stats.mtime,
created: stats.birthtime
}
}
} catch (error) {
throw new Error(`Failed to read file: ${error.message}`)
}
}
private async writeFile(filePath: string, content: string) {
try {
await fs.writeFile(filePath, content, 'utf8')
return { success: true, message: 'File written successfully' }
} catch (error) {
throw new Error(`Failed to write file: ${error.message}`)
}
}
private async listDirectory(dirPath: string) {
try {
const entries = await fs.readdir(dirPath, { withFileTypes: true })
return entries.map(entry => ({
name: entry.name,
type: entry.isDirectory() ? 'directory' : 'file',
path: path.join(dirPath, entry.name)
}))
} catch (error) {
throw new Error(`Failed to list directory: ${error.message}`)
}
}
private async deleteFile(filePath: string) {
try {
await fs.unlink(filePath)
return { success: true, message: 'File deleted successfully' }
} catch (error) {
throw new Error(`Failed to delete file: ${error.message}`)
}
}
private async moveFile(sourcePath: string, destinationPath: string) {
try {
await fs.rename(sourcePath, destinationPath)
return { success: true, message: 'File moved successfully' }
} catch (error) {
throw new Error(`Failed to move file: ${error.message}`)
}
}
}
3. Client Integration
import { Client } from '@modelcontextprotocol/sdk/client'
const client = new Client({
serverUrl: 'ws://localhost:3000'
})
// Example: Read a file
const fileContent = await client.tools.file_system.execute({
operation: 'read',
path: '/data/reports/monthly-summary.md'
})
console.log('File content:', fileContent.content)
// Example: Write a new file
const writeResult = await client.tools.file_system.execute({
operation: 'write',
path: '/data/reports/ai-generated-report.md',
content: '# AI Generated Report\n\nThis report was generated by an AI model...'
})
console.log('Write result:', writeResult)
// Example: List directory contents
const directoryContents = await client.tools.file_system.execute({
operation: 'list',
path: '/data/reports'
})
console.log('Directory contents:', directoryContents)
// Example: Move a file
const moveResult = await client.tools.file_system.execute({
operation: 'move',
path: '/data/reports/draft-report.md',
destination: '/data/reports/archived/draft-report.md'
})
console.log('Move result:', moveResult)
Security Features
Path Security
- • Path whitelisting and blacklisting
- • Directory traversal prevention
- • Symbolic link protection
- • Absolute path restrictions
- • Sandboxed file operations
Access Control
- • File size limits
- • Extension filtering
- • Operation permissions
- • User-based restrictions
- • Audit logging
Configuration Example
# file-system-mcp-config.yaml
server:
name: file-system-mcp
version: 1.0.0
port: 3000
host: localhost
file_system:
allowed_paths:
- /app/data
- /app/uploads
- /app/reports
- /app/temp
- /app/logs
blocked_paths:
- /app/config
- /app/secrets
- /app/node_modules
- /app/.git
- /etc
- /var/log
- /home
file_limits:
max_file_size: 10485760 # 10MB
max_directory_depth: 10
max_files_per_operation: 100
allowed_extensions:
- .txt
- .md
- .json
- .csv
- .log
- .xml
- .yaml
- .yml
blocked_extensions:
- .exe
- .bat
- .sh
- .ps1
- .jar
- .dll
- .so
operations:
read: true
write: true
list: true
delete: false # Disable deletion for safety
move: true
copy: true
security:
path_validation:
prevent_traversal: true
allow_absolute_paths: false
max_path_length: 500
content_validation:
scan_for_malware: true
validate_file_signatures: true
block_executable_content: true
audit_logging:
enabled: true
level: info
log_operations: true
log_file_access: true
storage: database
retention: 90d
monitoring:
metrics:
enabled: true
track_operations: true
track_file_sizes: true
track_access_patterns: true
alerts:
large_file_operations: true
suspicious_path_access: true
high_operation_frequency: true
Common Use Cases
Document Processing
AI models can read documents, extract information, and generate new reports while maintaining access to only authorized directories and file types.
Data Analysis
AI models can process CSV files, JSON data, and log files to perform analysis, generate insights, and create visualizations from structured data.
Content Management
AI models can organize files, create documentation, manage content workflows, and maintain file structures while respecting security boundaries.