MCP聊天API
基于FastAPI的聊天API,具有组织良好、可扩展的结构。
项目结构
app/
├── __init__.py # Package initialization
├── main.py # FastAPI application entry point
├── api/ # API layer
│ ├── __init__.py
│ ├── dependencies.py # Dependency injection
│ └── routes/ # API route handlers
│ ├── __init__.py # Route aggregation
│ └── chat.py # Chat endpoints
├── core/ # Core configuration
│ ├── __init__.py
│ └── config.py # Application settings
├── db/ # Database configuration
│ └── __init__.py
├── models/ # Database models (ORM)
│ └── __init__.py
├── schemas/ # Pydantic schemas
│ ├── __init__.py
│ └── chat.py # Chat-related schemas
├── services/ # Business logic
│ ├── __init__.py
│ └── chat_service.py # Chat service implementation
├── middleware/ # Custom middleware
│ └── __init__.py
└── utils/ # Utility functions
├── __init__.py
└── logger.py # Logging configuration入门指南
安装
- 安装依赖项:
pip install -r requirements.txt- 创建一个
.env文件(可选):
# Copy from example if it exists, or create manually
APP_NAME=MCP Chat API
DEBUG=False
ALLOWED_ORIGINS=http://localhost:5173运行应用程序
自动重新加载的开发模式:
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000生产方式:
uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4API文档
运行后,访问:
- Swagger用户界面: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
- OpenAPI JSON: http://localhost:8000/openapi.json
API终点
健康检查
GET /health-健康检查端点
聊天端点(v1)
POST /api/v1/chat/-发送聊天消息POST /api/v1/chat/sessions-创建新的聊天会话GET /api/v1/chat/sessions-列出所有会话GET /api/v1/chat/sessions/{session_id}-获取特定会话DELETE /api/v1/chat/sessions/{session_id}-删除会话GET /api/v1/chat/sessions/{session_id}/messages-获取会话消息
发展
建筑
该应用程序遵循分层架构:
- API层 (
app/api/):HTTP端点和请求/响应处理 - 服务层 (
app/services/):业务逻辑和编排 - 数据层 (
app/models/,app/db/):数据模型和数据库访问 - 架构层 (
app/schemas/):使用Pydantic进行请求/响应验证
添加新端点
- 在中创建架构
app/schemas/ - 在中添加业务逻辑
app/services/ - 在中创建路由处理程序
app/api/routes/ - 在中注册路由器
app/api/routes/__init__.py
配置
应用程序设置通过以下方式管理 app/core/config.py 使用 pydantic-settings. 可以通过环境变量或 .env 文件。
数据库集成
要添加数据库支持,请执行以下操作:
- 取消注释中的数据库设置
app/core/config.py - 在中添加SQLAlchemy模型
app/models/ - 在中配置数据库连接
app/db/__init__.py - 更新服务以使用数据库而不是内存存储
测试
使用pytest运行测试:
pytest在中创建测试 tests/ 目录遵循与相同的结构 app/.
后续步骤
- \[\]与实际的AI/MCP后端集成
- \[\]添加身份验证和授权
- \[\]实现数据库持久化
- \[\]添加速率限制
- \[\]设置日志记录和监控
- \[\]添加综合测试
- \[\]配置部署(Docker等)
许可证
\[您的许可证在这里\]
