一、項目背景
本文分享一個基于 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_stylesmcp = 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 協議構建文檔處理服務,開發者可根據實際需求擴展更多文檔操作功能。完整項目代碼需注意分離服務端/客戶端模塊,并完善錯誤處理機制。