Token导航 LogoToken导航TokenDH.com
ts API logo
运维云端stdio官方级别未说明来源级核验

ts API

MCP Server

一个支持REST和MCP协议的时间序列数据分析API,提供高级分析、预测和异常检测功能。

工具数

5

提示词数

0

GitHub Stars

0

资源数

0
PythonClaude云端部署Claude

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

jacobeverist

提供方

jacobeverist

最后核验

2026/5/17 20:20

运行时

Python

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

命令预览

python -m venv venv

详细介绍

时间序列API-统一的REST和MCP服务器

全面的时间序列数据API,支持传统的REST端点和模型上下文协议(MCP)服务器功能。这种统一的实现提供了高级分析、预测和异常检测功能,并具有生产就绪功能。

特性

核心功能

  • 双协议支持:统一应用程序中的REST API和MCP服务器
  • 时间序列数据:使用灵活的参数查询、聚合和分析时间序列数据
  • 高级分析:统计异常检测、趋势预测和数据聚合
  • 示例数据生成:用于测试和开发的内置合成数据生成器
  • 交互式文档:用于REST API探索的Swagger UI和ReDoc

第4阶段增强功能

  • 统一入口点:单个应用程序仅支持REST、MCP或混合模式
  • 配置管理:具有环境变量覆盖的YAML/JSON配置
  • 结构化日志记录:带有性能指标的JSON和文本日志
  • 集成测试:全面的端到端测试套件
  • 健康监测:性能指标和健康检查端点
  • 优雅关闭:正确的信号处理和资源清理

快速开始

安装

  1. 克隆和设置环境:
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

测试设置

  1. REST API:参观 http://localhost:8000/docs 用于交互式文档
  2. 健康检查: curl http://localhost:8000/health
  3. 示例查询: 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.yaml

API端点(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/last24h
  • timeseries://memory_usage/last24h
  • timeseries://temperature/last24h
  • timeseries://cpu_usage/last7d
  • timeseries://memory_usage/last7d
  • timeseries://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.py

MCP服务器测试

# 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部署

  1. 创建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"]
  1. 构建并运行:
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)

  1. 更新启动命令:
   # Old
   python main.py

   # New
   python app.py --mode rest
  1. 所有现有端点保持兼容
  1. 新的运行状况和配置端点可用

来自MCP服务器(MCP_Server.py)

  1. 更新启动命令:
   # Old
   python mcp_server.py

   # New
   python app.py --mode mcp
  1. 所有MCP工具保持不变
  1. 增强的日志记录和配置支持

切换到混合动力模式

  1. 对两种协议都使用混合模式:
   python app.py --mode hybrid
  1. 访问端口8000上的REST API
  1. 通过STDIO传输访问MCP服务器
  1. 通过统一的健康端点对两者进行监控

API兼容性矩阵

功能REST APIMCP服务器混合模式
时间序列查询/timeseriesquery_timeseries✅ 两者皆有
指标列表/metricsget_metrics✅ 两者皆有
数据聚合/timeseries/aggregateaggregate_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

贡献

  1. 代码的风格:遵循PEP 8和现有模式
  2. 测试:在中添加新功能的测试 test_integration.py
  3. 文档:更新README.md和文档字符串
  4. 日志记录:为新组件添加结构化日志记录

添加新指标

  1. 更新数据生成器main.pymcp_server.py:
   elif metric == "new_metric":
       values = generate_new_metric_data(date_range)
  1. 添加到指标列表/metrics 端点和MCP get_metrics
  1. 添加测试test_integration.py

添加新的MCP工具

  1. 添加工具定义handle_list_tools()
  2. 机具处理程序 遵循现有模式的功能
  3. 添加错误处理 以及日志记录
  4. 更新文档 在这个README中

许可证

该项目根据MIT许可证获得许可。有关详细信息,请参阅LICENSE文件。

支持

对于问题和疑问:

  1. 检查故障排除部分
  2. 在启用调试模式的情况下查看日志
  3. 验证配置文件
  4. 运行集成测试以验证功能

目录标签

目录标签

PythonClaude云端部署时间序列分析本地部署数据聚合异常检测趋势预测双协议支持

支持客户端

Claude

接入字段

传输方式(transport,传输协议)

stdio

鉴权方式(authType,认证方式)

none

运行时(runtime,运行环境)

Python

工具数量(toolCount,工具数)

5

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

stdionone部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

来源信息

继续浏览同类 MCP