Skip to main content
Glama
docx_mcp_server_ts

docx_mcp_server_ts

by Mavline

DOCX MCP 服务器

一个基于 TypeScript 的全面 MCP(模型上下文协议)服务器,用于通用 DOCX 处理,支持完整的 OOXML。以编程方式处理 Word 文档,支持文本、表格、图片、页眉/页脚、SDT、批注等。

功能特性

  • 完整 OOXML 访问:在 ZIP 级别读写 DOCX 部件,支持完整命名空间

  • 文本操作:提取、查找和替换文本,最小化差异保留

  • 表格管理:插入/删除行、修改单元格、合并/拆分操作

  • 图片处理:添加内联/浮动图片,支持基于 EMU 的尺寸设置

  • 结构化数据标签(SDT):按标签或别名访问内容控件

  • 页眉/页脚:列出和修改节页眉和页脚

  • 修订跟踪:接受/拒绝修订,处理插入/删除

  • 批注:管理文档批注

  • 元数据:读写核心和应用属性

  • LRU 缓存:通过部件缓存实现高效内存管理

  • 无损 XML:通过 fast-xml-parser 保留文档结构

Related MCP server: InkPaw

安装

npm install
npm run build

快速开始

启动服务器

npm start

服务器将在 stdin/stdout 上监听 MCP 协议消息。

安装与配置

Claude Code CLI

claude mcp install docx \
  --command node \
  --args /full/path/to/docx_mcp_server_ts/dist/index.js \
  --env LOG_LEVEL=INFO

~/.claude.json(用于 Claude Code)

编辑 ~/.claude.json,在 "projects" 部分中添加:

{
  "projects": {
    "/full/path/to/docx_mcp_server_ts": {
      "mcpServers": {
        "docx": {
          "command": "node",
          "args": ["/full/path/to/docx_mcp_server_ts/dist/index.js"],
          "env": {
            "LOG_LEVEL": "INFO"
          }
        }
      }
    }
  }
}

Linux/WSL 示例:

{
  "projects": {
    "/mnt/c/Users/pavelk/Desktop/Projects/MCP-servers/docx_mcp_server_ts": {
      "mcpServers": {
        "docx": {
          "command": "node",
          "args": ["/mnt/c/Users/pavelk/Desktop/Projects/MCP-servers/docx_mcp_server_ts/dist/index.js"],
          "env": {
            "LOG_LEVEL": "INFO"
          }
        }
      }
    }
  }
}

MCP 工具

文档管理

docx.open

从文件或 base64 缓冲区打开 DOCX 文档。

输入:

{
  "path": "/path/to/document.docx",
  "bufferBase64": "..."  // OR provide base64 data
}

输出:

{
  "docId": "uuid-string",
  "parts": ["word/document.xml", ...],
  "props": { "core": {}, "app": {} }
}

docx.close

关闭文档并释放资源。

输入: { "docId": "uuid" }

docx.save

将文档保存到文件或返回为 base64。

输入:

{
  "docId": "uuid",
  "path": "/output/path.docx",  // optional
  "returnBase64": true  // optional
}

docx.list_parts

列出文档中的所有部件。

docx.part_read / docx.part_write

读写单个 XML 部件,用于底层访问。

文本操作

docx.get_text

提取文档中的所有文本。

输入: { "docId": "uuid", "scope": "document|headers|footers|all" }

docx.replace_text

替换文本,保留运行结构。

输入:

{
  "docId": "uuid",
  "match": "search text",
  "replace": "replacement",
  "mode": "literal|regex",
  "where": "document|headers|footers|all"
}

输出: { "replaced": 5 }

docx.find

查找文本并返回上下文。

输出:

{
  "hits": [
    {
      "text": "found text",
      "context": "...found text...",
      "offset": 150
    }
  ]
}

表格操作

docx.tables_list

列出所有表格及其尺寸。

输出:

{
  "tables": [
    {
      "tableXPath": "//w:tbl[1]",
      "rows": 5,
      "colsApprox": 3
    }
  ]
}

docx.table_edit

执行表格操作。

输入:

{
  "docId": "uuid",
  "tableXPath": "//w:tbl[1]",
  "op": {
    "kind": "setCellText",
    "row": 0,
    "col": 0,
    "text": "new value"
  }
}

支持的操作:

  • { "kind": "setCellText", "row": number, "col": number, "text": string }

  • { "kind": "insertRow", "at": number }

  • { "kind": "deleteRow", "at": number }

  • { "kind": "insertCol", "at": number }

  • { "kind": "deleteCol", "at": number }

结构化数据标签(SDT)

docx.sdt_get

获取内容控件内容。

输入: { "docId": "uuid", "tagOrAlias": "control_tag" }

输出:

{
  "xml": "<w:p>...</w:p>",
  "textPreview": "Control content..."
}

docx.sdt_put

更新内容控件。

输入:

