import os
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("file-write")

@mcp.tool()
def write_file(path: str, content: str, mode: str = "w", encoding: str = "utf-8") -> str:
    """将文本内容写入指定路径的文件。
    mode 可选: 'w' (覆盖写入), 'a' (追加写入)
    """
    if mode not in ('w', 'a'):
        return "写入模式只能是 'w' 或 'a'"
        
    try:
        # 确保目录存在
        os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
        
        with open(path, mode, encoding=encoding) as f:
            f.write(content)
        return f"成功写入 {len(content)} 字符到: {path}"
    except Exception as e:
        return f"写入失败: {e}"

def main():
    mcp.run()

if __name__ == "__main__":
    main()
