Skip to main content
Glama
README.md
# docx-mcp: Word 文档 MCP 服务器
 
> 基于 [rajesh-docx-mcp](https://lobehub.com/zh/mcp/rajesh-docx-mcp) 开发改进

一个功能全面的 Model Context Protocol (MCP) 服务器,用于读取、写入和操作 Microsoft Word (.docx) 文档。提供 30+ 工具,覆盖文档全生命周期管理,从基础文本操作到高级格式化、模板和内容控制。

## 功能特性

### 核心文档操作
- **create_docx** - 创建新的空白文档
- **read_docx** - 提取文本和元数据
- **write_docx** - 写入/覆盖文档内容
- **append_docx** - 追加内容到现有文档
- **list_docx** - 列出目录中的文档
- **delete_docx** - 安全删除文档
- **copy_docx** - 复制文档到新位置

### Word 原生模板系统
- **list_merge_fields** - 提取文档中的 MERGEFIELD 名称
- **fill_merge_fields** - 用数据替换合并字段值
- **list_content_controls** - 列出所有内容控件
- **get_document_properties** - 读取文档元数据
- **set_document_properties** - 更新文档元数据

### 样式管理
- **list_styles** - 列出所有可用的段落和字符样式
- **apply_paragraph_style** - 应用命名样式("标题 1"、"正文"等)

### 列表 - 项目符号和编号
- **apply_bullet_list** - 应用项目符号格式
- **apply_numbered_list** - 应用编号格式
- **set_list_level** - 控制列表缩进级别(0-8)

### 图片和标题
- **insert_image** - 插入图片并设置尺寸
- **add_image_caption** - 添加自动编号的标题
- **list_images** - 列出文档中的所有图片
- **extract_images** - 提取图片并保存或返回 base64 编码

### 公式提取(新增)
- **list_equations** - 列出文档中所有数学公式,转换为 LaTeX 格式
- **get_equation** - 获取指定索引的公式详情

### 其他特性
- 结构化 JSON 日志
- 安全优先设计,带路径验证
- 全面的错误处理
- 支持文档属性和元数据
- MCP 资源端点用于文档内容访问

## 安装

### 前置要求
- Python 3.10 或更高版本
- uv 包管理器(或 pip)

### 快速开始

```bash
# 1. 克隆或进入项目目录
cd docx-mcp

# 2. 运行安装脚本
./setup.sh

# 3. 激活虚拟环境
source venv/bin/activate

# 4. 运行服务器
./run.sh
```

### 手动安装

```bash
# 创建并激活虚拟环境
python3 -m venv venv
source venv/bin/activate

# 安装依赖
uv sync

# 运行服务器
python -m docx_mcp.server
```

## 配置使用

### Claude Desktop 配置

1. 复制配置到 Claude:
```bash
cp claude_desktop_config.json ~/Library/Application\ Support/Claude/claude_desktop_config.json
```

2. 更新配置中的路径:
```json
{
  "mcpServers": {
    "docx-mcp": {
      "command": "uv",
      "args": [
        "--directory",
        "/你的/docx-mcp/路径",
        "run",
        "python",
        "-m",
        "docx_mcp.server"
      ]
    }
  }
}
```

3. 重启 Claude Desktop

### Kiro 配置

在 `.kiro/settings/mcp.json` 中添加:
```json
{
  "mcpServers": {
    "docx-mcp": {
      "command": "uv",
      "args": [
        "--directory",
        "/你的/docx-mcp/路径",
        "run",
        "python",
        "-m",
        "docx_mcp.server"
      ]
    }
  }
}
```

## 使用示例

### 创建和写入文档

```
用户: 在 ./report.docx 创建一个新文档,标题为"月度报告"
工具: create_docx(filepath="./report.docx", title="月度报告")

用户: 写入一些内容
工具: write_docx(filepath="./report.docx", content="执行摘要\n主要发现...")
```

### 提取图片

```
用户: 提取文档中的所有图片
工具: extract_images(filepath="./doc.docx", output_dir="./images")

用户: 获取图片的 base64 编码
工具: extract_images(filepath="./doc.docx", return_base64=True)
```

### 提取公式

```
用户: 列出文档中的所有公式
工具: list_equations(filepath="./论文.docx")

用户: 获取第 18 个公式
工具: get_equation(filepath="./论文.docx", equation_index=17)
```

### 应用样式和格式

```
用户: 列出文档中可用的样式
工具: list_styles(filepath="./report.docx")

用户: 将第一段应用"标题 1"样式
工具: apply_paragraph_style(filepath="./report.docx", paragraph_index=0, style_name="Heading 1")
```

### 创建列表

```
用户: 将第 3-5 段设为项目符号列表
工具: apply_bullet_list(filepath="./report.docx", paragraph_indices=[3,4,5])

用户: 改为编号列表
工具: apply_numbered_list(filepath="./report.docx", paragraph_indices=[3,4,5])
```

## 环境变量配置

```bash
# 文档访问的项目目录
export DOCX_MCP_PROJECT_DIR=/path/to/documents

# 最大文件大小(默认:50MB)
export DOCX_MCP_MAX_FILE_SIZE=52428800

# 日志级别(DEBUG, INFO, WARNING, ERROR)
export DOCX_MCP_LOG_LEVEL=INFO

# 允许访问任意路径(谨慎使用)
export DOCX_MCP_ALLOW_UNSAFE_PATHS=true
```

## 文件系统安全

服务器验证所有文件路径以防止目录遍历攻击:
- 默认允许访问 home 目录下的所有路径
- 验证文件扩展名(.docx, .doc, .dotx, .dot)
- 强制文件大小限制
- 防止空字节注入

## 支持的文档格式

- **.docx** - 现代 Microsoft Word 格式(推荐)
- **.doc** - 旧版 Microsoft Word 格式
- **.dotx** - Word 模板格式
- **.dot** - 旧版 Word 模板格式

## 开发

### 运行测试

```bash
# 安装开发依赖
uv sync --all-extras

# 运行所有测试
uv run pytest tests/

# 带覆盖率运行
uv run pytest tests/ --cov=src/docx_mcp
```

### 代码风格

```bash
# 格式化代码
uv run black src/ tests/

# 检查代码
uv run ruff check src/ tests/

# 类型检查
uv run mypy src/
```

## 项目结构

```
docx-mcp/
├── src/docx_mcp/
│   ├── __init__.py           # 包初始化
│   ├── server.py             # 主 MCP 服务器及所有工具
│   ├── config.py             # 配置管理
│   ├── logging_config.py     # 日志设置
│   ├── exceptions.py         # 自定义异常类
│   └── utils/
│       ├── path_utils.py     # 路径验证和规范化
│       ├── document_utils.py # 文档处理工具
│       └── __init__.py
├── tests/                    # 测试文件
├── pyproject.toml            # 项目元数据和依赖
├── setup.sh                  # 环境安装脚本
├── run.sh                    # 服务器启动脚本
└── README.md                 # 本文件
```

## 故障排除

### 在其他项目路径无法使用
设置环境变量 `DOCX_MCP_ALLOW_UNSAFE_PATHS=true` 或确保文档在 home 目录下。

### 虚拟环境问题
```bash
rm -rf venv/
./setup.sh
```

### 服务器无法启动
```bash
# 检查 Python 版本
python3 --version  # 应为 3.10+

# 查看日志
cat logs/docx_mcp_*.log
```

## 许可证

MIT

---

基于 FastMCP 和 python-docx 构建,提供全面的 Word 文档管理能力。

TDQS

B3.4/5.0

Scored across 24 tools

Disambiguation4/5

Most tools have distinct purposes targeting specific document elements (images, equations, lists, styles), though some overlap exists between write_docx/create_docx/append_docx for document creation/modification and between various list_* tools for different element types. Descriptions clarify boundaries well, but an agent might occasionally need to choose between similar tools.

Naming Consistency5/5

Excellent consistency with a clear verb_noun pattern throughout (e.g., add_image_caption, apply_bullet_list, extract_images, list_equations). All tools use snake_case exclusively, with verbs accurately describing actions (add, apply, copy, create, delete, extract, fill, get, insert, list, read, set, write). No deviations or mixed conventions.

Tool Count3/5

24 tools is borderline heavy for a document processing server, though the domain (Word document manipulation) is rich. Many tools are specialized (e.g., separate tools for bullet vs numbered lists, multiple image/equation tools), which could feel overwhelming but may be justified by the complexity of Word documents. A more consolidated design might reduce the count.

Completeness5/5

Extremely comprehensive coverage of Word document operations: full CRUD (create_docx, read_docx, write_docx, delete_docx), content manipulation (text, images, equations, lists, styles), metadata handling, merge fields, content controls, and utilities (copy, health_check). No obvious gaps; agents can perform complex document workflows without dead ends.

Maintenance

ActivityInactive
ResponsivenessNo issues