Skip to main content
Glama

TianshangScribe

中文版

PyPI CI License TianshangScribe MCP server

Procesamiento de documentos de Office multiplataforma para desarrolladores, automatización CLI y agentes de IA. Crea, edita, rellena plantillas y convierte documentos de Word (.docx), Excel (.xlsx) y PowerPoint (.pptx), con marcado estilo LaTeX, fórmulas matemáticas OMML nativas y un motor de plantillas ({{placeholders}}, bucles {{#each}}, condiciones {{#if}}). Incluye un servidor MCP con 7 herramientas (crear, editar, rellenar plantilla, convertir, extraer, validar, comparar) sobre transportes stdio, SSE y HTTP Streamable, con autenticación por token portador y limitación de velocidad.

Advertencia: API inestable \u2014 se esperan cambios incompatibles

Este proyecto está en pre-1.0 (0.x). Las opciones de CLI, las firmas de las herramientas MCP, la sintaxis de las plantillas y los formatos de salida no están congelados y pueden cambiar sin previo aviso. Compromiso de compatibilidad: cualquier cambio incompatible se anunciará en el CHANGELOG al menos con una versión de antelación y se acompañará de una guía de migración. Para uso en producción, fija una versión específica y revisa el CHANGELOG antes de actualizar.

Instalación

pip install tianshang-scribe

# Or from source:
git clone https://github.com/Tianshang301/TianshangScribe.git
cd TianshangScribe
pip install -e ".[dev]"

Despliegue en Linux

Docker (recomendado para el servidor MCP sobre HTTP Streamable):

git clone https://github.com/Tianshang301/TianshangScribe.git
cd TianshangScribe
docker compose up -d
# Streamable HTTP MCP Server at http://localhost:8080/mcp
# (override transport / auth / rate limits via TIANSHANG_SCRIBE_* env vars)

Paquete .deb (Debian / Ubuntu):

# Download from GitHub Releases
sudo dpkg -i tianshang-scribe_0.7.1_all.deb
tianshang-scribe --help

pipx (CLI aislado):

pipx install tianshang-scribe
tianshang-scribe --help

Requiere Python 3.10+ · python-docx · openpyxl · python-pptx · typer · rich · lxml

Related MCP server: docx-forge-mcp

Inicio rápido

# Create a Word document
tianshang-scribe -w --create -a "Hello World" -o hello.docx

# Replace text (--regex for regex mode)
tianshang-scribe input.docx -r "old" --replace-new "new" -o output.docx

# LaTeX markup with nesting
tianshang-scribe -w --create --latex-style \
  -s "font=Times New Roman,size=14" \
  -a "\bfseries{\itshape{bold italic}} \fontsize{24}{Heading} \color{FF0000}{red}" \
  -o styled.docx

# Math formulas —auto-converted to native Word OMML
tianshang-scribe -w --create \
  --math "x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}" \
  --math "\sum_{i=0}^{n} i^2" \
  -o formulas.docx

# Template filling (JSON / CSV / YAML →{{placeholder}})
tianshang-scribe template.docx -t data.json -o filled.docx

# Convert to PDF (office2pdf ~2MB, or LibreOffice fallback)
tianshang-scribe input.docx --topdf -o output.pdf

# MCP Server —stdio mode (Claude Code / Cursor)
python -m tianshang_scribe.mcp.server

# MCP Server —SSE mode (Dify / Coze / FastGPT)
python -m tianshang_scribe.mcp.server --transport sse --port 8080

# Excel: import CSV, sort, export JSON
tianshang-scribe -e --create --from-csv data.csv --sort "A1:A10 asc" --to-json -o out.json

# Excel: add formula, protect workbook
tianshang-scribe budget.xlsx --formula "B10 =SUM(B2:B9)" --protect "p@ss" -o protected.xlsx

Opciones globales

Parámetro

Descripción

input_file

Ruta del documento de entrada (omitir con --create)

-w --word

Procesar documento de Word

-e --excel

Procesar libro de Excel

-p --ppt

Procesar presentación de PowerPoint

-o --output

Ruta del archivo de salida

--force

Permitir sobrescribir archivos existentes

--topdf

Salida como PDF

--stdin

Leer desde la entrada estándar

--stdout

Escribir en la salida estándar

Cuando se omite -w/-e/-p, el tipo de documento se deduce de la extensión del archivo de entrada.

Operaciones

Opción

Descripción

Ejemplo

-cr --create

Crear documento en blanco

--create -w

-a --add

Añadir texto

-a "Hola"

--column

Columna de destino para --add

--column 2

-r --replace

Buscar y reemplazar

-r "foo" --replace-new "bar"

-d --delete

Eliminar contenido

-d "palabra clave"

-cl --clear

Limpiar contenido / formatos / enlaces

--clear formats

-m --modify

Modificar contenido

-m "viejo" --modify-new "nuevo"

-s --style

Establecer estilo

-s "font=Times,size=14,bold"

-t --template

Relleno de plantilla

-t data.json

-x --extract

Extraer datos (math/latex etc.)

-x latex

--meta

Establecer propiedades

--meta "title=Informe,author=Juan"

--latex-style

Habilitar análisis LaTeX

--math

Añadir fórmula matemática (Word)

--math "\frac{a}{b}"

--math-style

Dialecto de análisis matemático (office/mathtype)

--math-style mathtype

--math-font

Fuente matemática OMML (por defecto Cambria Math)

--math-font "Times New Roman"

--math-mtef

Incrustar como objeto OLE de MathType (MTEF)

--math "\frac{a}{b}" --math-mtef

--heading

Añadir encabezado (Word)

--heading "level:1 text:Intro"

--regex

Modo de expresión regular

Usar con --replace --delete

--merge

Fusionar archivos

--merge "a.docx,b.docx"

--split

Dividir documento (solo Excel: --split by-sheet)

--split by-sheet

--comment

Añadir comentario (Word) / notas del orador (PPT)

--comment "2 Nota de texto"

--add-table

Añadir tabla (Word)

--add-table "H1,H2|a1,a2"

--chart-add

Añadir gráfico (Excel)

--chart-add "type=bar data=B1:C10"

--batch

Modo por lotes

--batch

--files

Patrón glob para lote

--files "informes/*.docx"

--schedule-db

Ruta de la base de datos SQLite de programación

--schedule-db ~/.tianshang-scribe/schedules.db

--schedule-add

Registrar programación

--schedule-add "daily|0 9 * * *|echo hi"

--schedule-rm

Eliminar programación

--schedule-rm daily

--schedule-list

Listar programaciones

--schedule-list

--schedule-run

Ejecutar programación ahora

--schedule-run daily

--schedule-run-all

Ejecutar programaciones pendientes

--schedule-run-all

--run-script

Ejecutar script en sandbox

--run-script build.py

--stdin

Leer desde stdin

--stdout

Escribir en stdout

Opciones específicas de Word

Opción

Descripción

Ejemplo

--heading

Añadir encabezado

--heading "level:1 text:Intro"

--math

Añadir fórmula matemática

--math "\frac{a}{b}"

--latex-style

Habilitar marcado LaTeX

--toc

Generar tabla de contenidos

--toc

--section-break

Insertar salto de sección

--section-break

--header

Establecer encabezado de página

--header "Capítulo 1"

--footer

Establecer pie de página

--footer "Página X"

--watermark

Marca de agua de texto

--watermark "BORRADOR"

--tomd

Convertir a Markdown

--tomd

--tohtml

Convertir a HTML

--tohtml

Opciones específicas de Excel

Opción

Descripción

Ejemplo

--sheet-add

Añadir hoja de cálculo

--sheet-add "Q1"

--sheet-delete

Eliminar hoja de cálculo

--sheet-delete "Hoja2"

--sheet-rename

Renombrar hoja de cálculo

--sheet-rename "Antigua Nueva"

--column-width

Establecer ancho de columna

--column-width "2=20"

--row-height

Establecer alto de fila

--row-height "3=30"

--formula

Establecer fórmula de celda

--formula "A1 =SUM(B1:B10)"

--from-csv

Importar datos CSV

--from-csv datos.csv

--sort

Ordenar rango

--sort "A1:A10 asc"

--chart-add

Añadir gráfico

--chart-add "type=bar data=B1:C10"

--protect

Establecer contraseña

--protect "p@ss"

--unprotect

Eliminar contraseña

--unprotect

--to-csv

Exportar como CSV

--to-json

Exportar como JSON

--to-html

Exportar como HTML

Marcado de estilo LaTeX

Incorpora el siguiente marcado en el contenido de --add. Habilítalo con --latex-style. Admite anidamiento.

Sintaxis

Efecto

\bfseries{texto}

Negrita

\itshape{texto}

Cursiva

\scshape{texto}

Versalitas

\underline{texto}

Subrayado

\rmfamily{texto}

Romana (serif)

\sffamily{texto}

Sans-serif

\ttfamily{texto}

Monoespaciada

\fontfamily{Arial}{texto}

Fuente específica

\fontsize{18}{texto}

Tamaño de fuente (pt)

\color{FF0000}{texto}

Color (hex)

\centering{...}

Alineación centrada *

\raggedright{...}

Alineación izquierda *

\raggedleft{...}

Alineación derecha *

\linespread{1.5}{...}

Interlineado *

\indent{...} / \noindent{...}

Sangría *

\heading{2}{Título}

Insertar encabezado

\newpage

Salto de página

\includegraphics{ruta}

Insertar imagen

* Formato a nivel de párrafo (crea un nuevo párrafo).

Configuración de fuentes

Comando

Efecto

\setmainfont{Nombre}

Fuente occidental predeterminada

\setCJKmainfont{Nombre}

Fuente CJK predeterminada

\setsansfont{Nombre}

Fuente sans-serif

\setCJKsansfont{Nombre}

Fuente CJK sans-serif

\setmonofont{Nombre}

Fuente monoespaciada

\setCJKmonofont{Nombre}

Fuente CJK monoespaciada

Word OOXML separa de forma nativa w:ascii (occidental) y w:eastAsia (CJK), lo que permite el cambio automático de fuente en texto mixto.

Fórmulas matemáticas

Las fórmulas LaTeX con --math se convierten en OMML nativo de Word (Office Math Markup Language). El conversor es un analizador sintáctico descendente recursivo escrito a mano (expresión → término → factor → átomo) sobre un árbol de tokens anidado e inmutable (tokens de fracción, raíz, n-ario, sub/superíndice, acento, estilo y delimitador), despachado mediante una tabla de comandos O(1) con expresiones regulares precompiladas y división de argumentos sin copias. Usa --math-font "Times New Roman" para renderizar ecuaciones con una fuente serif estilo MathType en lugar de la fuente Cambria Math predeterminada de Word (<m:mathPr><m:mathFont>). --math-style mathtype cambia el dialecto de análisis de LaTeX para la compatibilidad con MathType. Usa --math-mtef para incrustar la fórmula como un objeto OLE real de MathType (binario MTEF) en su lugar, editable por MathType heredado (6.x y anteriores), el mismo formato que --extract math lee. La salida es estable byte a byte entre versiones (protegida por una suite de regresión de capturas de referencia).

Sintaxis compatible

Categoría

Comandos

Fracciones

\frac{num}{den}

Raíces

\sqrt{content} \sqrt[n]{content}

Super/Subíndices

x^{2} x_{i} x_{i}^{n}

Sumas/Integrales

\sum \int \oint \prod \coprod \bigcup \bigcap \bigvee \bigwedge

Límites

\lim_{x \to 0} \max \min \sup \inf

Funciones con nombre

\sin \cos \tan \cot \sec \csc \log \ln \det \Pr \gcd \deg \dim \hom \ker \arg

Letras griegas

\alpha \beta \gamma\Gamma \Delta \Theta

Símbolos

\pm \times \div \cdot \infty \partial \nabla \forall \exists

Relaciones

\leq \geq \neq \approx \equiv \propto \subset \supset \in

Flechas

\to \rightarrow \leftarrow \mapsto \uparrow

Acentos

\hat{x} \bar{x} \tilde{x} \dot{x} \ddot{x} \vec{x} \widehat{x} \widetilde{x}

Delimitadores

\left( \right) \left[ \right] \left\{ \right\}

Fuentes matemáticas

\mathrm{abc} \mathbf{abc} \mathit{abc} \mathcal{ABC} \mathbb{ABC} \mathsf{abc} \mathtt{abc}

Tipografía matemática

Conforme a los estándares de las principales revistas de matemáticas (AMS, Elsevier, Springer):

Contenido

Estilo

Ejemplo

Variables de una sola letra

Cursiva

a b x y

Dígitos

Recta

0 1 2

Funciones con nombre

Recta

\sin \cos \log

Letras griegas en minúsculas

Cursiva

\alpha \beta \gamma

Letras griegas en mayúsculas

Recta

\Gamma \Delta \Theta

Autodetección

Los comandos en el texto --add se reconocen automáticamente como matemáticas incluso sin envolverlos con $...$:

  • Con argumentos: \frac \sqrt \sum \int \prod \lim

  • Acentos: \hat{x} \bar{x} \vec{x} etc.

  • Operadores unarios: \sin \cos \tan \log \ln etc.

  • H_{2}O y m^{2} en texto sin formato se convierten en subíndices/superíndices Unicode (H₂O / m²)

Sintaxis de estilo

--style usa pares clave-valor separados por comas:

--style "font=Times New Roman,size=14,bold,italic,color=FF0000,align=center"

Clave

Alias

Valor

Descripción

font

font_name, font-family

Nombre de fuente

Fuente occidental

cjk-font

cjk_font_name, cjk-font-family

Nombre de fuente

Fuente CJK

size

font_size, font-size

pt

Tamaño de fuente

bold

indica

Negrita

italic

indicador

Cursiva

underline

indicador

Subrayado

color

font_color, font-color

FF0000

Color hexadecimal

align

alignment

left/center/right/justify

Alineación

Las claves booleanas (bold italic underline) son True si están presentes.

Relleno de plantillas

Admite fuentes de datos JSON, CSV y YAML. Reemplaza {{placeholder}} en los documentos. Los objetos anidados se expanden mediante notación de puntos. Los bucles iteran sobre los valores de una lista. Los condicionales muestran u ocultan bloques.

{
  "name": "John Doe",
  "date": "2026-07-28",
  "user": { "city": "Beijing" },
  "show": true,
  "paid": false,
  "items": [
    { "product": "Widget", "price": "10" },
    { "product": "Gadget", "price": "20" }
  ]
}
{{name}}              → John Doe
{{user.city}}         → Beijing
{{#each items}}       → repeats the block for each item
  {{product}}: {{price}}
{{/each}}
{{#if show}}          → shown only when show is truthy
  Confidential content
{{/if}}
{{#if role=admin}}    → shown only when role equals "admin"
  Admin dashboard
{{/if}}
{{#unless paid}}      → shown only when paid is falsy
  Payment required
{{/unless}}

Características de Excel

Característica

Opción de la CLI

Gestión de hojas

--sheet-add --sheet-delete --sheet-rename

Tamaño de columnas/filas

--column-width --row-height

Fórmulas

--formula "A1 =SUM(B1:B10)"

Importación de datos

--from-csv

Exportación de datos

--to-csv --to-json --to-html

Ordenación

--sort "A1:A10 asc"

Gráficos

--chart-add "type=bar data=B1:C10"

Protección

--protect --unprotect

Características de PowerPoint

Característica

Descripción

Gestión de diapositivas

Añadir, eliminar y reordenar diapositivas (--slide-add, --slide-delete, --slide-move)

Diseños

Aplicar diseños de diapositiva por nombre o índice (--layout)

Notas del orador

Añadir notas del presentador (--notes)

Fórmulas matemáticas

$...$ / $$...$$ representadas como OMML nativo

Transiciones

Configurar transiciones de diapositiva —fundido, empujar, barrido, etc. (--transition)

Compresión multimedia

Comprimir imágenes (--compress-media "1920,80")

Protección

Establecer o quitar contraseña (--protect, --unprotect)

Códigos de salida

Código

Significado

0

Éxito

1

Error general

2

Error de argumentos

3

No implementado

Servidor MCP

TianshangScribe incluye un servidor MCP (Model Context Protocol): los agentes de IA pueden crear, editar, rellenar plantillas, convertir y extraer datos de documentos de Office.

Conexión rápida

stdio (Claude Code, Cursor):

{"mcpServers": {"tianshang-scribe": {
  "command": "python", "args": ["-m", "tianshang_scribe.mcp.server"]
}}}

SSE (Dify, Coze, FastGPT):

python -m tianshang_scribe.mcp.server --transport sse --host 0.0.0.0 --port 8080
{"mcpServers": {"tianshang-scribe": {
  "url": "http://localhost:8080/sse", "transport": "sse"
}}}

Herramientas (7)

Herramienta

Descripción

create_office_document

Crear archivos .docx / .xlsx / .pptx con bloques de contenido estructurado

edit_office_document

Reemplazar, eliminar, modificar, aplicar estilos y añadir operaciones en documentos existentes

fill_template

Rellenar {{placeholders}} con datos; admite {{#each}} / {{#if}}

convert_document

Convertir entre formatos (docx↔pdf/md/html, xlsx↔csv/json)

extract_document_data

Extraer metadatos, texto completo o estructura del documento

validate_template

Prevalidar los placeholders de la plantilla antes de rellenar con datos

compare_documents

Diferencia a nivel de párrafo entre dos archivos .docx

Capacidades

Característica

Detalle

Protocolo

MCP 2024-11-05 · stdio + SSE · JSON-RPC 2.0

Recursos

resources/list + resources/read —documentos expuestos como URI legibles

Prompts

5 plantillas de flujo de trabajo incorporadas (prompts/list + prompts/get)

Progreso

notifications/progress durante la conversión a PDF y operaciones largas

Respuesta

content[] multicolor: mensaje de texto + recurso (URI de archivo, tipo MIME, tamaño)

Esquema

Restricciones enum, default, examples, minimum/maximum en todos los parámetros

Producción (solo SSE)

# With authentication
TIANSHANG_SCRIBE_AUTH_TOKEN="secret" \
python -m tianshang_scribe.mcp.server --transport sse --host 0.0.0.0 --port 8080

# Health check
curl http://localhost:8080/health
# {"status":"ok","version":"0.7.1","uptime_seconds":3600,"active_sessions":3,"tools_available":7}

# CORS whitelist
python -m tianshang_scribe.mcp.server --transport sse --cors-origins "https://coze.com,https://dify.ai"

Endpoints: GET /health · GET /sse · POST /message?session_id=X

Documentación completa: docs/mcp/README.md.

python tests/integration/mcp/mcp_stdio_smoke.py     # 9/9 quick tests (stdio)
python tests/integration/mcp/test_sse.py        # 3/3 SSE transport tests
python tests/integration/mcp/mcp_agent_sim.py      # 11-scenario Agent simulation

Arquitectura

src/
└── tianshang_scribe/    # importable package (tianshang_scribe.*)
    ├── cli/               # Typer CLI entry
    │  ├── main.py        # Command parsing & dispatch
    │  └── global_opts.py # File path / type inference
    ├── core/              # Document engine abstraction
    │  ├── document.py    # DocumentABC unified interface
    │  ├── word_engine.py # Word engine (python-docx)
    │  ├── excel_engine.py# Excel engine (openpyxl)
    │  └── ppt_engine.py  # PPT engine (python-pptx)
    ├── rendering/         # Style & formula rendering
    │  ├── styles.py      # TextStyle dataclass
    │  ├── latex_parser.py # LaTeX markup parser
    │  ├── math_omml.py   # LaTeX →OMML math converter
    │  └── template.py    # Template filling engine
    ├── transform/         # Format conversion
    │  └── pdf.py         # PDF export (office2pdf + LibreOffice)
    ├── mcp/                    # MCP Server (official mcp SDK 2.x)
    │  ├── server.py           # build_server + entry (stdio / SSE / Streamable HTTP)
    │  ├── transport.py        # transport wiring + ASGI middleware
    │  ├── schemas.py          # pydantic models + as_dict
    │  ├── auth.py             # Bearer token auth
    │  ├── rate_limit.py       # token bucket rate limiting
    │  ├── metrics.py          # Prometheus-style metrics
    │  ├── security.py         # read-only / destructive classification
    │  ├── prompts.py          # 5 prompt workflows
    │  ├── tools/              # 7 Agent tools
    │  │  ├── _registry.py    # tool registry (schemas auto-derived)
    │  │  ├── create.py / edit.py / template.py / convert.py
    │  │  ├── validate.py / compare.py
    │  └── errors.py           # structured error codes + fixes
    └── utils/             # Utility functions
        └── file_utils.py

Pila tecnológica

Componente

Tecnología

CLI

Typer + Rich

Word

python-docx

Excel

openpyxl

PPT

python-pptx

Matemáticas

Analizador descendente recursivo escrito a mano → OMML XML (árbol de tokens inmutable, tabla de ejecución de comandos)

Plantillas

Motor propio ({{variable}}, {{#each}}, {{#if}})

PDF

office2pdf (binario Rust de ~2MB, cero dependencias) + alternativa LibreOffice

Calidad

pytest (936 pruebas) · ruff · mypy

Compilar EXE

pip install pyinstaller
pyinstaller --onefile --name tianshang-scribe --hidden-import openpyxl.cell._writer --hidden-import openpyxl.cell.read_only --hidden-import openpyxl.styles --hidden-import openpyxl.chart --hidden-import openpyxl.comments src/tianshang_scribe/cli/main.py
# dist/tianshang-scribe.exe (~35 MB)

Demostración

python -m demo.generate_demos
# demo/demo_word.docx   —LaTeX + math + TOC + watermark
# demo/demo_excel.xlsx  —CSV import + formulas + chart + protection
# demo/demo_ppt.pptx    —slides + notes + transitions + math formulas

Prueba de conformidad de la CLI:

python demo/test_cli.py

Desarrollo

git clone https://github.com/Tianshang301/TianshangScribe.git
cd TianshangScribe
pip install -e ".[dev]"

pytest tests/ -v        # Run tests
ruff check src/tianshang_scribe/ tests/  # Lint
mypy src/tianshang_scribe/               # Type check

Licencia

Apache-2.0

Related MCP Servers

View all related MCP servers

Related MCP Connectors

  • Generate PDF/DOCX/XLSX/PPTX from templates+JSON. Convert Office/HTML/MD to PDF. Universal templating

  • Use your own Word templates to convert Markdown → DOCX/PDF/HTML from any MCP-compatible AI.

  • Markdown in, any format out. PDFs merged, split, watermarked. Runs on our own doc engines.

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Tianshang301/TianshangScribe'

If you have feedback or need assistance with the MCP directory API, please join our Discord server