{
  "docId": "uuid",
  "tagOrAlias": "control_tag",
  "xmlFragment": "<w:p>...</w:p>"
}

图片操作

docx.images_list

列出所有图片及其元数据。

输出:

{
  "images": [
    {
      "rId": "rId4",
      "path": "word/media/image1.png",
      "sizeEMU": { "cx": 914400, "cy": 914400 }
    }
  ]
}

docx.image_add

插入内联或锚定图片。

输入:

{
  "docId": "uuid",
  "target": {
    "afterParagraphXPath": "//w:p[1]",
    "sdtTagOrAlias": "imageControl"  // OR use SDT
  },
  "image": {
    "path": "/local/image.png",
    "base64": "...",  // OR base64 data
    "filename": "image.png",
    "contentType": "image/png"
  },
  "placement": {
    "kind": "inline"  // OR { "kind": "anchor", "xEMU": 0, "yEMU": 0 }
  },
  "size": {
    "widthMM": 50,
    "heightMM": 50
  },
  "altText": "Description"
}

docx.image_update_position

更新锚定图片的位置/尺寸。

高级操作

docx.styles_get / docx.styles_set

读写 styles.xml

docx.numbering_get / docx.numbering_set

读写 numbering.xml

docx.headers_footers_list

列出页眉和页脚及节信息。

docx.headers_footers_get / docx.headers_footers_set

读写特定页眉或页脚。

docx.comments_list / docx.comments_add / docx.comments_delete

管理文档批注。

docx.changes_accept_all

接受所有修订(删除 w:del,展开 w:ins)。

输出: { "removedDel": 3, "flattenedIns": 5 }

docx.metadata_get / docx.metadata_set

读写文档属性(core.xml、app.xml)。

尺寸换算

服务器内部处理 EMU(英制公制单位)换算:

  • 1 英寸 = 914,400 EMU

  • 1 毫米 ≈ 36,000 EMU

  • 1 磅 ≈ 12,700 EMU

示例

提取和替换文本

// Open document
const openResult = await client.call('docx.open', {
  path: '/tmp/document.docx'
});
const docId = openResult.docId;

// Get text
const textResult = await client.call('docx.get_text', { docId });
console.log(textResult.text);

// Replace text
await client.call('docx.replace_text', {
  docId,
  match: 'old text',
  replace: 'new text',
  mode: 'literal'
});

// Save
await client.call('docx.save', {
  docId,
  path: '/tmp/document-modified.docx'
});

// Close
await client.call('docx.close', { docId });

修改表格

// List tables
const tablesResult = await client.call('docx.tables_list', { docId });
const tableXPath = tablesResult.tables[0].tableXPath;

// Update cell
await client.call('docx.table_edit', {
  docId,
  tableXPath,
  op: {
    kind: 'setCellText',
    row: 0,
    col: 0,
    text: 'Updated Value'
  }
});

// Insert row
await client.call('docx.table_edit', {
  docId,
  tableXPath,
  op: {
    kind: 'insertRow',
    at: 1
  }
});

添加图片

const fs = require('fs').promises;

const imageBuffer = await fs.readFile('/path/to/image.png');
const base64 = imageBuffer.toString('base64');

await client.call('docx.image_add', {
  docId,
  target: {
    afterParagraphXPath: '//w:p[1]'
  },
  image: {
    base64,
    filename: 'image.png',
    contentType: 'image/png'
  },
  placement: {
    kind: 'inline'
  },
  size: {
    widthMM: 100,
    heightMM: 75
  },
  altText: 'My image'
});

架构

src/
├── index.ts              # MCP server entry point
├── logger.ts             # Logging utility
├── errors.ts             # Error types and codes
├── ooxml/
│   ├── namespaces.ts     # OOXML constants and namespaces
│   ├── emu.ts            # Unit conversion utilities
│   ├── dom.ts            # XML DOM utilities (xmldom + fontoxpath)
│   ├── xmlParser.ts      # FXP parser with order preservation
│   ├── parts.ts          # ZIP part reading/writing
│   ├── rels.ts           # Relationship management
│   ├── text.ts           # Text operations with diff-match-patch
│   ├── tables.ts         # Table manipulation
│   ├── sdt.ts            # Structured Data Tags
│   ├── drawings.ts       # Image handling
│   ├── headersFooters.ts # Header/footer operations
│   ├── comments.ts       # Comment management
│   ├── changes.ts        # Track changes handling
│   ├── styles.ts         # Styles XML access
│   └── numbering.ts      # Numbering XML access
├── store/
│   ├── types.ts          # Store type definitions
│   └── docStore.ts       # Document store with LRU cache
└── mcp/
    └── tools.ts          # MCP tool implementations

性能

  • 内存:LRU 缓存将每个文档的部件限制为 50 个缓存项

  • 总大小:支持内存中最大 100MB 的文档

  • 部分访问:仅从 ZIP 中解析请求的部件

  • 最小差异:文本替换在可能时保留运行结构

