智能Word文档助手

基于MCP协议的智能Word文档助手,通过自然语言指令创建、编辑和管理文档,支持多Agent协作和三层记忆系统。

  • by ceilf6
  • Python
  • 本地部署
  • 11 星标
  • 更新于
在 GitHub 查看 ceilf6/word-MCP-agent

使用说明

Word MCP Agent

An intelligent Word document assistant based on MCP (Model Context Protocol). Create, edit, and manage Word documents using natural language commands, with the ability toMulti Agent Collaborationandmemory ability.

✨ Core Features

🤖 Multi Agent Pipeline

The document creation adopts three-stage Agent collaboration to ensure high-quality output:

用户请求
    ↓
┌─────────────────────────────────────┐
│ 🔍 结构化 Agent (Structurizer)       │
│ • 解析用户意图                        │
│ • 提取参数(文件名、标题、内容要求)     │
│ • 识别缺失信息,向用户提问              │
└─────────────────────────────────────┘
    ↓
┌─────────────────────────────────────┐
│ ✍️ 创作 Agent (Writer)               │
│ • 根据结构化数据生成内容               │
│ • 调整写作风格                        │
└─────────────────────────────────────┘
    ↓
┌─────────────────────────────────────┐
│ ⭐ 评审 Agent (Reviewer)             │
│ • 评估文档质量 (1-10分)               │
│ • 评分 < 7 → 返回创作Agent重写        │
│ • 最多 3 轮迭代优化                   │
└─────────────────────────────────────┘
    ↓
高质量文档输出

🧠 Three-layer memory system

Memory hierarchy Description Persistence
Short term memory The conversation history of the current session (last 20 rounds) ❌
working memory The context and temporary variables of the current task ❌
long-term memory User preferences, important facts (automatically extracted) ✅ JSON

Features:

  • Automatically extract user preferences (writing style, naming conventions, etc.)
  • Support multi session isolation (through) session_id)
  • Long term memory automatically clears based on importance

📝 Document operation

Function Description
📝 Create Document Generate High Quality Documents through Multi Agent Pipeline
📖 Read Document Extract Document Text and Table Content
✏️ Update Document Add Content, Insert Paragraphs, Replace Text
🗑️ Delete Document Delete the specified document
📋 List Documents View all created documents
📊 Add Table Insert Format Table into Document
🔍 Search Replace Bulk Replace Text in Documents

🌐 外部能力

Function Description
🔎 Google Search Retrieve information and organize it into documents
🖼️ Image Search Search for Related Images
⬇️ Image Download Download images from URL to local
🖼️ Insert Image Insert Image into Document

📁 project structure

word-MCP-agent/
├── backend/                 # 后端服务
│   ├── server.py           # FastAPI 主服务器 (SSE + LLM Agent + 记忆)
│   ├── main.py             # MCP 工具定义
│   ├── agents.py           # 多 Agent 模块 (结构化/创作/评审)
│   ├── memory.py           # 三层记忆系统
│   ├── mcpconfig.json      # 配置文件 (LLM、API Keys)
│   ├── pyproject.toml      # Python 依赖
│   ├── start.sh            # 启动脚本
│   ├── word/               # 生成的文档存放目录
│   └── memory_store/       # 长期记忆持久化目录
│
├── frontend/                # 前端应用
│   ├── index.tsx           # React 主组件
│   ├── __entry.tsx         # React 入口
│   ├── index.html          # HTML 入口
│   ├── vite.config.ts      # Vite 配置
│   ├── tsconfig.json       # TypeScript 配置
│   └── package.json        # Node 依赖
│
└── README.md

🚀 Quick Start

1. Configure the backend

cd backend

# 创建虚拟环境并安装依赖
python3 -m venv venv
source venv/bin/activate
pip install -e .

# 或使用启动脚本 (自动处理环境)
./start.sh

2. Configuration mcpconfig.json

edit backend/mcpconfig.jsonFill in your API key:

{
  "defaultLLM": {
    "baseURL": "https://api.siliconflow.cn/v1",
    "apiToken": "your-api-token",
    "model": "deepseek-ai/DeepSeek-V3"
  },
  "google": "your-serper-api-key"
}
  • LLMSupport any large model compatible with OpenAI
  • Google: Serper.dev API Key (for search function)

3. Start the backend service

cd backend
./start.sh
# 或
source venv/bin/activate && python server.py

After the server is started, it runs on http://localhost:8080

4. Start the front-end

cd frontend
npm install
npm run dev

The front-end development server runs on http://localhost:3000

📡 API endpoint

Core endpoint

Endpoint Method Description
/ GET Server Status
/tools GET Get the list of available tools
/documents GET Get document list
/call POST Directly call the tool
/sse GET SSE connection
/sse/agent POST LLM Agent (SSE streaming, with memory)
/chat POST LLM Agent (non streaming)

Memory management endpoint

Endpoint Method Description
/memory/sessions GET List all sessions
/memory/session/{id} GET Get session information
/memory/session/{id} DELETE Delete session
/memory/session/{id}/clear POST Clear short-term memory
/memory/session/{id}/history GET Retrieve conversation history
/memory/session/{id}/remember POST Add Long Term Memory
/memory/session/{id}/recall GET Search for Long Term Memory

