All projects

AI agents & MCP

File Operations MCP

File, text and data tools for MCP, in Java.

File and directory management, regex search, text processing, checksums, ZIP archives and JSON/CSV handling behind one MCP interface.

Why I built it

I wanted one MCP server that covers the everyday file chores an assistant runs into: reading and searching, checksums, archives and JSON or CSV data.

Architecture

How it fits together

AI client

  • Any MCP app

Java MCP server

  • Files and folders

  • Text processing

  • Checksums and ZIP

  • JSON and CSV

Your disk

  • Local file system

Documentation

From the README

Open on GitHub

A comprehensive Java-based Model Context Protocol (MCP) server that provides extensive file system operations, text processing, data analysis, and structured data handling capabilities. Built with enterprise-grade architecture following industry best practices.

๐Ÿš€ Features

Core File Operations

  • File Management: Create, read, write, delete, copy, move, and rename files
  • Directory Operations: Create, delete, rename, and list directories with advanced filtering
  • File Information: Get detailed metadata, permissions, timestamps, and file statistics
  • Search & Discovery: Pattern-based file searching with regex support

Advanced Operations

  • Text Processing: Find/replace text, file comparison, line counting with statistics
  • Checksum Calculation: Support for MD5, SHA1, SHA256 algorithms
  • Archive Creation: Create ZIP archives with compression level control
  • Batch Operations: Bulk file renaming with pattern matching and preview mode

Structured Data Support

  • JSON Processing: Read, validate, and pretty-print JSON files with error reporting
  • CSV Handling: Advanced CSV parsing with proper quote handling and delimiter support
  • Data Analysis: File statistics, directory size calculation, and content analysis

Enterprise Features

  • Logging: Comprehensive SLF4J logging with configurable levels
  • Error Handling: Robust error handling with descriptive messages
  • Security: Built-in validation and safe file operations
  • Performance: Optimized for large files and directories
  • Extensibility: Modular architecture for easy feature additions

๐Ÿ“‹ Prerequisites

  • Java: JDK 11 or higher
  • Maven: 3.6 or higher
  • Memory: Minimum 512MB RAM (recommended: 1GB+)
  • Storage: Varies based on file operations

๐Ÿ› ๏ธ Installation & Setup

1. Clone/Download the Project

git clone <repository-url>
cd mcp-file-operations

2. Build the Project

mvn clean compile

3. Run Tests (Optional)

mvn test

4. Create Executable JAR

mvn package

This creates: target/mcp-file-operations-2.0.0.jar

5. Quick Test

java -jar target/mcp-file-operations-2.0.0.jar

๐ŸŽฏ Use Cases & Examples

Development & Code Management

1. Project File Analysis

# Count lines of code in a project
tools/call: count_lines
Arguments: {"filePath": "src/main/java/Main.java"}

# Search for TODO comments
tools/call: find_in_file
Arguments: {"filePath": "Main.java", "searchText": "TODO", "caseSensitive": false}

# Get project directory size
tools/call: get_directory_size
Arguments: {"directoryPath": "src/", "includeHidden": true}

2. Code Refactoring

# Replace deprecated method calls
tools/call: replace_in_file
Arguments: {
  "filePath": "Service.java", 
  "searchText": "oldMethod()", 
  "replaceText": "newMethod()",
  "replaceAll": true
}

# Compare files after refactoring
tools/call: compare_files
Arguments: {
  "file1Path": "Service_old.java", 
  "file2Path": "Service.java",
  "ignoreWhitespace": true
}

Data Management & Analysis

3. CSV Data Processing

# Read financial statements
tools/call: read_csv
Arguments: {
  "filePath": "Statements.csv", 
  "delimiter": ",", 
  "maxRows": 50
}

# Analyze large datasets
tools/call: get_file_info
Arguments: {"filePath": "large_dataset.csv"}

4. JSON Configuration Management

# Validate configuration files
tools/call: validate_json
Arguments: {"filePath": "config/app-config.json"}

# Pretty-print JSON for review
tools/call: read_json
Arguments: {"filePath": "api-response.json"}

System Administration

5. Log File Management

# Search error logs
tools/call: search_files
Arguments: {
  "directoryPath": "/var/log/", 
  "pattern": "error.*\\.log", 
  "recursive": true
}