限制

  • 不执行页面布局计算(需要 Word 的渲染引擎)

  • 高级 DrawingML 变换为只读

  • 不支持 VBA 宏和嵌入的 OLE 对象

  • 超大文档(>500MB)可能需要流式处理

开发

# Install dependencies
npm install

# Type check
npm run type-check

# Build
npm run build

# Run dev server
npm run dev

# Debug with inspector
npm run dev:debug

日志

通过环境变量控制日志级别:

LOG_LEVEL=DEBUG npm start     # Verbose
LOG_LEVEL=INFO npm start      # Default
LOG_LEVEL=WARN npm start      # Warnings only
LOG_LEVEL=ERROR npm start     # Errors only

协议支持

  • 传输:stdio

  • 协议:MCP(模型上下文协议)

  • 处理器:@modelcontextprotocol/sdk

许可证

MIT

资源

Available Tools

29 tools
docx.changes_accept_allB

Accept all changes

Inputs: no named parameters.

docx.closeB

Close a DOCX document and free resources

Inputs: docId.

docx.comments_addD

Add comment

Inputs: no named parameters.

docx.comments_deleteD

Delete comment

Inputs: no named parameters.

docx.comments_listC

List comments

Inputs: no named parameters.

docx.findB

Find text in document

Inputs: no named parameters.

docx.get_textC

Get all text from document

Inputs: docId.

docx.headers_footers_getC

Get header/footer

Inputs: no named parameters.

docx.headers_footers_listC

List headers/footers

Inputs: no named parameters.

docx.headers_footers_setC

Set header/footer

Inputs: no named parameters.

docx.image_addC

Add image

Inputs: no named parameters.

docx.images_listA

List all images

Inputs: no named parameters.

docx.image_update_positionD

Update image position

Inputs: no named parameters.

docx.list_partsB

List all parts (XML files) in a DOCX document

Inputs: docId.

docx.metadata_getC

Get metadata

Inputs: no named parameters.

docx.metadata_setC

Set metadata

Inputs: no named parameters.

docx.numbering_getC

Get numbering

Inputs: no named parameters.

docx.numbering_setC

Set numbering

Inputs: no named parameters.

docx.openB

Open a DOCX document from file or buffer

Inputs: path, bufferBase64.

docx.part_readB

Read a specific XML part from the document

Inputs: docId, partPath.

docx.part_writeC

Write/update a specific XML part in the document

Inputs: xml, docId, partPath.

docx.replace_textB

Replace text in document

Inputs: no named parameters.

docx.saveC

Save a DOCX document to file or get as base64

Inputs: path, docId, returnBase64.

docx.sdt_getC

Get SDT content

Inputs: no named parameters.

docx.sdt_putC

Set SDT content

Inputs: no named parameters.

docx.styles_getC

Get styles

Inputs: no named parameters.

docx.styles_setC

Set styles

Inputs: no named parameters.

docx.table_editD

Edit table

Inputs: no named parameters.

docx.tables_listB

List all tables

Inputs: no named parameters.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    C2.9/5.0

    Scored across 29 tools

    Disambiguation5/5

    Each tool has a clear, distinct purpose (e.g., get_text vs. find vs. replace_text), with no overlapping functionality. The split between list/get/set operations across different document parts (tables, headers, styles) avoids ambiguity.

    Naming Consistency5/5

    All tools follow a consistent verb_noun pattern (e.g., list_parts, part_read, table_edit) and share the 'docx.' prefix. The naming is uniform, lowercase with underscores, making it predictable and easy to navigate.

    Tool Count4/5

    With 29 tools, the count is higher than the typical 3-15 range, but it is justified by the comprehensive scope of DOCX manipulation (text, tables, images, styles, metadata, comments, etc.). It feels extensive rather than bloated, though slightly over the ideal range.

    Completeness4/5

    The tool set covers a wide range of DOCX operations including open/save, text handling, tables, images, styles, numbering, headers/footers, comments, changes, and metadata. Minor gaps exist (e.g., no explicit delete for tables or images, no create-new-document operation), but agents can likely work around these using existing tools.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      D
      quality
      D
      maintenance
      Enables reading, writing, editing, and converting Office documents (ODT, DOCX, ODS, XLSX, PDF, etc.) using MCP tools, with no external dependencies.
      11
      17 npm
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI agents to generate, edit, validate, and render Word documents programmatically via MCP, ensuring correct OOXML structure and style.
      3
      MIT
    • A
      license
      B
      quality
      C
      maintenance
      Provides MCP tools for working with Microsoft Word documents, enabling reading, editing with tracked changes, formatting, table manipulation, comments, and PDF conversion via direct OOXML manipulation.
      37
      MIT
    • F
      license
      C
      quality
      D
      maintenance
      Enables comprehensive DOCX/OOXML document manipulation via MCP, covering text, tables, images, content controls, comments, tracked changes, and metadata.
      34
      -