Files
mcp-example/macOS/word_opt.py
2025-08-15 19:50:11 +08:00

40 lines
1.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from mcp.server.fastmcp import FastMCP
import os
import docx
from docx.oxml.ns import qn
mcp = FastMCP("word")
@mcp.tool()
async def create_word_doc(filename: str, content: str, filepath: str) -> str:
"""在macOS下创建一个Word文档。
Args:
filename: 文件名(如 example.docx
content: 文档正文内容
filepath: 文件保存路径(若用户未提供则默认为"~/Desktop")
"""
if docx is None:
return "python-docx 未安装,请先运行 pip install python-docx"
try:
doc = docx.Document()
para = doc.add_paragraph(content)
run = para.runs[0] if para.runs else para.add_run(content)
font = run.font
font.name = "宋体"
# 设置中英文字体
r = run._element
r.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
r.rPr.rFonts.set(qn('w:ascii'), 'Times New Roman')
r.rPr.rFonts.set(qn('w:hAnsi'), 'Times New Roman')
save_path = os.path.expanduser(os.path.join(filepath, filename))
doc.save(save_path)
return f"Word文档已在指定路径创建创建路径为: {save_path}"
except Exception as e:
return f"创建Word文档失败: {e}"
if __name__ == "__main__":
mcp.run(transport='stdio')