时间序列API-统一的REST和MCP服务器
全面的时间序列数据API,支持传统的REST端点和模型上下文协议(MCP)服务器功能。这种统一的实现提供了高级分析、预测和异常检测功能,并具有生产就绪功能。
特性
核心功能
- 双协议支持:统一应用程序中的REST API和MCP服务器
- 时间序列数据:使用灵活的参数查询、聚合和分析时间序列数据
- 高级分析:统计异常检测、趋势预测和数据聚合
- 示例数据生成:用于测试和开发的内置合成数据生成器
- 交互式文档:用于REST API探索的Swagger UI和ReDoc
第4阶段增强功能
- 统一入口点:单个应用程序仅支持REST、MCP或混合模式
- 配置管理:具有环境变量覆盖的YAML/JSON配置
- 结构化日志记录:带有性能指标的JSON和文本日志
- 集成测试:全面的端到端测试套件
- 健康监测:性能指标和健康检查端点
- 优雅关闭:正确的信号处理和资源清理
快速开始
安装
- 克隆和设置环境:
git clone
cd ts_api
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt运行应用程序
选项1:统一入口点(推荐)
# REST API only
python app.py --mode rest
# MCP server only
python app.py --mode mcp
# Both REST and MCP (hybrid mode)
python app.py --mode hybrid
# With custom configuration
python app.py --config config.yaml --mode hybrid选项2:传统入口点
# REST API (legacy)
python main.py
# MCP server (legacy)
python mcp_server.py测试设置
- REST API:参观
http://localhost:8000/docs用于交互式文档 - 健康检查:
curl http://localhost:8000/health - 示例查询:
curl "http://localhost:8000/timeseries?metric=cpu_usage&limit=10"
配置
配置文件
创建一个 config.yaml 自定义设置文件:
mode: hybrid # rest, mcp, or hybrid
debug: false
environment: production # development, staging, production
logging:
level: INFO # DEBUG, INFO, WARNING, ERROR, CRITICAL
json_format: false # Enable JSON structured logging
file_path: logs/ts_api.log # Log file path (optional)
console_output: true # Enable console logging
rest:
host: 0.0.0.0
port: 8000
workers: 1 # Number of worker processes
mcp:
server_name: timeseries-server
transport: stdio # stdio or http
http_port: 8001 # HTTP transport port (if enabled)
data:
default_limit: 100 # Default query result limit
max_limit: 10000 # Maximum allowed limit
cache_enabled: true # Enable data caching
cache_ttl: 300 # Cache TTL in seconds
performance:
enable_metrics: true # Enable performance monitoring
slow_query_threshold: 1.0 # Slow query threshold in seconds
max_concurrent_requests: 100 # Maximum concurrent requests环境变量
用环境变量覆盖配置:
export TS_API_MODE=hybrid
export TS_API_REST_PORT=8080
export TS_API_LOG_LEVEL=DEBUG
export TS_API_LOG_JSON=true
export TS_API_CACHE_ENABLED=false命令行选项
python app.py --help
usage: app.py [-h] [--mode {rest,mcp,hybrid}] [--config CONFIG]
[--create-config FILE] [--host HOST] [--port PORT]
[--debug] [--log-level {DEBUG,INFO,WARNING,ERROR,CRITICAL}]
[--validate-config]
Examples:
python app.py --mode hybrid --port 8080 --debug
python app.py --config production.yaml --log-level INFO
python app.py --create-config sample-config.yaml
python app.py --validate-config --config config.yamlAPI端点(REST)
核心终点
GET / -根
返回欢迎信息和API信息。
GET /health -健康检查
{
"status": "ready",
"mode": "hybrid",
"uptime_seconds": 3600,
"metrics": {
"requests_total": 150,
"requests_active": 2,
"errors_total": 1
},
"timestamp": "2024-01-15T10:30:00Z"
}GET /metrics -可用指标
{
"metrics": [
{"name": "cpu_usage", "description": "CPU usage percentage (0-100)"},
{"name": "memory_usage", "description": "Memory usage percentage (0-100)"},
{"name": "temperature", "description": "Temperature in Celsius"}
]
}数据查询端点
GET /timeseries -时间序列数据查询
使用灵活的参数查询时间序列数据。
参数:
metric(必填):度量名称(cpu_usage、memory_usage和温度)start_time(可选):ISO 8601格式的开始时间end_time(可选):ISO 8601格式的结束时间limit(可选):返回的最大点数(默认值:100,最大值:10000)frequency(可选):数据频率(1H、30T、1D等)(默认:1H)
例子:
curl "http://localhost:8000/timeseries?metric=cpu_usage&start_time=2024-01-15T00:00:00&end_time=2024-01-16T00:00:00&limit=50&frequency=1H"答复:
{
"data": [
{
"timestamp": "2024-01-15T00:00:00",
"value": 45.2,
"metric": "cpu_usage"
}
],
"count": 25,
"start_time": "2024-01-15T00:00:00",
"end_time": "2024-01-16T00:00:00"
}GET /timeseries/aggregate -聚合数据
使用各种统计方法获取聚合的时间序列数据。
参数:
metric(必填):度量名称start_time(可选):ISO 8601格式的开始时间end_time(可选):ISO 8601格式的结束时间aggregation(可选):方法(平均值、总和、最小值、最大值、计数)(默认值:平均值)window(可选):聚合窗口(1H、1D、1W)(默认:1H)
例子:
curl "http://localhost:8000/timeseries/aggregate?metric=memory_usage&aggregation=mean&window=6H"MCP服务器工具
MCP服务器为AI应用程序提供高级分析工具:
可用工具
query_timeseries
相当于REST /timeseries 具有相同参数的端点。
get_metrics
列出可用指标及其描述。
aggregate_data
使用pandas重采样进行高级数据聚合。
detect_anomalies
使用z评分或IQR方法进行统计异常检测。
参数:
metric:要分析的度量名称method:检测方法(zscore、iqr)threshold:灵敏度阈值(默认值:zscore为2.0,iqr为1.5)
forecast_trend
使用线性回归或移动平均线进行时间序列预测。
参数:
metric:要预测的度量名称method:预测方法(线性、移动平均)periods:未来期数(默认值:24)frequency:预测频率(1H、1D等)
MCP资源
服务器还提供缓存的资源端点:
timeseries://cpu_usage/last24htimeseries://memory_usage/last24htimeseries://temperature/last24htimeseries://cpu_usage/last7dtimeseries://memory_usage/last7dtimeseries://temperature/last7d
发展
项目结构
ts_api/
├── app.py # Unified entry point
├── config.py # Configuration management
├── main.py # FastAPI REST application
├── mcp_server.py # MCP server implementation
├── mcp_client.py # MCP client for testing
├── test_integration.py # Integration tests
├── test_api.py # REST API tests (legacy)
├── requirements.txt # Python dependencies
├── CLAUDE.md # Development instructions
└── README.md # This file运行测试
集成测试(推荐)
# Run comprehensive integration tests
python test_integration.py
# Run with pytest for better output
pytest test_integration.py -v遗留测试
# Start REST server first
python main.py
# Run REST API tests in another terminal
python test_api.pyMCP服务器测试
# Test MCP server functionality
python test_mcp_server.py
# Test MCP client communication
python test_mcp_client.py性能测试
集成测试包括性能基准测试:
# Run performance tests
python test_integration.py
# Results include response time analysis:
# /health: avg=0.002s, max=0.005s
# /metrics: avg=0.003s, max=0.008s
# /timeseries: avg=0.050s, max=0.120s配置验证
# Validate configuration file
python app.py --validate-config --config config.yaml
# Create sample configuration
python app.py --create-config sample-config.yaml生产部署
Docker部署
- 创建Dockerfile:
FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000 8001
# Default to hybrid mode
CMD ["python", "app.py", "--mode", "hybrid", "--host", "0.0.0.0"]- 构建并运行:
docker build -t ts-api .
docker run -p 8000:8000 -p 8001:8001 ts-api生产配置
创建生产配置文件:
mode: hybrid
debug: false
environment: production
logging:
level: INFO
json_format: true
file_path: /var/log/ts_api/app.log
rest:
host: 0.0.0.0
port: 8000
workers: 4
performance:
enable_metrics: true
max_concurrent_requests: 200
memory_limit_mb: 2048监控和日志记录
结构化日志记录
为生产启用JSON日志记录:
export TS_API_LOG_JSON=true
export TS_API_LOG_LEVEL=INFO健康监测
在运行状况端点上设置监控:
curl -f http://localhost:8000/health || exit 1性能指标
通过运行状况端点访问性能数据:
{
"metrics": {
"requests_total": 10450,
"requests_active": 5,
"errors_total": 12,
"uptime_seconds": 86400
}
}迁移指南
来自旧版REST API(main.py)
- 更新启动命令:
# Old
python main.py
# New
python app.py --mode rest- 所有现有端点保持兼容
- 新的运行状况和配置端点可用
来自MCP服务器(MCP_Server.py)
- 更新启动命令:
# Old
python mcp_server.py
# New
python app.py --mode mcp- 所有MCP工具保持不变
- 增强的日志记录和配置支持
切换到混合动力模式
- 对两种协议都使用混合模式:
python app.py --mode hybrid- 访问端口8000上的REST API
- 通过STDIO传输访问MCP服务器
- 通过统一的健康端点对两者进行监控
API兼容性矩阵
| 功能 | REST API | MCP服务器 | 混合模式 |
|---|---|---|---|
| 时间序列查询 | ✅ /timeseries | ✅ query_timeseries | ✅ 两者皆有 |
| 指标列表 | ✅ /metrics | ✅ get_metrics | ✅ 两者皆有 |
| 数据聚合 | ✅ /timeseries/aggregate | ✅ aggregate_data | ✅ 两者皆有 |
| 异常检测 | ❌ | ✅ detect_anomalies | ✅ 仅限MCP |
| 趋势预测 | ❌ | ✅ forecast_trend | ✅ 仅限MCP |
| 健康监测 | ✅ /health | ❌ | ✅ 仅限REST |
| 配置 | ✅ /config (调试) | ❌ | ✅ 仅限REST |
| 资源端点 | ❌ | ✅ 资源 | ✅ 仅限MCP |
性能基准
基于样本数据的集成测试:
| 端点 | 平均响应时间 | 最大响应时间 | 备注 |
|---|---|---|---|
/health | ~2ms | ~5ms | 最小处理 |
/metrics | ~3ms | ~8ms | 静态数据 |
/timeseries (100点) | ~50ms | ~120ms | 数据生成+处理 |
/timeseries/aggregate | ~80ms | ~200ms | 熊猫重采样 |
| MCP工具 | ~60ms | ~150ms | 类似于REST+序列化 |
内存使用:~50-100MB基线,每1000个数据点增加~1MB
并发请求:测试了多达100个并发请求,性能稳定
故障排除
常见问题
“端口已在使用中”
# Check what's using the port
lsof -i :8000
# Use different port
python app.py --port 8080“配置验证错误”
# Validate your config file
python app.py --validate-config --config config.yaml
# Create a working sample
python app.py --create-config working-config.yaml“MCP服务器连接问题”
- 确保STDIO传输已正确配置
- 检查是否没有其他进程正在使用STDIN/STDOUT
- 验证MCP客户端是否与协议版本兼容
“查询性能缓慢”
- 减少
limit查询中的参数 - 在大时间范围内使用聚合
- 在配置中启用缓存
- 通过以下方式监控内存使用情况
psutil
调试模式
启用调试模式以进行详细日志记录:
python app.py --debug --log-level DEBUG健康检查故障排除
# Check application status
curl http://localhost:8000/health
# Expected response:
# {"status": "ready", "mode": "hybrid", ...}
# If status is "error", check logs for details贡献
- 代码的风格:遵循PEP 8和现有模式
- 测试:在中添加新功能的测试
test_integration.py - 文档:更新README.md和文档字符串
- 日志记录:为新组件添加结构化日志记录
添加新指标
- 更新数据生成器 在
main.py和mcp_server.py:
elif metric == "new_metric":
values = generate_new_metric_data(date_range)- 添加到指标列表 在
/metrics端点和MCPget_metrics
- 添加测试 在
test_integration.py
添加新的MCP工具
- 添加工具定义 在
handle_list_tools() - 机具处理程序 遵循现有模式的功能
- 添加错误处理 以及日志记录
- 更新文档 在这个README中
许可证
该项目根据MIT许可证获得许可。有关详细信息,请参阅LICENSE文件。
支持
对于问题和疑问:
- 检查故障排除部分
- 在启用调试模式的情况下查看日志
- 验证配置文件
- 运行集成测试以验证功能