💡 Usage example

Basic document creation

创建一个关于 React 的介绍文档
列出所有文档

Multi Agent Collaboration

When the input is vague, the structured agent will ask for more information:

用户: 帮我写一份文档
助手: 请问文档要叫什么名字?
用户: 年度报告
助手: [创作Agent生成内容] → [评审Agent评分8/10] → 文档创建成功!

Combining search

帮我搜索一下人工智能的最新发展,然后写成一篇文档

insert image

创建一份关于圣诞节的文档并插入一些精美的相关图片

Use memory function

// 前端发送请求时指定 session_id
fetch('/sse/agent', {
  method: 'POST',
  body: JSON.stringify({
    query: "帮我创建一个文档",
    session_id: "user_123"  // 不同用户使用不同 session_id
  })
})

🔧 Available tools

Documentation Tool

Tool Name Description
create_document_with_agents 【 Recommendation 】 Multi Agent Pipeline Creation Document
structurize_input Only structurally parse user input
create_document Create documents directly (without quality checks)
read_document Read document content
update_document Update document
delete_document Delete document
list_documents List all documents
add_table Add Table
search_replace Search for replacement

search tool

Tool Name Description
google_search Google search for text information
google_image_search Google Image Search
download_image Download images locally
insert_image Insert image into document

Memory tools

Tool Name Description
save_to_memory Save to long-term memory
recall_memory Retrieve from long-term memory
get_memory_stats Retrieve memory statistics

🏗️ tech stack

back-end

  • Python 3.10+
  • FastAPI - Web Framework
  • Python docx - Word Document Processing
  • Httpx - HTTP client
  • MCP (Model Context Protocol) - Tool Protocol

Multi Agent System

  • Self developed Agent Pipeline
  • Support AgentScope integration (optional)

Memory system

  • Three layer memory architecture
  • JSON file persistence
  • Automatically clear by importance

front-end

  • React 18
  • TypeScript
  • Vite - Build Tool
  • SSE (Server Sent Events) - Real time communication

AI

  • DeepSeek-V3/Other Large Models
  • Serper.dev (Google Search API)

🔌 Expand development

Add a new agent

In backend/agents.py Inheritance in the Middle BaseAgent:

class MyAgent(BaseAgent):
    def __init__(self):
        super().__init__("MyAgent", "系统提示词")
    
    def process(self, input_data):
        # 处理逻辑
        return result

Add new tool

In backend/server.py of TOOLS and TOOL_HANDLERS Registration in China:

TOOLS["my_tool"] = {
    "description": "工具说明",
    "parameters": {...}
}

def my_tool_handler(**kwargs):
    return {"success": True, "result": ...}

TOOL_HANDLERS["my_tool"] = my_tool_handler

Custom Memory Retrieval

In backend/memory.py of Session._extract_to_long_term Add rules in:

def _extract_to_long_term(self, role: str, content: str):
    if "我喜欢" in content:
        self.long_term.add(
            f"用户偏好: {content}",
            category="preference",
            importance=0.8
        )

📊 system architecture

┌─────────────────────────────────────────────────────────────────┐
│                         前端 (React)                             │
│                    http://localhost:3000                        │
└────────────────────────────┬────────────────────────────────────┘
                             │ SSE / HTTP
                             ▼
┌─────────────────────────────────────────────────────────────────┐
│                    FastAPI Server                               │
│                    http://localhost:8080                        │
├─────────────────────────────────────────────────────────────────┤
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐           │
│  │   LLM 调用    │  │  工具执行器   │  │  SSE 流      │            │
│  └──────┬───────┘  └──────┬───────┘  └──────────────┘           │
│         │                 │                                     │
│  ┌──────▼─────────────────▼──────┐                              │
│  │        多 Agent Pipeline       │                             │
│  │  ┌────────┐ ┌────────┐ ┌────────┐                            │
│  │  │结构化   │→│创作     │→│评审    │                            │
│  │  │Agent   │ │Agent   │ │Agent   │                            │
│  │  └────────┘ └────────┘ └────────┘                            │
│  └───────────────────────────────┘                              │
│                                                                 │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │                    记忆系统                              │    │
│  │  ┌──────────┐  ┌──────────┐  ┌──────────────────────┐   │    │
│  │  │短期记忆   │  │工作记忆    │  │长期记忆 (JSON持久化)│  │  │     │
│  │  └──────────┘  └──────────┘  └──────────────────────┘   │    │
│  └─────────────────────────────────────────────────────────┘    │
│                                                                 │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │                    工具集                                │    │
│  │  文档操作 │ 搜索功能 │ 图片处理 │ 记忆操作                   │    │
│  └─────────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────────┘
                             │
                             ▼
              ┌──────────────────────────┐
              │   外部服务                │
              │  • LLM API               │
              │  • Serper.dev (搜索)      │
              └──────────────────────────┘

📝 Changelog

v2.0.0

  • ✨ Add multi-agent pipeline (structured/creative/review)
  • ✨ Add a three-layer memory system
  • ✨ Add Memory Management API
  • 🔧 Optimize the quality of document creation

v1.0.0

  • 🎉 初始版本
  • 📝 Basic document operations
  • 🌐 Google Search Integration
  • 🖼️ Image search and insertion

License

MIT