Skip to main content
Glama

TianshangScribe

中文版

PyPI CI License TianshangScribe MCP server

面向开发者、CLI 自动化和 AI 代理的跨平台 Office 文档处理工具。可创建、编辑、模板填充和转换 Word(.docx)、Excel(.xlsx)和 PowerPoint(.pptx)文档,支持 LaTeX 风格标记、原生 OMML 数学公式以及模板引擎({{placeholders}}、{{#each}} 循环、{{#if}} 条件)。附带一个 MCP 服务器,提供 7 个工具(create、edit、fill template、convert、extract、validate、compare),支持 stdio、SSE 和 Streamable HTTP 传输,并带有 bearer-token 认证和速率限制。

警告:API 不稳定——可能发生破坏性变更

本项目处于 1.0 之前(0.x)阶段。CLI 选项、MCP 工具签名、模板语法和输出格式尚未冻结,可能随时变更,恕不另行通知。 兼容性承诺:任何破坏性变更将至少提前一个版本在 CHANGELOG 中公布,并附有迁移指南。 生产环境使用时,请锁定特定版本,并在升级前查看 CHANGELOG。

安装

pip install tianshang-scribe

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

Linux 部署

Docker(推荐用于通过 Streamable HTTP 运行 MCP 服务器):

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)

.deb 包(Debian / Ubuntu):

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

pipx(隔离的 CLI):

pipx install tianshang-scribe
tianshang-scribe --help

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

Related MCP server: docx-forge-mcp

快速开始

# 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

全局选项

参数

说明

input_file

输入文档路径(使用 --create 时省略)

-w --word

处理 Word 文档

-e --excel

处理 Excel 工作簿

-p --ppt

处理 PowerPoint 演示文稿

-o --output

输出文件路径

--force

允许覆盖已有文件

--topdf

输出为 PDF

--stdin

从标准输入读取

--stdout

写入标准输出

当省略 -w/-e/-p 时,将根据输入文件的扩展名推断文档类型。

操作

选项

说明

示例

-cr --create

创建空白文档

--create -w

-a --add

添加文本

-a "Hello"

--column

--add 的目标列

--column 2

-r --replace

查找并替换

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

-d --delete

删除内容

-d "keyword"

-cl --clear

清除内容 / 格式 / 链接

--clear formats

-m --modify

修改内容

-m "old" --modify-new "new"

-s --style

设置样式

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

-t --template

模板填充

-t data.json

-x --extract

提取数据(math/latex 等)

-x latex

--meta

设置属性

--meta "title=Report,author=John"

--latex-style

启用 LaTeX 解析

--math

添加数学公式(Word)

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

--math-style

数学解析方言(office/mathtype)

--math-style mathtype

--math-font

OMML 数学字体(默认 Cambria Math)

--math-font "Times New Roman"

--math-mtef

以 MathType OLE 对象(MTEF)嵌入

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

--heading

添加标题(Word)

--heading "level:1 text:Intro"

--regex

正则表达式模式

--replace --delete 一起使用

--merge

合并文件

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

--split

拆分文档(仅 Excel:--split by-sheet

--split by-sheet

--comment

添加批注(Word)/ 演讲者备注(PPT)

--comment "2 Note text"

--add-table

添加表格(Word)

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

--chart-add

添加图表(Excel)

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

--batch

批处理模式

--batch

--files

批处理的 glob 模式

--files "reports/*.docx"

--schedule-db

计划任务 SQLite 数据库路径

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

--schedule-add

注册计划任务

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

--schedule-rm

移除计划任务

--schedule-rm daily

--schedule-list

列出计划任务

--schedule-list

--schedule-run

立即运行计划任务

--schedule-run daily

--schedule-run-all

运行到期的计划任务

--schedule-run-all

--run-script

在沙箱中运行脚本

--run-script build.py

--stdin

从标准输入读取

--stdout

写入标准输出

Word 专用选项

选项

说明

示例

--heading

添加标题

--heading "level:1 text:Intro"

--math

添加数学公式

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

--latex-style

启用 LaTeX 标记

--toc

生成目录

--toc

--section-break

插入分节符

--section-break

--header

设置页眉

--header "Chapter 1"

--footer

设置页脚

--footer "Page X"

--watermark

文字水印

--watermark "DRAFT"

--tomd

转换为 Markdown

--tomd

--tohtml

转换为 HTML

--tohtml

Excel 专用选项

选项

说明

示例

--sheet-add

添加工作表

--sheet-add "Q1"

--sheet-delete

删除工作表

--sheet-delete "Sheet2"

--sheet-rename

重命名工作表

--sheet-rename "Old New"

--column-width

设置列宽

--column-width "2=20"

--row-height

设置行高

--row-height "3=30"

--formula

设置单元格公式

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

--from-csv

导入 CSV 数据

--from-csv data.csv

--sort

排序区域

--sort "A1:A10 asc"

--chart-add

添加图表

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

--protect

设置密码

--protect "p@ss"

--unprotect

移除密码

--unprotect

--to-csv

导出为 CSV

--to-json

导出为 JSON

--to-html

导出为 HTML

LaTeX 风格标记

--add 内容中嵌入以下标记。使用 --latex-style 启用。支持嵌套。

语法

效果

\bfseries{text}

粗体

\itshape{text}

斜体

\scshape{text}

小型大写字母

\underline{text}

下划线

\rmfamily{text}

罗马体(衬线)

\sffamily{text}

无衬线体

\ttfamily{text}

等宽体

\fontfamily{Arial}{text}

指定字体

\fontsize{18}{text}

字号(磅)

\color{FF0000}{text}

颜色(十六进制)

\centering{...}

居中对齐 *

\raggedright{...}

左对齐 *

\raggedleft{...}

右对齐 *

\linespread{1.5}{...}

行距 *

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

缩进 *

\heading{2}{Title}

插入标题

\newpage

分页

\includegraphics{path}

插入图片

* 段落级格式(创建新段落)。

字体配置

命令

效果

\setmainfont{Name}

默认西文字体

\setCJKmainfont{Name}

默认中文字体

\setsansfont{Name}

无衬线字体

\setCJKsansfont{Name}

中文无衬线字体

\setmonofont{Name}

等宽字体

\setCJKmonofont{Name}

中文等宽字体

Word OOXML 原生区分 w:ascii(西文)和 w:eastAsia(中文)字体,可在混合文字中自动切换字体。

数学公式

LaTeX 数学公式可通过 --math 转换为原生 Word OMML(Office Math Markup Language)格式。该转换器是一个手写的递归下降解析器(expression → term → factor → atom),作用于嵌套的不可变令牌树(fraction、root、N-ary、sub/sup、accent、styled、delimiter 令牌),并通过一张 O(1) 命令表进行分派,该命令表包含预编译的正则表达式和零拷贝参数切片。使用 --math-font "Times New Roman" 可将公式渲染为 MathType 风格的衬线字体,而不是 Word 默认的 Cambria Math(<m:mathPr><m:mathFont>)。--math-style mathtype 可切换 LaTeX 解析方言以获得 MathType 兼容。使用 --math-mtef 可将公式作为真正的 MathType OLE 对象(MTEF 二进制格式)嵌入——这可由旧版 MathType(6.x 及更早版本)编辑,也与 --extract math 读取回的格式相同。输出在所有版本之间保持字节级稳定(受 golden-snapshot 回归测试套件保护)。

支持语法

分类

命令

分数

\frac{num}{den}

根式

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

上标/下标

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

求和/积分

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

极限

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

具名函数

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

希腊字母

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

符号

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

关系

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

箭头

\to \rightarrow \leftarrow \mapsto \uparrow

重音

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

括号

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

数学字体

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

数学排版

遵循主流数学期刊标准(AMS、Elsevier、Springer):

内容

样式

示例

单字母变量

斜体

a b x y

数字

正体

0 1 2

具名函数

正体

\sin \cos \log

小写希腊字母

斜体

\alpha \beta \gamma

大写希腊字母

正体

\Gamma \Delta \Theta

自动识别

--add 文本中的命令即使没有 $...$ 包裹也会自动识别为数学公式:

  • 带参数:\frac \sqrt \sum \int \prod \lim

  • 重音:\hat{x} \bar{x} \vec{x}

  • 一元运算符:\sin \cos \tan \log \ln

  • 纯文本中的 H_{2}Om^{2} 会变成 Unicode 下标/上标(H₂O / m²)

样式语法

--style 使用逗号分隔的键值对:

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

别名

说明

font

font_name, font-family

字体名

西文字体

cjk-font

cjk_font_name, cjk-font-family

字体名

CJK 字体

size

font_size, font-size

pt

字号

bold

flag

粗体

italic

flag

斜体

underline

flag

下划线

color

font_color, font-color

FF0000

十六进制颜色

align

alignment

left/center/right/justify

对齐方式

布尔键(bold italic underline)只要存在即为 True

模板填充

支持 JSON、CSV 和 YAML 数据源。替换文档中的 {{placeholder}}。嵌套对象可用点号表示法展开。循环可迭代列表值。条件语句可显示/隐藏块。

{
  "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}}

Excel 功能

功能名称

CLI 选项

工作表管理

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

列/行调整

--column-width --row-height

公式

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

数据导入

--from-csv

数据导出

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

排序

--sort "A1:A10 asc"

图表

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

保护

--protect --unprotect

PPT 功能

功能名称

说明

幻灯片管理

添加、删除、重新排列幻灯片(--slide-add--slide-delete--slide-move

版式

按名称或索引应用幻灯片版式(--layout

演讲者备注

添加演示者备注(--notes

数学公式

$...$ / $$...$$ 渲染为原生 OMML

切换效果

设置幻灯片切换效果——淡入、推入、擦除等(--transition

导出

将幻灯片保存为图片(--toimg)或转为 PDF(--topdf

媒体压缩

压缩图片(--compress-media "1920,80"

保护

设置/移除密码(--protect--unprotect

退出码

代码

含义

0

成功

1

一般错误

2

参数错误

3

未实现

MCP 服务器

天匠Scribe 包含 MCP(Model Context Protocol)服务器——AI 智能体可以创建、编辑、填充模板、转换,以及从 Office 文档中提取数据。

Quick Connect

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"
}}}

Tools (7)

Tool

Description

create_office_document

使用结构化内容块创建 .docx / .xlsx / .pptx

edit_office_document

对现有文档执行替换、删除、修改、样式和添加操作

fill_template

用数据填充 {{placeholders}};支持 {{#each}} / {{#if}}

convert_document

在格式之间转换(docx↔pdf/md/html,xlsx↔csv/json)

extract_document_data

提取元数据、全文或文档结构

validate_template

在填充前预检模板占位符与数据是否匹配

compare_documents

比较两个 .docx 文件的段落级差异

Capabilities

Feature

Detail

协议

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

资源

resources/list + resources/read — 文档以可读 URI 暴露

提示词

5 个内置工作流模板(prompts/list + prompts/get

进度

在 PDF 转换和长操作期间发送 notifications/progress 通知

响应

多类型 content[]:文本消息 + 资源(文件 URI、MIME 类型、大小)

模式

所有参数均支持 enumdefaultexamplesminimum/maximum 约束

生产环境(仅 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"

端点GET /health · GET /sse · POST /message?session_id=X

完整文档: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

架构

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

技术栈

组件

技术

CLI

Typer + Rich

Word

python-docx

Excel

openpyxl

PPT

python-pptx

数学

手写递归下降解析器 → OMML XML(不可变令牌树、命令分派表)

模板

自定义引擎({{placeholder}}, {{#each}}, {{#if}})

PDF

office2pdf(约 2MB Rust 二进制,零依赖)+ LibreOffice 后备方案

质量

pytest(936 项测试)· ruff · mypy

构建 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)

演示

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

CLI 合规性测试:

python demo/test_cli.py

开发

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

许可证

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