docx_mcp_server_ts
DOCX MCP Server
Un servidor MCP (Model Context Protocol) integral basado en TypeScript para el procesamiento universal de DOCX con soporte completo de OOXML. Procese documentos de Word mediante programación con soporte para texto, tablas, imágenes, encabezados/pies de página, SDT, comentarios y más.
Características
Acceso completo a OOXML: Leer/escribir partes DOCX a nivel ZIP con soporte completo de espacios de nombres
Operaciones de texto: Extraer, buscar y reemplazar texto con preservación mínima de diferencias
Gestión de tablas: Insertar/eliminar filas, modificar celdas, operaciones de combinar/dividir
Manejo de imágenes: Añadir imágenes en línea/posicionadas con dimensionado basado en EMU
Etiquetas de datos estructurados (SDT): Acceder a los controles de contenido por etiqueta o alias
Encabezados/Pies de página: Listar y modificar encabezados y pies de página de secciones
Control de cambios: Aceptar/rechazar revisiones, gestionar inserciones/eliminaciones
Comentarios: Gestionar comentarios de documentos
Metadatos: Leer/escribir propiedades principales y de aplicación
Caché LRU: Gestión eficiente de memoria con caché de partes
XML sin pérdidas: Preserva la estructura del documento con fast-xml-parser
Related MCP server: InkPaw
Instalación
npm install
npm run buildInicio rápido
Iniciar el servidor
npm startEl servidor escuchará en stdin/stdout los mensajes del protocolo MCP.
Instalación y configuración
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 (para Claude Code)
Editar ~/.claude.json y añadir a la sección "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"
}
}
}
}
}
}Ejemplo para 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"
}
}
}
}
}
}Herramientas MCP
Gestión de documentos
docx.open
Abrir un documento DOCX desde un archivo o búfer base64.
Entrada:
{
"path": "/path/to/document.docx",
"bufferBase64": "..." // OR provide base64 data
}Salida:
{
"docId": "uuid-string",
"parts": ["word/document.xml", ...],
"props": { "core": {}, "app": {} }
}docx.close
Cerrar un documento y liberar recursos.
Entrada: { "docId": "uuid" }
docx.save
Guardar el documento en un archivo o devolverlo como base64.
Entrada:
{
"docId": "uuid",
"path": "/output/path.docx", // optional
"returnBase64": true // optional
}docx.list_parts
Listar todas las partes del documento.
docx.part_read / docx.part_write
Leer/escribir partes XML individuales para acceso de bajo nivel.
Operaciones de texto
docx.get_text
Extraer todo el texto del documento.
Entrada: { "docId": "uuid", "scope": "document|headers|footers|all" }
docx.replace_text
Reemplazar texto preservando la estructura de run.
Entrada:
{
"docId": "uuid",
"match": "search text",
"replace": "replacement",
"mode": "literal|regex",
"where": "document|headers|footers|all"
}Salida: { "replaced": 5 }
docx.find
Buscar texto con contexto.
Salida:
{
"hits": [
{
"text": "found text",
"context": "...found text...",
"offset": 150
}
]
}Operaciones de tablas
docx.tables_list
Listar todas las tablas con dimensiones.
Salida:
{
"tables": [
{
"tableXPath": "//w:tbl[1]",
"rows": 5,
"colsApprox": 3
}
]
}docx.table_edit
Realizar operaciones de tabla.
Entrada:
{
"docId": "uuid",
"tableXPath": "//w:tbl[1]",
"op": {
"kind": "setCellText",
"row": 0,
"col": 0,
"text": "new value"
}
}Operaciones admitidas:
{ "kind": "setCellText", "row": number, "col": number, "text": string }{ "kind": "insertRow", "at": number }{ "kind": "deleteRow", "at": number }{ "kind": "insertCol", "at": number }{ "kind": "deleteCol", "at": number }
Etiquetas de datos estructurados (SDT)
docx.sdt_get
Obtener el contenido del control de contenido.
Entrada: { "docId": "uuid", "tagOrAlias": "control_tag" }
Salida:
{
"xml": "<w:p>...</w:p>",
"textPreview": "Control content..."
}docx.sdt_put
Actualizar el control de contenido.
Entrada:
{
"docId": "uuid",
"tagOrAlias": "control_tag",
"xmlFragment": "<w:p>...</w:p>"
}Operaciones de imágenes
docx.images_list
Listar todas las imágenes con metadatos.
Salida:
{
"images": [
{
"rId": "rId4",
"path": "word/media/image1.png",
"sizeEMU": { "cx": 914400, "cy": 914400 }
}
]
}docx.image_add
Insertar imagen en línea o anclada.
Entrada:
{
"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
Actualizar posición/tamaño de imagen anclada.
Operaciones avanzadas
docx.styles_get / docx.styles_set
Leer/escribir styles.xml
docx.numbering_get / docx.numbering_set
Leer/escribir numbering.xml
docx.headers_footers_list
Listar encabezados y pies de página con información de sección.
docx.headers_footers_get / docx.headers_footers_set
Leer/escribir un encabezado o pie de página específico.
docx.comments_list / docx.comments_add / docx.comments_delete
Gestionar comentarios de documentos.
docx.changes_accept_all
Aceptar todos los cambios controlados (eliminar w:del, desenvolver w:ins).
Salida: { "removedDel": 3, "flattenedIns": 5 }
docx.metadata_get / docx.metadata_set
Leer/escribir propiedades del documento (core.xml, app.xml).
Conversiones de tamaño
El servidor gestiona las conversiones de EMU (Unidad Métrica Inglesa) internamente:
1 pulgada = 914 400 EMU
1 mm ≈ 36 000 EMU
1 punto ≈ 12 700 EMU
Ejemplos
Extraer y reemplazar texto
// 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 });Modificar tabla
// 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
}
});Añadir imagen
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'
});Arquitectura
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 implementationsRendimiento
Memoria: la caché LRU limita las partes por documento a 50 elementos en caché
Tamaño total: admite documentos de hasta 100 MB en memoria
Acceso parcial: solo se analizan las partes solicitadas del ZIP
Diferencias mínimas: los reemplazos de texto preservan la estructura de run cuando es posible
Limitaciones
No se realizan cálculos de diseño de página (se necesita el motor de renderizado de Word)
Las transformaciones avanzadas de DrawingML son de solo lectura
No se admiten macros VBA ni objetos OLE incrustados
Los documentos extremadamente grandes (>500 MB) pueden requerir procesamiento por flujo
Desarrollo
# 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:debugRegistro
Controlar el nivel de registro mediante la variable de entorno:
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 onlySoporte de protocolo
Transporte: stdio
Protocolo: MCP (Model Context Protocol)
Manejador: @modelcontextprotocol/sdk
Licencia
MIT
Recursos
Available Tools
29 toolsdocx.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.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
Scored across 29 tools
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.
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.
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.
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
Related MCP Connectors
Document processing over MCP: merge, split and compress PDFs, run OCR, extract document text.
Parse, convert and create Office and PDF documents. OAuth at /mcp/connect/, API key at /mcp/.
Convert DOCX documents to and from PDF, TXT, HTML, ODT, JPG and RTF.
Document conversion MCP server: PDF to Markdown, image OCR, spreadsheet parsing.
Related MCP Servers
- AlicenseDqualityDmaintenanceEnables reading, writing, editing, and converting Office documents (ODT, DOCX, ODS, XLSX, PDF, etc.) using MCP tools, with no external dependencies.1117 npmMIT
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to generate, edit, validate, and render Word documents programmatically via MCP, ensuring correct OOXML structure and style.3MIT
- AlicenseBqualityCmaintenanceProvides 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.37MIT
- FlicenseCqualityDmaintenanceEnables comprehensive DOCX/OOXML document manipulation via MCP, covering text, tables, images, content controls, comments, tracked changes, and metadata.34-