Skip to main content
Glama
local-excel-mcp-implementation.md12.9 kB
# Excel MCP 本地实现设计文档 ## 1. 概述 本项目旨在实现一个基于Model Context Protocol (MCP)的Excel处理服务器,使其能够在本地运行并被Claude Code等AI工具调用。该服务器将提供Excel文件的读取、写入、数据操作等功能,通过标准化的MCP协议与AI模型进行交互。 ### 1.1 核心功能 - Excel文件读取和解析 - 数据查询和筛选 - 单元格数据修改 - 工作表操作(创建、删除、重命名) - 公式计算和应用 - 图表生成和操作 - 数据格式化和样式设置 ### 1.2 技术目标 - 支持.xlsx、.xls格式文件 - 本地运行,无需外部依赖 - 通过JSON-RPC协议与Claude Code通信 - 提供丰富的错误处理和日志记录 - 支持大文件处理和内存优化 ## 2. 技术栈与依赖 ### 2.1 核心技术栈 - **语言**: Python 3.10+ - **MCP SDK**: Python MCP SDK (v1.2.0+) - **Excel处理**: openpyxl, xlrd, xlwt - **数据处理**: pandas, numpy - **异步处理**: asyncio, aiofiles - **HTTP客户端**: httpx (如需要) ### 2.2 项目依赖 ``` mcp[cli]>=1.2.0 openpyxl>=3.1.0 pandas>=2.0.0 numpy>=1.24.0 xlrd>=2.0.0 xlwt>=1.3.0 aiofiles>=23.0.0 ``` ## 3. 架构设计 ### 3.1 整体架构 ```mermaid graph TB subgraph "Claude Code / AI Client" A[AI Assistant] B[MCP Client] end subgraph "Excel MCP Server" C[FastMCP Server] D[Excel Tool Handler] E[File Manager] F[Data Processor] G[Format Handler] end subgraph "Local File System" H[Excel Files] I[Temp Files] J[Log Files] end A --> B B <--> C C --> D D --> E D --> F D --> G E <--> H F <--> I G --> J ``` ### 3.2 模块架构 ```mermaid classDiagram class ExcelMCPServer { +FastMCP server +initialize() +run() } class FileManager { +load_workbook(path) +save_workbook(workbook, path) +create_backup(path) +validate_file(path) } class DataProcessor { +read_range(sheet, range) +write_range(sheet, range, data) +query_data(sheet, conditions) +calculate_formula(formula) } class SheetOperations { +create_sheet(name) +delete_sheet(name) +rename_sheet(old_name, new_name) +list_sheets() } class FormatHandler { +apply_style(range, style) +set_number_format(range, format) +merge_cells(range) +add_chart(data, chart_type) } ExcelMCPServer --> FileManager ExcelMCPServer --> DataProcessor ExcelMCPServer --> SheetOperations ExcelMCPServer --> FormatHandler ``` ## 4. MCP工具定义 ### 4.1 文件操作工具 #### read_excel_file - **功能**: 读取Excel文件内容 - **参数**: - file_path: 文件路径 - sheet_name: 工作表名称(可选) - range: 读取范围(可选,如"A1:C10") - **返回**: JSON格式的表格数据 #### write_excel_file - **功能**: 写入数据到Excel文件 - **参数**: - file_path: 文件路径 - data: 要写入的数据 - sheet_name: 工作表名称 - start_cell: 起始单元格(如"A1") - **返回**: 操作结果状态 #### create_excel_file - **功能**: 创建新的Excel文件 - **参数**: - file_path: 文件路径 - sheets: 工作表列表 - **返回**: 文件创建结果 ### 4.2 数据查询工具 #### query_excel_data - **功能**: 查询Excel数据 - **参数**: - file_path: 文件路径 - sheet_name: 工作表名称 - conditions: 查询条件 - columns: 返回列(可选) - **返回**: 符合条件的数据 #### get_excel_info - **功能**: 获取Excel文件信息 - **参数**: - file_path: 文件路径 - **返回**: 文件基本信息(工作表列表、行数、列数等) ### 4.3 工作表操作工具 #### create_worksheet - **功能**: 创建新工作表 - **参数**: - file_path: 文件路径 - sheet_name: 工作表名称 - position: 插入位置(可选) #### delete_worksheet - **功能**: 删除工作表 - **参数**: - file_path: 文件路径 - sheet_name: 工作表名称 #### rename_worksheet - **功能**: 重命名工作表 - **参数**: - file_path: 文件路径 - old_name: 原名称 - new_name: 新名称 ### 4.4 数据处理工具 #### apply_formula - **功能**: 应用Excel公式 - **参数**: - file_path: 文件路径 - sheet_name: 工作表名称 - cell: 目标单元格 - formula: 公式字符串 #### format_cells - **功能**: 设置单元格格式 - **参数**: - file_path: 文件路径 - sheet_name: 工作表名称 - range: 单元格范围 - format_type: 格式类型(数字、日期、货币等) #### create_chart - **功能**: 创建图表 - **参数**: - file_path: 文件路径 - sheet_name: 工作表名称 - data_range: 数据范围 - chart_type: 图表类型 - position: 图表位置 ## 5. 核心实现逻辑 ### 5.1 服务器初始化流程 ```mermaid sequenceDiagram participant Main as main() participant Server as ExcelMCPServer participant Tools as Tool Handlers participant MCP as FastMCP Main->>Server: initialize() Server->>Tools: register_tools() Tools->>MCP: @mcp.tool() decorators Server->>MCP: setup_logging() Server->>MCP: run(transport='stdio') MCP-->>Main: Server running ``` ### 5.2 文件读取流程 ```mermaid sequenceDiagram participant Client as MCP Client participant Server as Excel MCP Server participant FileManager as File Manager participant Processor as Data Processor Client->>Server: read_excel_file(path, sheet, range) Server->>FileManager: validate_file(path) FileManager-->>Server: validation_result Server->>FileManager: load_workbook(path) FileManager-->>Server: workbook Server->>Processor: read_range(sheet, range) Processor-->>Server: data Server-->>Client: formatted_data ``` ### 5.3 数据写入流程 ```mermaid sequenceDiagram participant Client as MCP Client participant Server as Excel MCP Server participant FileManager as File Manager participant Processor as Data Processor Client->>Server: write_excel_file(path, data, sheet, start_cell) Server->>FileManager: create_backup(path) Server->>FileManager: load_workbook(path) FileManager-->>Server: workbook Server->>Processor: write_range(sheet, start_cell, data) Processor-->>Server: result Server->>FileManager: save_workbook(workbook, path) FileManager-->>Server: save_result Server-->>Client: operation_result ``` ## 6. 错误处理与日志 ### 6.1 错误处理策略 #### 文件操作错误 - 文件不存在: 返回明确的错误信息 - 文件权限问题: 提供权限设置建议 - 文件格式错误: 支持的格式列表提示 - 文件损坏: 尝试修复或提供替代方案 #### 数据操作错误 - 范围超出边界: 自动调整或提示正确范围 - 数据类型不匹配: 提供类型转换建议 - 公式错误: 详细的公式验证反馈 - 内存不足: 分片处理大文件 ### 6.2 日志系统 ```python import logging import sys from pathlib import Path # 配置日志系统 def setup_logging(): log_dir = Path("logs") log_dir.mkdir(exist_ok=True) logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler(log_dir / "excel_mcp.log"), logging.StreamHandler(sys.stderr) # 避免污染stdout ] ) ``` ## 7. 配置管理 ### 7.1 配置文件结构 ```json { "server": { "name": "excel-mcp", "version": "1.0.0", "transport": "stdio" }, "excel": { "max_file_size": "100MB", "supported_formats": [".xlsx", ".xls"], "backup_enabled": true, "temp_dir": "./temp" }, "security": { "allowed_paths": ["./data", "~/Documents"], "forbidden_extensions": [".exe", ".bat"], "max_memory_usage": "512MB" }, "logging": { "level": "INFO", "file": "./logs/excel_mcp.log", "max_size": "10MB", "backup_count": 5 } } ``` ### 7.2 Claude Desktop配置 ```json { "mcpServers": { "excel-mcp": { "command": "python", "args": ["/absolute/path/to/excel-mcp/server.py"], "env": { "EXCEL_MCP_CONFIG": "/absolute/path/to/config.json" } } } } ``` ## 8. 安全考虑 ### 8.1 文件系统安全 - 路径验证: 防止目录遍历攻击 - 文件类型检查: 仅允许指定的Excel格式 - 文件大小限制: 防止内存耗尽 - 访问权限控制: 限制可访问的目录 ### 8.2 数据安全 - 敏感数据检测: 自动识别可能的敏感信息 - 临时文件清理: 及时清理处理过程中的临时文件 - 错误信息过滤: 避免在错误信息中暴露系统信息 ## 9. 性能优化 ### 9.1 内存管理 - 流式读取: 对大文件采用分块读取 - 惰性加载: 仅在需要时加载工作表数据 - 缓存机制: 缓存常用文件的基本信息 - 垃圾回收: 及时释放不再需要的对象 ### 9.2 处理优化 - 异步操作: 使用async/await处理I/O操作 - 批量处理: 合并多个小操作为单次文件操作 - 索引优化: 为频繁查询的数据建立索引 - 并发控制: 合理控制并发文件操作数量 ## 10. 测试策略 ### 10.1 单元测试 - 文件操作功能测试 - 数据处理逻辑测试 - 错误处理机制测试 - 性能基准测试 ### 10.2 集成测试 - MCP协议交互测试 - Claude Desktop集成测试 - 多文件并发操作测试 - 大文件处理测试 ### 10.3 测试用例 ```python # 示例测试用例结构 class TestExcelMCP: def test_read_excel_file(self): # 测试正常文件读取 pass def test_read_nonexistent_file(self): # 测试不存在文件的错误处理 pass def test_write_excel_data(self): # 测试数据写入功能 pass def test_large_file_handling(self): # 测试大文件处理能力 pass def test_concurrent_operations(self): # 测试并发操作安全性 pass ``` }, "security": { "allowed_paths": ["./data", "~/Documents"], "forbidden_extensions": [".exe", ".bat"], "max_memory_usage": "512MB" }, "logging": { "level": "INFO", "file": "./logs/excel_mcp.log", "max_size": "10MB", "backup_count": 5 } } ``` ### 7.2 Claude Desktop配置 ```json { "mcpServers": { "excel-mcp": { "command": "python", "args": ["/absolute/path/to/excel-mcp/server.py"], "env": { "EXCEL_MCP_CONFIG": "/absolute/path/to/config.json" } } } } ``` ## 8. 安全考虑 ### 8.1 文件系统安全 - 路径验证: 防止目录遍历攻击 - 文件类型检查: 仅允许指定的Excel格式 - 文件大小限制: 防止内存耗尽 - 访问权限控制: 限制可访问的目录 ### 8.2 数据安全 - 敏感数据检测: 自动识别可能的敏感信息 - 临时文件清理: 及时清理处理过程中的临时文件 - 错误信息过滤: 避免在错误信息中暴露系统信息 ## 9. 性能优化 ### 9.1 内存管理 - 流式读取: 对大文件采用分块读取 - 惰性加载: 仅在需要时加载工作表数据 - 缓存机制: 缓存常用文件的基本信息 - 垃圾回收: 及时释放不再需要的对象 ### 9.2 处理优化 - 异步操作: 使用async/await处理I/O操作 - 批量处理: 合并多个小操作为单次文件操作 - 索引优化: 为频繁查询的数据建立索引 - 并发控制: 合理控制并发文件操作数量 ## 10. 测试策略 ### 10.1 单元测试 - 文件操作功能测试 - 数据处理逻辑测试 - 错误处理机制测试 - 性能基准测试 ### 10.2 集成测试 - MCP协议交互测试 - Claude Desktop集成测试 - 多文件并发操作测试 - 大文件处理测试 ### 10.3 测试用例 ```python # 示例测试用例结构 class TestExcelMCP: def test_read_excel_file(self): # 测试正常文件读取 pass def test_read_nonexistent_file(self): # 测试不存在文件的错误处理 pass def test_write_excel_data(self): # 测试数据写入功能 pass def test_large_file_handling(self): # 测试大文件处理能力 pass def test_concurrent_operations(self): # 测试并发操作安全性 pass ```

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/xuhongxin/excel-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server