TimeSense MCP服务器
受LLM启发的用于时间序列分析的模型上下文协议(MCP)服务器 TimeSense论文.
概述
TimeSense MCP为Claude Code和Cursor等LLM驱动的工具提供智能时间序列分析功能。它结合了:
- 时间序列预处理 具有归一化、分割和特征提取功能
- LLM推理 使用结构化提示的跨时间数据
- 数值验证 在统计现实中实现LLM输出
- MCP协议 与AI编码助手无缝集成
主要特点
✅ EvalTS启发的任务类别:
- 原子理解:极值、趋势、峰值、变化点
- 分子推理:分割、比较、相对变化
- 组成任务:异常检测、根本原因分析、全面描述
✅ TimeSense编码方法:
- 位置嵌入(索引+值对)
- `` 时间序列数据的标记
- 长序列的基于摘要的编码
✅ 外部时间感验证:
- 根据统计计算验证LLM输出
- 提供置信度评分和差异度量
- 无需模型训练即可捕捉幻觉
建筑
Time Series → Preprocessing → Encoding → LLM Prompt → LLM Response
↓ ↓
Features & Verification
Statistics (optional)
↓ ↓
Final Analysis模块:
preprocessing.py-归一化、分割、特征提取、异常检测encoder.py-将时间序列转换为具有位置信息的文本(`` 标记)prompts.py-与EvalTS对齐的特定任务提示模板verification.py-根据数字地面实况进行外部验证server.py-MCP服务器公开分析工具
安装
先决条件
- Python 3.10+
- pip或uv包管理器
设置
# Clone the repository
git clone https://github.com/andreahaku/time_series_llm_mcp.git
cd time_series_llm_mcp
# Install dependencies
pip install -e .
# Or with development dependencies
pip install -e ".[dev]"配置为MCP服务器
添加到您的Claude Code或MCP客户端配置中:
克劳德代码 (~/.config/claude/claude_desktop_config.json):
{
"mcpServers": {
"timesense": {
"command": "python",
"args": ["-m", "src.server"],
"cwd": "/path/to/time_series_llm_mcp"
}
}
}对于光标 (.cursorrules 或设置):
{
"mcp": {
"servers": {
"timesense": {
"command": "python -m src.server",
"cwd": "/path/to/time_series_llm_mcp"
}
}
}
}用法
MCP工具
1. analyze_time_series
具有自动或手动任务类型选择的通用时间序列分析。
参数:
series(列表\[TimeSeriesInput\]):时间序列数据question(str):分析问题task_type(str,可选):任务类型或“自动”verify(bool):启用验证(默认值:true)
例子:
{
"series": [{
"name": "cpu_usage",
"timestamps": ["2025-01-01T00:00:00", "2025-01-01T01:00:00", ...],
"values": [45.2, 48.1, 52.3, ...]
}],
"question": "What is the maximum CPU usage and when did it occur?",
"task_type": "extreme",
"verify": true
}支持的任务类型:
extreme-查找最大/最小值spike-检测尖峰和异常trend-识别趋势(增加/减少/稳定)change_point-检测政权更迭segment-分阶段comparison-比较多个系列describe-综合分析anomaly_detection-检测并解释异常情况
2. describe_segments
分段时间序列并描述每个阶段。
参数:
series(TimeSeriesInput):要分段的时间序列window_size(int):分段窗口大小(默认值:50)
例子:
{
"series": {
"name": "temperature",
"timestamps": [...],
"values": [...]
},
"window_size": 30
}3. detect_anomalies
使用可选的自定义规则检测异常。
参数:
series(列表\[TimeSeriesInput\]):要分析的时间序列interval(List\[int\],可选):聚焦间隔\[start,end\]anomaly_rules(List\[str\],可选):自定义规则
例子:
{
"series": [{
"name": "latency",
"timestamps": [...],
"values": [...]
}],
"interval": [100, 200],
"anomaly_rules": [
"Latency above 100ms is anomalous",
"Sudden jumps > 20ms indicate issues"
]
}4. compare_series
比较两个时间序列并找出差异。
参数:
series_a(TimeSeriesInput):第一系列series_b(TimeSeriesInput):第二系列aspect(str):比较什么(默认:“整体行为”)
例子:
{
"series_a": {"name": "production", ...},
"series_b": {"name": "staging", ...},
"aspect": "latency and throughput"
}示例工作流
一旦配置为MCP服务器,您就可以直接从AI编码助手使用TimeSense。以下是真实世界的场景:
1.性能监控
场景:调查服务器性能问题
User: I have CPU usage data in monitoring_data.json. What was the peak CPU
usage today and when did it occur?
Claude Code: [Uses analyze_time_series with task_type="extreme"]
Result: ✓ Peak CPU usage was 94.2% at index 847 (2025-01-17 14:23:00)
Verification: Confirmed with 100% confidence2.异常检测
场景:检测应用程序指标中的异常模式
User: Analyze response_times.csv and tell me if there are any anomalous spikes
in the last hour (indices 3600-7200).
Claude Code: [Uses detect_anomalies with interval=[3600, 7200]]
Result: ## Statistical Detection
- Spikes detected: 12
- Indices: [3847, 3891, 4203, 4567, 5012, 5234, 5678, 6012, 6234, 6789, 7001, 7123]
## LLM Analysis
The series shows a cluster of anomalous spikes starting around index 3847.
These spikes exceed 3 standard deviations above the mean and appear to
correlate with deployment events. The pattern suggests intermittent service
degradation rather than sustained issues.3.部署比较
场景:比较部署前后的指标
User: Compare the latency between before_deploy.json and after_deploy.json.
Did performance improve or degrade?
Claude Code: [Uses compare_series]
Result: ## Statistical Comparison
| Metric | before_deploy | after_deploy | Difference |
|---------|---------------|--------------|------------|
| Mean | 245.3ms | 189.7ms | -55.6ms |
| Std | 42.1ms | 28.3ms | -13.8ms |
| Max | 892.1ms | 456.2ms | -435.9ms |
## LLM Analysis
Performance significantly improved after deployment:
- Average latency decreased by 22.7%
- Variability reduced (lower std deviation)
- Peak latency cut in half
- The improvement is consistent across the entire time period4.趋势分析
场景:了解长期模式
User: What's the overall trend of user_growth.csv over the past 6 months?
Are there any change points where growth accelerated or slowed?
Claude Code: [Uses analyze_time_series with task_type="auto"
→ infers "trend" and "change_point"]
Result: ## Trend Analysis
Overall trend: increase
Confidence: high
## Change Points Detected
- Index 892 (Month 2): Growth rate doubles
- Index 2401 (Month 4): Plateau begins
- Index 3567 (Month 5): Growth resumes at moderate pace
The user base shows three distinct growth phases: initial steady growth,
followed by viral acceleration in month 2, a saturation period in month 4,
and renewed moderate growth as new features launched.5.分段和阶段分析
场景:分解复杂的时间序列行为
User: Segment the stock_prices.csv data and describe each phase.
Claude Code: [Uses describe_segments with window_size=50]
Result: ## Overall Statistics
- Length: 1440 points (6 months of trading days)
- Mean: $142.35
- Range: [$98.20, $187.45]
## Segments (15 total)
### Segment 1
- Interval: indices [0, 50]
- Trend: **increasing**
- Mean: $105.23, Slope: +0.3214
- Bullish rally phase with consistent gains
### Segment 2
- Interval: indices [50, 100]
- Trend: **volatile**
- Mean: $118.45, Slope: +0.1832
- High volatility period, earnings uncertainty
[... segments 3-14 ...]
### Segment 15
- Interval: indices [700, 750]
- Trend: **flat**
- Mean: $165.82, Slope: -0.0023
- Consolidation after peak, sideways movement6.多系列根本原因分析
场景:调查跨服务的相关故障
User: I have metrics from 5 microservices in services_metrics/. Between
10:00-11:00 AM, response times spiked across all services. Can you
identify which service caused the cascade failure?
Claude Code: [Uses analyze_time_series with task_type="anomaly_detection"
on all 5 series, then correlates timing]
Result: ## Anomaly Detection Results
### Service: auth-service
- Anomaly start: index 600 (10:02 AM)
- Type: upward spike in latency
- Severity: 5.2σ above normal
### Service: user-service
- Anomaly start: index 615 (10:05 AM)
- Type: upward spike
- Severity: 3.8σ above normal
### Service: payment-service
- Anomaly start: index 618 (10:05 AM)
...
## Root Cause Analysis
Based on the temporal sequence, **auth-service** appears to be the root cause:
1. First to show anomaly (index 600)
2. Highest severity (5.2σ)
3. Other services degraded 3-5 minutes later
4. Propagation chain: auth-service → user-service → payment-service → ...
Recommendation: Investigate auth-service for issues around 10:02 AM.7.自定义异常规则
场景:域特定异常检测
User: In temperature_sensors.csv, detect anomalies using these rules:
- Sensor 1: temp > 75°C is critical
- Sensor 2: temp 15°C are critical
Claude Code: [Uses detect_anomalies with custom anomaly_rules]
Result: ## Anomaly Detection Results
### Sensor 1
- Anomalies detected: Yes
- Critical intervals: [234, 289], [567, 612]
- Type: upward (exceeded 75°C threshold)
- Max temperature: 82.3°C at index 267
- Duration: Total 101 minutes above threshold
### Sensor 2
- Anomalies detected: Yes
- Critical intervals: [1203, 1289]
- Type: downward (below 10°C)
- Min temperature: 6.8°C at index 1245
- Possible cooling system failure
### Sensor 3
- Anomalies detected: Yes
- Sudden changes: [445, 891, 1567]
- Index 445: +18.2°C jump in 1 minute
- Index 891: -16.7°C drop in 1 minute
- Likely sensor malfunction or physical shock events快速命令示例
对于编码助手中的简单单行代码:
# Find maximum value
"What's the max value in sales_data.csv?"
# Detect spikes
"Are there any anomalous spikes in error_logs.json?"
# Compare versions
"Compare API latency between v1.2 and v1.3"
# Identify trends
"Is user engagement increasing or decreasing in metrics.csv?"
# Find change points
"When did the traffic pattern change in web_analytics.json?"
# Segment analysis
"Break down stock_prices.csv into distinct phases"备注:所有示例都透明地使用MCP工具——您不需要知道工具名称或参数,只需描述您想要分析的内容!
TimeSense论文实施
此MCP服务器实现了 TimeSense论文:
我们实施什么
✅ 位置编码:每个时间点都包括其绝对索引 ✅ `` 标记:包裹在特殊代币中的时间序列 ✅ EvalTS任务类别:原子、分子和组成任务 ✅ 外部时间感知:通过数值计算进行验证
我们没有实施什么(MVP)
❌ 模型训练:通过API使用预先训练的LLM(无自定义微调) ❌ 基于补丁的MLP编码:改用文本表示法 ❌ 内部重建损失:验证是外部的,不是后天习得的 ❌ ChronGen数据生成:可以添加用于测试/评估
设计理念
这是一个 实用MVP 即:
- 给你图案 对于时间序列+LLM,无需重新实施整篇论文
- 使用外部验证 而不是训练内部重建模块
- 专注于有用的任务 (EvalTS子集)而不是全面的基准测试
- 开箱即用 通过API调用使用现有LLM
发展
项目结构
time_series_llm_mcp/
├── src/
│ ├── __init__.py
│ ├── server.py # MCP server
│ ├── preprocessing.py # Time series preprocessing
│ ├── encoder.py # TS → text encoding
│ ├── prompts.py # Task-specific prompts
│ └── verification.py # Numerical verification
├── examples/
│ └── basic_usage.py # Usage examples
├── docs/
│ └── 2511.06344v1.pdf # TimeSense paper
├── CLAUDE.md # Claude Code guidance
├── SETUP.md # Setup instructions
├── pyproject.toml
└── README.md运行测试
# Run examples
python examples/basic_usage.py
# Run the server directly
python -m src.server
# With pytest (after implementing tests)
pytest tests/贡献
欢迎投稿!需要改进的地方:
- \[\]实际Anthropic API集成(当前使用占位符)
- \[\]ChronGen合成数据生成器
- \[\]全面实施EvalTS基准测试
- \[\]更复杂的变化点检测算法
- \[\]季节性和趋势分解(STL)
- \[\]多元异常检测(基于LSTM的隔离林)
- \[\]多元序列的根本原因分析
- \[\]流媒体/在线分析模式
参考文献
- 时间感论文: 使大型语言模型精通时间序列分析
- 模型上下文协议: MCP文件
- 克劳德代码: 人类克劳德密码
许可证
MIT许可证-有关详细信息,请参阅许可证文件
引用
如果您使用此作品,请引用TimeSense的原始论文:
@article{zhang2025timesense,
title={TimeSense: Making Large Language Models Proficient in Time-Series Analysis},
author={Zhang, Zhirui and Pei, Changhua and Gao, Tianyi and Xie, Zhe and Hao, Yibo and Yu, Zhaoyang and Xu, Longlong and Xiao, Tong and Han, Jing and Pei, Dan},
journal={arXiv preprint arXiv:2511.06344},
year={2025}
}______________________________________________________________________
内置于🤖 通过将TimeSense研究与实际MCP实现相结合
