Initial commit: chat-v3 with 1 tools - src/server/mcp_server.py

This commit is contained in:
2026-01-30 13:59:49 +00:00
parent cb8e6a38ac
commit eabc82b843
+132
View File
@@ -0,0 +1,132 @@
"""
MCP 服务器 - chat-v3-c4b7df
Agent with 1 external tools
使用 Pydantic AI 和 FastMCP 框架。
自动生成时间: 2026-01-30T13:59:46.787948
"""
import json
import os
from typing import Optional
from mcp.server.fastmcp import FastMCP
from pydantic_ai import Agent
# ==================== 配置 ====================
# LiteLLM Gateway 配置
_BASE_URL = os.getenv('OPENAI_BASE_URL',
os.getenv('LLM_BASE_URL', 'https://litellm.graystone-fb459c5d.southeastasia.azurecontainerapps.io/v1'))
_API_KEY = os.getenv('OPENAI_API_KEY', 'sk')
os.environ.setdefault('OPENAI_API_KEY', _API_KEY)
os.environ.setdefault('OPENAI_BASE_URL', _BASE_URL)
# 模型名称(pydantic_ai 需要 openai: 前缀)
def _get_model_name() -> str:
model = os.getenv('MODEL_NAME', os.getenv('LITELLM_MODEL', 'taiji/gpt-4o-mini'))
return model if ':' in model else f'openai:{model}'
MODEL_NAME = _get_model_name()
# ==================== MCP 服务器 ====================
server = FastMCP('chat-v3-c4b7df')
# 系统提示词
SYSTEM_PROMPT = """你是 chat-v3-c4b7df,一个专业的 AI 智能助手。
## 角色定位
Agent with 1 external tools
## 可用工具
- info-tool: 获取信息
## 工作原则
1. 理解用户意图:仔细分析用户的请求,确保准确理解需求
2. 选择合适工具:根据需求选择最合适的工具来完成任务
3. 清晰反馈:以用户友好的方式呈现结果
4. 错误处理:遇到问题时提供有用的错误信息和建议
## 响应格式
- 对于数据查询:返回结构化的 JSON 数据
- 对于操作请求:返回操作状态和结果
- 始终使用中文与用户交流(除非用户使用其他语言)"""
def get_agent() -> Agent:
"""创建 Agent 实例(每次调用使用最新的 API Key)"""
return Agent(MODEL_NAME, system_prompt=SYSTEM_PROMPT)
# ==================== MCP 工具定义 ====================
@server.tool()
async def info_tool(query: Optional[str] = None) -> str:
"""
获取信息
Args:
query:
Returns:
API 响应结果 (JSON 格式)
"""
import httpx
url = "https://httpbin.org/get"
headers = {}
params = {"query": query}
try:
async with httpx.AsyncClient(timeout=30) as client:
response = await client.request(
method="GET",
url=url,
headers=headers,
params={k: v for k, v in params.items() if v is not None}
)
if response.status_code == 200:
return json.dumps({
"success": True,
"data": response.json() if response.headers.get("content-type", "").startswith("application/json") else response.text
}, ensure_ascii=False, indent=2)
else:
return json.dumps({
"success": False,
"status_code": response.status_code,
"error": response.text[:500]
}, ensure_ascii=False)
except Exception as e:
# 使用 AI Agent 作为后备
result = await get_agent().run(f"请帮我处理这个请求: ['query: Optional[str] = None']")
return json.dumps({
"success": True,
"source": "ai_agent",
"result": result.output
}, ensure_ascii=False, indent=2)
# ==================== 工具映射(供 API 使用)====================
TOOL_MAP = {
'info_tool': info_tool,
}
TOOL_LIST = [
{
"name": "info_tool",
"description": "获取信息",
"inputSchema": {
"type": "object",
"properties": {"query": {"type": "string", "description": ""}},
"required": []
}
},
]
if __name__ == '__main__':
server.run()