# Archive old logs
tools/call: create_archive
Arguments: {
  "sourcePath": "/var/log/old/", 
  "archivePath": "/backup/logs-2024.zip",
  "compressionLevel": 9
}

6. System Monitoring

# Monitor directory sizes
tools/call: get_directory_size
Arguments: {"directoryPath": "/home/user/", "includeHidden": false}

# Check file integrity
tools/call: calculate_checksum
Arguments: {"filePath": "important-file.txt", "algorithm": "SHA256"}

Content Management

7. Batch File Operations

# Rename image files with date pattern
tools/call: batch_rename
Arguments: {
  "directoryPath": "photos/", 
  "pattern": "IMG_(\\d+)", 
  "replacement": "Photo_$1",
  "preview": true
}

# Organize files by extension
tools/call: search_files
Arguments: {
  "directoryPath": "downloads/", 
  "pattern": ".*\\.pdf$", 
  "recursive": false
}

8. Document Processing

# Read configuration with line numbers
tools/call: read_file_with_line_numbers
Arguments: {
  "filePath": "nginx.conf", 
  "startLine": 1, 
  "endLine": 50
}

# Create project backup
tools/call: copy_file
Arguments: {
  "sourcePath": "project/", 
  "destinationPath": "backup/project-backup/"
}

๐Ÿ”ง Integration Guide

MCP Client Integration

Claude Desktop Configuration

Add to your claude_desktop_config.json:

{
  "mcpServers": {
    "file-operations": {
      "command": "java",
      "args": ["-jar", "/path/to/mcp-file-operations-2.0.0.jar"],
      "env": {
        "LOG_LEVEL": "INFO"
      }
    }
  }
}

VS Code Extension

{
  "mcp.servers": {
    "file-ops": {
      "command": ["java", "-jar", "mcp-file-operations-2.0.0.jar"],
      "transport": "stdio"
    }
  }
}

Custom Application

import subprocess
import json

# Start MCP server
process = subprocess.Popen([
    'java', '-jar', 'mcp-file-operations-2.0.0.jar'
], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)

# Send initialization request
init_request = {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
        "protocolVersion": "2024-11-05",
        "capabilities": {},
        "clientInfo": {"name": "my-app", "version": "1.0.0"}
    }
}

process.stdin.write(json.dumps(init_request) + '\n')

๐Ÿ“Š Available Tools

CategoryToolDescriptionKey Parameters
Basicread_fileRead file contentsfilePath
create_fileCreate new file with contentfilePath, content
write_fileWrite/append to filefilePath, content, append
delete_fileDelete a filefilePath
Directorycreate_directoryCreate directorydirectoryPath
delete_directoryDelete directory and contentsdirectoryPath
list_filesList directory contentsdirectoryPath, recursive, includeHidden
Movementcopy_fileCopy files/directoriessourcePath, destinationPath
move_fileMove files/directoriessourcePath, destinationPath
rename_fileRename filesoldPath, newPath
Informationfind_fileCheck file existencefilePath
get_file_infoGet detailed file infofilePath
search_filesSearch with patternsdirectoryPath, pattern, recursive
Advancedcalculate_checksumCalculate file hashesfilePath, algorithm
get_directory_sizeCalculate directory sizedirectoryPath, includeHidden
create_archiveCreate ZIP archivessourcePath, archivePath
count_linesCount lines/words/charsfilePath
Textfind_in_fileSearch text in filefilePath, searchText, caseSensitive
replace_in_fileReplace text in filefilePath, searchText, replaceText
compare_filesCompare two filesfile1Path, file2Path
Batchbatch_renameBatch rename filesdirectoryPath, pattern, replacement
Dataread_jsonRead and format JSONfilePath
validate_jsonValidate JSON syntaxfilePath
read_csvRead CSV with proper parsingfilePath, delimiter, maxRows

โš™๏ธ Configuration

Environment Variables

# Logging level
export LOG_LEVEL=DEBUG

# Maximum file size for operations (bytes)
export MAX_FILE_SIZE=104857600

# Working directory
export WORK_DIR=/home/user/workspace

JVM Options

# For large file operations
java -Xmx2G -XX:+UseG1GC -jar mcp-file-operations-2.0.0.jar

