文件操作服务器

一个基于Java的全面文件操作服务器,提供文件系统操作、文本处理、数据分析和结构化数据处理功能,适用于企业级应用。

  • by anand34577
  • 本地部署
  • 更新于
在 GitHub 查看 anand34577/file-operation-mcp-server

使用说明

高级文件操作MCP服务器

一个全面的基于Java的模型上下文协议(MCP)服务器,提供广泛的文件系统操作、文本处理、数据分析和结构化数据处理功能。遵循行业最佳实践,采用企业级架构构建。

🚀 特性

核心文件操作

  • 文件管理:创建、读取、写入、删除、复制、移动和重命名文件
  • 目录操作:使用高级筛选创建、删除、重命名和列出目录
  • 文件信息:获取详细的元数据、权限、时间戳和文件统计信息
  • 搜索与发现:基于模式的文件搜索,支持正则表达式

高级操作

  • 文本处理:查找/替换文本、文件比较、用统计数据计数行
  • 检查和计算:支持MD5、SHA1、SHA256算法
  • 档案创建:创建具有压缩级别控制的ZIP存档
  • 批量操作:使用模式匹配和预览模式进行批量文件重命名

结构化数据支持

  • JSON处理:读取、验证和漂亮打印带有错误报告的JSON文件
  • CSV处理:高级CSV解析,具有适当的引号处理和分隔符支持
  • 数据分析:文件统计、目录大小计算和内容分析

企业功能

  • 日志记录:具有可配置级别的全面SLF4J日志记录
  • 错误处理:使用描述性消息进行稳健的错误处理
  • 安全:内置验证和安全文件操作
  • 演出:针对大型文件和目录进行了优化
  • 可扩展性:模块化架构,便于添加功能

📋 先决条件

  • JavaJDK 11或更高版本
  • 梅文:3.6或更高
  • 记忆:最低512MB RAM(建议:1GB以上)
  • 存储:根据文件操作而有所不同

🛠️ 安装和设置

1.克隆/下载项目

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

2.建设项目

mvn clean compile

3.运行测试(可选)

mvn test

4.创建可执行JAR

mvn package

这将创建: target/mcp-file-operations-2.0.0.jar

5.快速测试

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

🎯 用例和示例

开发与代码管理

1.项目文件分析

# 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.代码重构

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

数据管理与分析

3.CSV数据处理

# 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配置管理

# 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"}

系统管理

5.日志文件管理

# 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.系统监控

# 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"}

内容管理

7.批处理文件操作

# 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.文件处理

# 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/"
}

🔧 集成指南

MCP客户端集成

Claude桌面配置

添加到您的 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代码扩展

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

自定义应用程序

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

📊 可用工具

类别 工具 描述 关键参数
基础 read_file 读取文件内容 filePath
create_file 创建包含内容的新文件 filePath, content
write_file 写入/追加到文件 filePath, content, append
delete_file 删除文件 filePath
目录 create_directory 创建目录 directoryPath
delete_directory 删除目录和内容 directoryPath
list_files 列出目录内容 directoryPath, recursive, includeHidden
运动 copy_file 复制文件/目录 sourcePath, destinationPath
move_file 移动文件/目录 sourcePath, destinationPath
rename_file 重命名文件 oldPath, newPath
信息 find_file 检查文件是否存在 filePath
get_file_info 获取详细的文件信息 filePath
search_files 使用图案搜索 directoryPath, pattern, recursive
高级 calculate_checksum 计算文件哈希值 filePath, algorithm
get_directory_size 计算目录大小 directoryPath, includeHidden
create_archive 创建ZIP存档 sourcePath, archivePath
count_lines 计数行数/单词数/字符数 filePath
文本 find_in_file 在文件中搜索文本 filePath, searchText, caseSensitive
replace_in_file 替换文件中的文本 filePath, searchText, replaceText
compare_files 比较两个文件 file1Path, file2Path
批次 batch_rename 批量重命名文件 directoryPath, pattern, replacement
数据 read_json 读取并格式化JSON filePath
validate_json 验证JSON语法 filePath
read_csv 使用正确的解析读取CSV filePath, delimiter, maxRows

⚙️ 配置

环境变量

# 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选项

# 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

日志记录配置

创建 logback.xml 在类路径中:

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

🧪 测试

使用MCP检查员进行手动测试

# 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

命令行测试

# 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

自动测试脚本

#!/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!"

🔒 安全考虑

文件系统访问

  • 沙箱:考虑在容器化环境中运行
  • 路径验证:服务器验证文件路径以防止目录遍历
  • 权限检查:尊重文件系统权限
  • 大小限制:对大型文件操作实施大小限制

生产部署

# 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

访问控制

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

🐛 故障排除

常见问题

1.拒绝许可

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

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

2.失忆

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

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

3.CSV解析问题

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

# Check file encoding
file -bi data.csv

4.JSON验证错误

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

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

调试模式

# 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

🚀 性能优化

大文件处理

# 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

批量操作

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

📈 监控和指标

健康检查

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

性能指标

  • 文件操作延迟
  • 内存使用模式
  • 按操作类型划分的错误率
  • 批处理操作的吞吐量

🤝 贡献

开发设置

git clone <repository>
cd mcp-file-operations
mvn clean install

添加新功能

  1. 创建新的服务类实现 FileOperationService
  2. 将工具定义添加到 ToolRegistry
  3. 在中注册服务 ServiceFactory
  4. 添加测试和文档

代码规范

  • 遵循Java 11+规范
  • 使用SLF4J进行日志记录
  • 实施适当的错误处理
  • 添加全面的JavaDoc

📜 许可证

本项目按原样提供,用于教育和发展目的。在生产环境中使用之前,请查看并遵守贵组织的安全策略。

🆘 支持

对于问题和疑问:

  1. 检查故障排除部分
  2. 在调试模式下查看日志
  3. 使用MCP检查员进行测试
  4. 创建详细的问题报告

版本: 2.0.0
最后更新:2025年9月
兼容性:MCP协议2024-11-05及更高版本