DOCX-MCP
Enables comprehensive Microsoft Word document manipulation through the Model Context Protocol, with advanced table operations including creation, data management, formatting, and bulk operations. Supports document creation, editing, and saving with plans for full document content management.
README
DOCX-MCP: Word Document MCP Server
A comprehensive Model Context Protocol (MCP) server for Microsoft Word document operations, built with FastMCP and python-docx. Currently focused on advanced table operations with plans to expand into full document manipulation capabilities.
🚀 Features
Phase 1 - Core Table Operations ✅
Document Management
- Open/create Word documents
- Save documents with optional rename
- Get document information and metadata
Table Structure Operations
- Create tables with customizable dimensions
- Delete tables by index
- Add/remove rows and columns at any position
- Support for header rows
Table Data Operations
- Set/get individual cell values
- Bulk table data retrieval (array, object, CSV formats)
- List all tables in document with metadata
Phase 2.1 - Cell Formatting ✅ (New!)
Text Formatting
- Font family, size, and color customization
- Bold, italic, underline, strikethrough styling
- Subscript and superscript support
Cell Alignment
- Horizontal alignment (left, center, right, justify)
- Vertical alignment (top, middle, bottom)
Visual Styling
- Cell background colors (hex color support)
- Cell borders with customizable styles, widths, and colors
- Complete formatting (apply all options at once)
Phase 2 - Advanced Table Features 🔄 (In Progress)
Table Formatting & Styling
- Cell formatting (bold, italic, font, color, alignment)
- Table borders and shading
- Row height and column width adjustment
- Table positioning and text wrapping
Data Import/Export
- CSV import to tables
- Excel data import
- JSON data mapping to tables
- Bulk data operations
Table Search & Query
- Search cell content across tables
- Filter table data by criteria
- Sort table rows by column values
- Table data validation
Phase 3 - Extended Table Features 🔮 (Planned)
Table Templates & Automation
- Predefined table templates
- Table style libraries
- Automated table generation from data
- Table cloning and duplication
Advanced Operations
- Table merging and splitting
- Cross-table references
- Calculated fields and formulas
- Table relationship management
Phase 4 - Document Operations 🔮 (Future)
Content Management
- Text insertion and formatting
- Paragraph operations
- Heading and outline management
- Document structure manipulation
Media & Objects
- Image insertion and positioning
- Shape and drawing objects
- Charts and graphs integration
- Hyperlinks and bookmarks
Document Formatting
- Page layout and margins
- Headers and footers
- Styles and themes
- Document properties and metadata
📦 Installation
Prerequisites
- Python 3.8+
- pip package manager
Install from Source
- Clone the repository:
git clone <repository-url>
cd docx_table
- Install dependencies:
pip install -r requirements.txt
- Install the package in development mode:
pip install -e .
🖥️ Usage
As MCP Server
Run the MCP server with default STDIO transport:
python -m docx_mcp.server
Transport Protocols
The server supports multiple transport protocols:
STDIO (default) - Standard input/output for direct integration:
python -m docx_mcp.server --transport stdio
SSE (Server-Sent Events) - HTTP-based streaming:
python -m docx_mcp.server --transport sse --host localhost --port 8000
Streamable HTTP - HTTP with streaming support:
python -m docx_mcp.server --transport streamable-http --host localhost --port 8000
Command Line Options
python -m docx_mcp.server --help
Available options:
--transport {stdio,sse,streamable-http}- Transport protocol (default: stdio)--host HOST- Host to bind to for HTTP/SSE transports (default: localhost)--port PORT- Port to bind to for HTTP/SSE transports (default: 8000)--no-banner- Disable startup banner
Direct Usage
from docx_mcp.core.document_manager import DocumentManager
from docx_mcp.operations.tables.table_operations import TableOperations
# Initialize
doc_manager = DocumentManager()
table_ops = TableOperations(doc_manager)
# Open document
result = doc_manager.open_document("document.docx", create_if_not_exists=True)
# Create table with headers
result = table_ops.create_table(
"document.docx",
rows=3,
cols=4,
headers=["Name", "Age", "City", "Occupation"]
)
# Set cell value
result = table_ops.set_cell_value("document.docx", 0, 1, 0, "Alice")
# Get table data
result = table_ops.get_table_data("document.docx", 0, include_headers=True)
# Save document
result = doc_manager.save_document("document.docx")
🔧 Available MCP Tools
All tools accept JSON parameters and return JSON responses, making them compatible with language models.
Document Operations
open_document(file_path, create_if_not_exists=True)- Open or create a Word documentsave_document(file_path, save_as=None)- Save a Word documentget_document_info(file_path)- Get document information
Table Structure Operations
create_table(file_path, rows, cols, position="end", paragraph_index=None, headers=None)- Create a new tabledelete_table(file_path, table_index)- Delete a tableadd_table_rows(file_path, table_index, count=1, position="end", row_index=None)- Add rows to a tableadd_table_columns(file_path, table_index, count=1, position="end", column_index=None)- Add columns to a tabledelete_table_rows(file_path, table_index, row_indices)- Delete rows from a table
Data Operations
set_cell_value(file_path, table_index, row_index, column_index, value)- Set individual cell valueget_cell_value(file_path, table_index, row_index, column_index)- Get individual cell valueget_table_data(file_path, table_index, include_headers=True, format="array")- Get entire table data
Query Operations
list_tables(file_path, include_summary=True)- List all tables in document
Table Search Operations (New in Phase 2.7!)
search_table_content(file_path, query, search_mode="contains", case_sensitive=False, table_indices=None, max_results=None)- Search for content within table cellssearch_table_headers(file_path, query, search_mode="contains", case_sensitive=False)- Search specifically in table headers
Cell Formatting Operations (New in Phase 2.1!)
format_cell_text(file_path, table_index, row_index, column_index, ...)- Format text in cellformat_cell_alignment(file_path, table_index, row_index, column_index, horizontal, vertical)- Set cell alignmentformat_cell_background(file_path, table_index, row_index, column_index, color)- Set cell background colorformat_cell_borders(file_path, table_index, row_index, column_index, ...)- Set cell borders
Example Language Model Usage
Language models can call these tools with JSON parameters:
{
"tool": "create_table",
"parameters": {
"file_path": "report.docx",
"rows": 5,
"cols": 3,
"headers": ["Product", "Sales", "Growth"]
}
}
{
"tool": "set_cell_value",
"parameters": {
"file_path": "report.docx",
"table_index": 0,
"row_index": 1,
"column_index": 0,
"value": "Widget A"
}
}
New! Cell Formatting Examples:
{
"tool": "format_cell_text",
"parameters": {
"file_path": "report.docx",
"table_index": 0,
"row_index": 0,
"column_index": 0,
"font_family": "Arial",
"font_size": 14,
"font_color": "FF0000",
"bold": true,
"italic": true
}
}
{
"tool": "format_cell_background",
"parameters": {
"file_path": "report.docx",
"table_index": 0,
"row_index": 0,
"column_index": 0,
"color": "FFFF00"
}
}
New! Table Search Examples:
{
"tool": "search_table_content",
"parameters": {
"file_path": "report.docx",
"query": "Alice",
"search_mode": "contains",
"case_sensitive": false,
"max_results": 10
}
}
{
"tool": "search_table_headers",
"parameters": {
"file_path": "report.docx",
"query": "Email",
"search_mode": "exact"
}
}
🧪 Testing
The project uses pytest for comprehensive testing with 71 test cases covering all functionality.
Run all tests:
pytest
Run tests with coverage:
pytest --cov=src/docx_mcp
Run specific test categories:
pytest -m unit # Unit tests only
pytest -m integration # Integration tests only
pytest tests/test_table_operations.py # Specific test file
Run tests with verbose output:
pytest -v
📋 Development Roadmap
Phase 2: Advanced Table Features (In Progress)
Priority: High - Completing table functionality before expanding scope
-
[x] Cell Formatting & Styling ✅ COMPLETED
- [x] Cell text formatting (bold, italic, underline, font family/size, color)
- [x] Cell background colors with hex color support
- [x] Cell borders with customizable styles, widths, and colors
- [x] Text alignment (horizontal: left, center, right, justify)
- [x] Vertical alignment (top, middle, bottom)
- [x] Complete formatting (apply all options at once)
- [ ] Row height and column width controls
-
[ ] Data Import/Export
- [ ] CSV file import to tables
- [ ] Excel file data import (.xlsx)
- [ ] JSON data structure mapping
- [ ] Enhanced export with formatting preservation
- [ ] Bulk cell data operations
-
[x] Table Search & Query ✅ COMPLETED
- [x] Search content across all table cells
- [x] Search specifically in table headers
- [x] Multiple search modes (exact, contains, regex)
- [x] Case-sensitive and case-insensitive search
- [x] Search specific tables or all tables
- [x] Limit search results
- [ ] Filter table rows by column criteria
- [ ] Sort table data by column values
- [ ] Find and replace in table content
Phase 3: Extended Table Features
Priority: Medium - Advanced table manipulation
-
[ ] Table Templates & Automation
- Predefined table styles and layouts
- Table template library system
- Auto-generate tables from data schemas
- Table duplication and cloning
-
[ ] Advanced Table Operations
- Merge and split table cells
- Table-to-table data relationships
- Calculated fields and basic formulas
- Cross-reference table data
-
[ ] Performance & Optimization
- Batch operations for large tables
- Memory optimization for big documents
- Caching for frequently accessed data
- Async operations support
Phase 4: Document Content Operations
Priority: Medium - Expanding beyond tables
-
[ ] Text & Paragraph Management
- Insert and format text content
- Paragraph styling and spacing
- Bullet points and numbering
- Text search and replace
-
[ ] Document Structure
- Heading hierarchy management
- Table of contents generation
- Section breaks and page layout
- Document outline operations
Phase 5: Media & Advanced Features
Priority: Low - Rich document features
-
[ ] Media Integration
- Image insertion and positioning
- Charts and graphs from table data
- Shape and drawing objects
- Embedded object support
-
[ ] Advanced Document Features
- Headers and footers
- Page numbering and layout
- Document properties and metadata
- Track changes and comments
Phase 6: Enterprise Features
Priority: Low - Production-ready enhancements
-
[ ] Security & Compliance
- Document encryption support
- Access control and permissions
- Audit logging and tracking
- Data validation and sanitization
-
[ ] Integration & Extensibility
- Plugin system architecture
- External data source connections
- API rate limiting and throttling
- Multi-document operations
🔧 Architecture
Project Structure
src/docx_mcp/
├── __init__.py # Package initialization
├── server.py # FastMCP server and tool definitions
├── core/
│ └── document_manager.py # Core document operations
├── operations/
│ └── tables/
│ └── table_operations.py # Table-specific operations
├── models/
│ ├── responses.py # Response data models
│ └── tables.py # Table-related data models
└── utils/
├── exceptions.py # Custom exception definitions
└── validation.py # Input validation utilities
Key Design Principles
- Modular Architecture: Clear separation between document, table, and future operations
- Type Safety: Full type hints and Pydantic models for data validation
- Error Handling: Comprehensive exception handling with detailed error messages
- Extensibility: Easy to add new operation types and document features
- Testing: High test coverage with unit and integration tests
🐛 Error Handling
The library includes comprehensive error handling with custom exceptions:
DocumentNotFoundError- Document file not foundTableNotFoundError- Table not found in documentInvalidTableIndexError- Invalid table indexInvalidCellPositionError- Invalid cell positionTableOperationError- Table operation failedDataFormatError- Invalid data format
🤝 Contributing
We welcome contributions! Here's how to get started:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes following our coding standards
- Add tests for new functionality
- Ensure all tests pass (
pytest) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Guidelines
- Follow PEP 8 coding standards
- Add type hints to all functions
- Write comprehensive tests for new features
- Update documentation for API changes
- Ensure backward compatibility when possible
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
📞 Support
- Issues: Report bugs and request features on GitHub Issues
- Documentation: Check the examples/ directory for usage examples
- Testing: Run the test suite to verify functionality
🔗 Dependencies
- Python 3.8+ - Core runtime
- python-docx ≥ 1.1.0 - Word document manipulation
- fastmcp ≥ 0.4.0 - MCP server framework
- pytest - Testing framework (development)
📊 Project Status
✅ Current Capabilities (Phase 1 + 2.1 + 2.7)
- 🧪 Test Coverage: 71/71 tests passing (100%)
- 🛠️ MCP Tools: 17 available tools (11 core + 4 formatting + 2 search)
- 📦 Modules: 7 core modules with clean architecture
- 🎨 Formatting: Complete cell formatting support
- 🔍 Search: Comprehensive table search capabilities
- 📚 Documentation: Comprehensive API docs and examples
🚀 Recent Additions (Phase 2.7)
- ✅ Table Content Search: Search across all table cells with multiple modes
- ✅ Header Search: Search specifically in table headers
- ✅ Search Modes: Exact match, contains, and regex pattern matching
- ✅ Search Options: Case sensitivity, table filtering, result limiting
- ✅ Detailed Results: Complete match information with table/cell positions
🎯 Next Milestones
- Phase 2.2: Data import/export (CSV, Excel, JSON)
- Phase 3: Advanced table features and templates
DOCX-MCP - Making Word document automation accessible through the Model Context Protocol! 🚀
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。