# For production deployment
java -server -Xms512m -Xmx1G -jar mcp-file-operations-2.0.0.jar

Logging Configuration

Create logback.xml in the classpath:

<configuration>
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
    
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>mcp-server.log</file>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
    
    <root level="INFO">
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="FILE" />
    </root>
</configuration>

๐Ÿงช Testing

Manual Testing with MCP Inspector

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

# Run inspector
mcp-inspector java -jar target/mcp-file-operations-2.0.0.jar

# Open browser to localhost:5173

Command Line Testing

# Test basic functionality
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0.0"}}}' | java -jar target/mcp-file-operations-2.0.0.jar

# Test file creation
echo '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"create_file","arguments":{"filePath":"test.txt","content":"Hello World"}}}' | java -jar target/mcp-file-operations-2.0.0.jar

Automated Testing Script

#!/bin/bash
# test-mcp-server.sh

SERVER_JAR="target/mcp-file-operations-2.0.0.jar"
TEST_DIR="test-workspace"

# Setup test environment
mkdir -p $TEST_DIR
cd $TEST_DIR

# Test file operations
echo "Testing file operations..."
echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"create_file","arguments":{"filePath":"sample.txt","content":"Sample content"}}}' | java -jar ../$SERVER_JAR

# Test CSV reading
echo "Testing CSV operations..."
echo '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"read_csv","arguments":{"filePath":"../Statements.csv","maxRows":5}}}' | java -jar ../$SERVER_JAR

echo "Tests completed!"

๐Ÿ”’ Security Considerations

File System Access

  • Sandboxing: Consider running in a containerized environment
  • Path Validation: Server validates file paths to prevent directory traversal
  • Permission Checks: Respects file system permissions
  • Size Limits: Implement size limits for large file operations

Production Deployment

# Run with restricted user
sudo -u mcp-user java -jar mcp-file-operations-2.0.0.jar

# Use Docker for isolation
docker run -v /safe/directory:/workspace -u 1000:1000 mcp-server

Access Control

# Limit file access to specific directories
export MCP_ALLOWED_PATHS="/home/user/documents,/tmp"
export MCP_FORBIDDEN_PATTERNS=".*\.key,.*\.pem,/etc/.*"

๐Ÿ› Troubleshooting

Common Issues

1. Permission Denied

# Check file permissions
ls -la /path/to/file

# Fix permissions
chmod 644 file.txt
chmod 755 directory/

2. Out of Memory

# Increase heap size
java -Xmx4G -jar mcp-file-operations-2.0.0.jar

# Monitor memory usage
jstat -gc <process-id>

3. CSV Parsing Issues

# Test with specific delimiter
{"filePath": "data.csv", "delimiter": ";"}

# Check file encoding
file -bi data.csv

4. JSON Validation Errors

# Pretty-print for debugging
cat file.json | python -m json.tool

# Check for BOM
hexdump -C file.json | head

Debug Mode

# Enable debug logging
export LOG_LEVEL=DEBUG
java -jar mcp-file-operations-2.0.0.jar 2>debug.log

# Trace MCP communication
export MCP_TRACE=true

๐Ÿš€ Performance Optimization

Large File Handling

# For files > 100MB
java -Xmx4G -XX:+UseG1GC -XX:G1HeapRegionSize=16m -jar mcp-file-operations-2.0.0.jar

# Stream processing for very large files
export STREAM_THRESHOLD=52428800  # 50MB

Batch Operations

# Optimize for batch processing
export BATCH_SIZE=1000
export PARALLEL_PROCESSING=true

๐Ÿ“ˆ Monitoring & Metrics

Health Check

# Check server status
echo '{"jsonrpc":"2.0","id":1,"method":"ping","params":{}}' | java -jar mcp-file-operations-2.0.0.jar

Performance Metrics

  • File operation latency
  • Memory usage patterns
  • Error rates by operation type
  • Throughput for batch operations

๐Ÿ†˜ Support

For issues and questions:

  1. Check the troubleshooting section
  2. Review logs in debug mode
  3. Test with MCP Inspector
  4. Create detailed issue reports

Version: 2.0.0
Last Updated: September 2025
Compatibility: MCP Protocol 2024-11-05 and later

AI agents & MCP

More like this