feat: 增强 Agent 系统和完善项目结构

主要改进:
- Agent 增强: 订单查询、售后支持、客服路由等功能优化
- 新增语言检测和 Token 管理模块
- 改进 Chatwoot webhook 处理和用户标识
- MCP 服务器增强: 订单 MCP 和 Strapi MCP 功能扩展
- 新增商城客户端、知识库、缓存和同步模块
- 添加多语言提示词系统 (YAML)
- 完善项目结构: 整理文档、脚本和测试文件
- 新增调试和测试工具脚本

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
wangliang
2026-01-16 16:28:47 +08:00
parent 0e59f3067e
commit e093995368
48 changed files with 5263 additions and 395 deletions

View File

@@ -3,7 +3,9 @@ Strapi MCP Server - FAQ and Knowledge Base
"""
import sys
import os
import asyncio
from typing import Optional
from datetime import datetime
# Add shared module to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@@ -13,6 +15,7 @@ from pydantic_settings import BaseSettings
from fastapi import Request
from starlette.responses import JSONResponse
import uvicorn
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from pydantic import ConfigDict
@@ -23,7 +26,9 @@ class Settings(BaseSettings):
strapi_api_url: str
strapi_api_token: str
log_level: str = "INFO"
sync_interval_minutes: int = 60 # Sync every 60 minutes
sync_on_startup: bool = True # Run initial sync on startup
model_config = ConfigDict(env_file=".env")
@@ -196,6 +201,55 @@ async def health_check() -> dict:
}
# ============ Sync Scheduler ============
scheduler = AsyncIOScheduler()
async def run_scheduled_sync():
"""Run scheduled sync from Strapi to local knowledge base"""
try:
from sync import StrapiSyncer
from knowledge_base import get_kb
kb = get_kb()
syncer = StrapiSyncer(kb)
print(f"[{datetime.now()}] Starting scheduled sync...")
result = await syncer.sync_all()
if result["success"]:
print(f"[{datetime.now()}] Sync completed successfully")
else:
print(f"[{datetime.now()}] Sync failed: {result.get('error', 'Unknown error')}")
except Exception as e:
print(f"[{datetime.now()}] Sync error: {e}")
async def run_initial_sync():
"""Run initial sync on startup if enabled"""
if settings.sync_on_startup:
print("Running initial sync on startup...")
await run_scheduled_sync()
print("Initial sync completed")
def start_scheduler():
"""Start the background sync scheduler"""
if settings.sync_interval_minutes > 0:
scheduler.add_job(
run_scheduled_sync,
'interval',
minutes=settings.sync_interval_minutes,
id='strapi_sync',
replace_existing=True
)
scheduler.start()
print(f"Sync scheduler started (interval: {settings.sync_interval_minutes} minutes)")
else:
print("Sync scheduler disabled (interval set to 0)")
if __name__ == "__main__":
# Create FastAPI app from MCP
@@ -252,9 +306,23 @@ if __name__ == "__main__":
# Add routes using the correct method
from fastapi import FastAPI
from contextlib import asynccontextmanager
# Lifespan context manager for startup/shutdown events
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup: start scheduler and run initial sync
start_scheduler()
if settings.sync_on_startup:
print("Running initial sync on startup...")
await run_scheduled_sync()
print("Initial sync completed")
yield
# Shutdown: stop scheduler
scheduler.shutdown()
# Create a wrapper FastAPI app with custom routes first
app = FastAPI()
app = FastAPI(lifespan=lifespan)
# Add custom routes BEFORE mounting mcp_app
app.add_route("/health", health_check, methods=["GET"])