金融AI助理MCP主机和MCP客户端
概述
金融AI助手MCP Host是一个FastAPI服务,它将聊天风格的请求代理到MCP(模型上下文协议)工具注册表中。它检索一个命名的系统提示符,将对话交给由OpenAI支持的LangChain代理,并返回模型的回复以及在此过程中执行的任何MCP工具调用。
特性
- 用于提交财务分析查询的FastAPI端点。
- LangChain代理(默认为GPT-4o-mini),具有可配置的递归护栏。
- 从远程工具注册表自动发现MCP工具和提示。
- 结构化响应捕获执行工具要求可审计性。
项目结构
src/api/chat.py–FastAPI应用程序和/chat终点。src/host/host.py–LangChain代理编排和MCP集成。src/host/connection_manager.py–MCP服务器的异步连接生命周期。src/config.py–使用配置环境变量pydantic-settings.
先决条件
- Python 3.12以上。
- OpenAI API密钥,可访问所选聊天模型。
- MCP兼容工具注册表的URL,显示所需的提示和工具。
uv依赖性管理(auv.lock包括在内)。
安装
uv sync配置
创建一个 .env 项目根目录中的文件:
OPENAI_API_KEY=sk-your-key
TOOL_REGISTRY_URL=https://your-tool-registry.example.com这两个值都是必需的,如果缺少或为空,启动将失败。
运行API
使用紫外线
uv run uvicorn src.api.chat:app --host 0.0.0.0 --port 5001 --reload直接使用uvicorn
uvicorn src.api.chat:app --host 0.0.0.0 --port 5001 --reload当服务器启动时,它初始化MCP连接,列出发现的工具,并准备接受聊天请求。
API使用
端点
POST /chat
请求体
{
"query": "Hey, I'm researching the company that builds the Model Y but I can't remember its stock symbol. Could you figure out the right ticker, pull a 5-minute intraday snapshot for today, summarize any headline sentiment from the last 24 hours, and grab a short excerpt from the latest 10‑K risk factors (1.A)?"
}响应体
{
"reply": "The company that builds the Model Y is **Tesla, Inc.**, and its stock symbol is **TSLA**....",
"tool_calls": [
{
"name": "alphavantage_search_symbol",
"args": {
"keywords": "Tesla"
},
"result": "..."
},
{
"name": "alphavantage_get_intraday",
"args": {
"symbol": "TSLA",
"interval": "5min"
},
"result": "..."
}
]
}示例
curl -X POST http://localhost:5001/chat \
-H "Content-Type: application/json" \
-d '{"query": "Summarize recent trends in the S&P 500."}'