124 lines
3.2 KiB
Python
124 lines
3.2 KiB
Python
"""
|
|
MCP 服务器 - Facebook 搜索 Agent
|
|
使用 FastMCP 提供 Facebook 搜索功能
|
|
"""
|
|
import json
|
|
import os
|
|
from typing import Optional
|
|
from loguru import logger
|
|
|
|
from mcp.server.fastmcp import FastMCP
|
|
|
|
# 支持相对导入和绝对导入
|
|
try:
|
|
from .config import Config
|
|
from .agent import FacebookAgent
|
|
from .models.schemas import SearchRequest
|
|
except ImportError:
|
|
from config import Config
|
|
from agent import FacebookAgent
|
|
from models.schemas import SearchRequest
|
|
|
|
# 创建 MCP 服务器
|
|
server = FastMCP('Facebook搜索Agent')
|
|
|
|
# 全局变量
|
|
agent: Optional[FacebookAgent] = None
|
|
|
|
|
|
def initialize_agent():
|
|
"""初始化 Agent"""
|
|
global agent
|
|
if agent is None:
|
|
try:
|
|
# 加载配置
|
|
config = Config.from_env()
|
|
config.validate()
|
|
|
|
# 创建Agent
|
|
agent = FacebookAgent(config)
|
|
|
|
logger.info("=" * 60)
|
|
logger.info("Facebook搜索Agent初始化完成")
|
|
logger.info("=" * 60)
|
|
logger.info(f"LiteLLM Gateway: {config.litellm_gateway_url}")
|
|
logger.info(f"模型: {config.litellm_model}")
|
|
logger.info(f"Facebook API Host: {config.facebook_api_host}")
|
|
|
|
except Exception as e:
|
|
logger.error(f"Agent初始化失败: {e}")
|
|
raise
|
|
|
|
|
|
@server.tool()
|
|
async def search_facebook(
|
|
query: str,
|
|
limit: int = 5
|
|
) -> str:
|
|
"""
|
|
搜索Facebook内容,返回相关帖子和AI生成的总结
|
|
|
|
Args:
|
|
query: 搜索关键词,例如:technology news、travel tips、food recipes等
|
|
limit: 返回结果数量,默认5,最大20
|
|
|
|
Returns:
|
|
搜索结果和AI生成的总结(JSON格式)
|
|
"""
|
|
global agent
|
|
|
|
# 确保Agent已初始化
|
|
if agent is None:
|
|
initialize_agent()
|
|
|
|
try:
|
|
if not query:
|
|
return json.dumps({
|
|
"success": False,
|
|
"error": "搜索关键词不能为空"
|
|
}, ensure_ascii=False)
|
|
|
|
# 限制结果数量
|
|
limit = max(1, min(limit, 20))
|
|
|
|
# 执行搜索
|
|
request = SearchRequest(query=query, limit=limit)
|
|
response = await agent.search(request)
|
|
|
|
# 构造返回结果
|
|
result = {
|
|
"success": response.success,
|
|
"query": response.query,
|
|
"total_count": response.total_count,
|
|
"results": [
|
|
{
|
|
"title": r.title,
|
|
"url": r.url,
|
|
"snippet": r.snippet,
|
|
"author": r.author,
|
|
"likes": r.likes
|
|
}
|
|
for r in response.results
|
|
],
|
|
"summary": response.summary,
|
|
"message": response.message
|
|
}
|
|
|
|
return json.dumps(result, ensure_ascii=False, indent=2)
|
|
|
|
except Exception as e:
|
|
logger.error(f"搜索处理失败: {e}")
|
|
return json.dumps({
|
|
"success": False,
|
|
"error": str(e)
|
|
}, ensure_ascii=False)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
# 初始化Agent
|
|
initialize_agent()
|
|
|
|
# 运行服务器
|
|
server.run()
|
|
|