一、项目背景
本文分享一个基于 FastMCP
框架实现的文档处理服务,可实现 Word 文档(.docx)与 JSON 数据格式的双向转换。通过此服务,开发者可以轻松实现文档内容提取、结构化数据填充、样式模板复用等功能,适用于自动化报告生成、数据导入导出等场景。
二、核心代码解析
1. 服务端实现(my_server.py
)
import json
from fastmcp import FastMCP
from wan_neng_copy_word import clone_document as word_to_dict
from wan_neng_copy_word_pro import clone_document
from wan_neng_copy_word import clone_document as get_para_style
from gen_all_styles import gen_all_styles
mcp = FastMCP(name="MyServer")
# 基础问候工具
@mcp.tool
def greet(name: str) -> str:
"""Greet a user by name."""
return f"Hello, {name}!"
# Word 转 JSON 工具
@mcp.tool
def word_to_json(word_path: str) -> str:
"""Convert a word document to json."""
body_s, body_p = word_to_dict(word_path)
return json.dumps(body_p)
# JSON 转 Word 工具
@mcp.tool
def json_to_word(word_path: str, json_data: str) -> str:
"""Convert a json to word document."""
try:
body_ws, _ = get_para_style('demo_template.docx')
except:
gen_all_styles()
body_ws, _ = get_para_style('demo_template.docx')
body_s, _ = get_para_style(word_path)
clone_document(body_s, json.loads(json_data), body_ws, 'cloned_example.docx')
return 'cloned_example.docx'
# 启动 MCP 服务
if __name__ == "__main__":
mcp.run(transport="streamable-http", host="127.0.0.1", port=9000)
关键组件说明:
- FastMCP:基于 MCP 协议的服务框架,提供工具注册与调用能力
- wan_neng_copy_word 系列模块:实现 Word 文档解析与生成的核心逻辑
- gen_all_styles:样式模板生成工具
- 双向转换逻辑:
word_to_json
:提取文档内容结构并序列化为 JSONjson_to_word
:应用模板样式生成新文档
2. 客户端测试代码
import asyncio
from fastmcp import Client
# MCP 服务配置
config = {
"mcpServers": {
"document-service": {
"url": "http://127.0.0.1:9000/mcp",
"transport": "streamable-http"
}
}
}
# 创建客户端实例
client = Client(config)
async def main():
async with client:
# 读取 JSON 数据
with open("1.json", "r", encoding="utf-8") as f:
body_p = f.read()
# 调用 JSON 转 Word 工具
result = await client.call_tool(
"json_to_word",
{"word_path": "1.docx", "json_data": body_p}
)
print(f"生成文档路径: {result}")
if __name__ == "__main__":
asyncio.run(main())
三、运行环境要求
- Python 3.8+ 环境
- 依赖库安装:
pip install fastmcp python-docx
- 文件依赖:
demo_template.docx
(样式模板)1.docx
(输入文档)1.json
(结构化数据)
四、功能演示流程
- 启动服务:
python my_server.py
- 执行客户端测试:
python client_test.py
- 输出结果:
- 生成
cloned_example.docx
文档 - 验证文档内容与原始模板样式的一致性
- 生成
五、应用场景
- 自动化报告生成:通过 API 动态填充数据到预设模板
- 文档结构分析:提取 Word 内容进行 NLP 处理
- 跨格式转换:作为其他格式(如 Markdown、HTML)转换的中间层
- 样式统一管理:基于模板批量生成标准化文档
六、注意事项
- 文件路径问题:确保工作目录包含所需模板文件
- 异常处理增强建议:
# 可扩展的异常处理示例 try: # 文件操作代码 except FileNotFoundError as e: return {"error": f"Missing file: {str(e)}"} except json.JSONDecodeError: return {"error": "Invalid JSON input"}
- 性能优化方向:
- 添加缓存机制复用样式模板
- 支持异步文件读写
- 实现流式传输处理大文件
七、扩展建议
- 添加文件校验模块:
def validate_word_file(path): if not os.path.exists(path): raise ValueError("Template file not found") if not path.endswith('.docx'): raise ValueError("Invalid file format")
- 支持更多格式转换:
- 集成
pandoc
实现多格式转换 - 添加 PDF 导出功能
- 集成
- API 接口增强:
- 添加文件上传下载接口
- 实现任务队列异步处理
该实现展示了如何通过 MCP 协议构建文档处理服务,开发者可根据实际需求扩展更多文档操作功能。完整项目代码需注意分离服务端/客户端模块,并完善错误处理机制。