Skip to main content
Glama

docx-mcp: Word 文档 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 资源端点用于文档内容访问

Related MCP server: docx-comments

安装

前置要求

  • Python 3.10 或更高版本

  • uv 包管理器(或 pip)

快速开始

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

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

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

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

手动安装

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

# 安装依赖
uv sync

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

配置使用

Claude Desktop 配置

  1. 复制配置到 Claude:

cp claude_desktop_config.json ~/Library/Application\ Support/Claude/claude_desktop_config.json
  1. 更新配置中的路径:

{
  "mcpServers": {
    "docx-mcp": {
      "command": "uv",
      "args": [
        "--directory",
        "/你的/docx-mcp/路径",
        "run",
        "python",
        "-m",
        "docx_mcp.server"
      ]
    }
  }
}
  1. 重启 Claude Desktop

Kiro 配置

在 .kiro/settings/mcp.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])

环境变量配置

# 文档访问的项目目录
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 模板格式

开发

运行测试

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

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

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

代码风格

# 格式化代码
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 目录下。

虚拟环境问题

rm -rf venv/
./setup.sh

服务器无法启动

# 检查 Python 版本
python3 --version  # 应为 3.10+

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

许可证

MIT


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

Available Tools

24 tools
add_image_captionC

Add a caption to an image in the document.

Args: filepath: Path to the document image_index: Index of the image (0-based) caption_text: Caption text caption_type: Type of caption (Figure, Table, Equation)

Returns: Dictionary with status

Inputs: filepath (required), image_index (required), caption_text (required), caption_type. Returns: object

append_docxC

Append text content to an existing document.

Args: filepath: Path to the document content: Text content to append

Returns: Dictionary with status

Inputs: filepath (required), content (required). Returns: object

apply_bullet_listC

Apply bullet list formatting to paragraphs.

Args: filepath: Path to the document paragraph_indices: List of paragraph indices to bullet bullet_style: Type of bullet ('bullet', 'circle', 'square', 'dash', 'check')

Returns: Dictionary with status

Inputs: filepath (required), paragraph_indices (required), bullet_style. Returns: object

apply_numbered_listC

Apply numbered list formatting to paragraphs.

Args: filepath: Path to the document paragraph_indices: List of paragraph indices to number number_format: Format for numbering ('1', 'a', 'i', 'I', 'A')

Returns: Dictionary with status

Inputs: filepath (required), paragraph_indices (required), number_format. Returns: object

apply_paragraph_styleC

Apply a named paragraph style to a paragraph.

Args: filepath: Path to the document paragraph_index: Index of the paragraph (0-based) style_name: Name of the style to apply (e.g., "Heading 1", "Normal")

Returns: Dictionary with status

Inputs: filepath (required), paragraph_index (required), style_name (required). Returns: object

copy_docxC

Copy a Word document to a new location.

Args: source_filepath: Path to the source document destination_filepath: Path for the copied document

Returns: Dictionary with status

Inputs: source_filepath (required), destination_filepath (required). Returns: object

create_docxC

Create a new blank Word document.

Args: filepath: Path where to create the document title: Optional title for the document

Returns: Dictionary with status and document info

Inputs: filepath (required), title. Returns: object

delete_docxA

Delete a Word document.

Args: filepath: Path to the document to delete confirm: Must be True to actually delete (safety check)

Returns: Dictionary with status

Inputs: filepath (required), confirm. Returns: object

extract_imagesB

Extract all images from a Word document.

Args: filepath: Path to the document output_dir: Directory to save extracted images (optional) return_base64: If True, return images as base64 encoded strings

Returns: Dictionary with extracted images info and optionally base64 data

Inputs: filepath (required), output_dir, return_base64. Returns: object

fill_merge_fieldsB

Fill merge fields in a document with provided data.

Args: filepath: Path to the document or template data: Dictionary mapping field names to values

Returns: Dictionary with status and modified document info

Inputs: filepath (required), data (required). Returns: object

get_document_propertiesC

Get document properties and metadata.

Args: filepath: Path to the document

Returns: Dictionary with document properties

Inputs: filepath (required). Returns: object

get_equationA

Get a specific equation by index from a Word document.

Args: filepath: Path to the document equation_index: Index of the equation (0-based) include_omml: If True, include the raw OMML XML

Returns: Dictionary with equation details including LaTeX representation

Inputs: filepath (required), equation_index (required), include_omml. Returns: object

health_checkB

Check server health and status.

Returns: Dictionary with health status

Inputs: no named parameters. Returns: object

insert_imageC

Insert an image into a document.

Args: filepath: Path to the document image_path: Path to the image file to insert width: Image width in inches (optional) height: Image height in inches (optional)

Returns: Dictionary with status

Inputs: filepath (required), image_path (required), width, height. Returns: object

list_content_controlsC

List all content controls in a document.

Args: filepath: Path to the document

Returns: Dictionary with list of content controls

Inputs: filepath (required). Returns: object

list_docxC

List all Word documents in a directory.

Args: directory: Directory path to list (defaults to project directory)

Returns: Dictionary with list of documents

Inputs: directory. Returns: object

list_equationsA

List all mathematical equations/formulas in a Word document.

Extracts equations stored in Office Math Markup Language (OMML) format and converts them to LaTeX notation for readability.

Args: filepath: Path to the document

Returns: Dictionary with list of equations including LaTeX representation

Inputs: filepath (required). Returns: object

list_imagesC

List all images in a document.

Args: filepath: Path to the document

Returns: Dictionary with list of images and metadata

Inputs: filepath (required). Returns: object

list_merge_fieldsA

Extract all MERGEFIELD names from a document or template.

Args: filepath: Path to the document

Returns: Dictionary with list of merge field names

Inputs: filepath (required). Returns: object

list_stylesB

List all paragraph and character styles available in a document.

Args: filepath: Path to the document

Returns: Dictionary with list of styles

Inputs: filepath (required). Returns: object

read_docxC

Read and extract text content from a Word document.

Args: filepath: Path to the document to read

Returns: Dictionary with document text and metadata

Inputs: filepath (required). Returns: object

set_document_propertiesB

Set document properties and metadata.

Args: filepath: Path to the document title: Document title subject: Document subject author: Document author keywords: Document keywords comments: Document comments

Returns: Dictionary with status

Inputs: filepath (required), title, subject, author, +2 more. Returns: object

set_list_levelB

Set indentation level for a list paragraph.

Args: filepath: Path to the document paragraph_index: Index of the paragraph level: Indentation level (0-8)

Returns: Dictionary with status

Inputs: filepath (required), paragraph_index (required), level (required). Returns: object

write_docxC

Create or overwrite a document with plain text content.

Args: filepath: Path to the document content: Text content to write

Returns: Dictionary with status

Inputs: filepath (required), content (required). Returns: object

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    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 recent community issues

    Related MCP Connectors

    Related MCP Servers