Skip to main content
Glama

Echo — объяснимые аномалии во временных рядах через Matrix Profile

Единственный проект в этой серии, который меняет не только масштаб, а домен и математический аппарат. Вместо дискретных символьных систем (git, файлы, политики) — непрерывные сигналы: показания датчиков, метрики серверов, биометрика, финансовые ряды.

Почему Matrix Profile, а не просто "порог + z-score"

Наивное обнаружение аномалий ("если значение выше среднего на 3σ — тревога") не объясняет почему что-то аномально и плохо работает с формой сигнала — пропускает "структурные" аномалии (например, правильные значения, но не в то время суток). Matrix Profile для каждого фрагмента сигнала находит его ближайшего двойника во всей остальной истории. Нет хорошего двойника — аномалия, и вот её конкретное объяснение: "вот с чем я тебя сравнивал, и даже это не похоже".

Related MCP server: timeseries-mcp

Демонстрация на реалистичных данных

240 часов (10 дней) почасовых показаний датчика температуры с естественным суточным циклом. В часы 120–131 датчик "застревает" на 23°C, не падая ночью, как во все остальные дни.

ANOMALIES (discords):
  Subsequence at [100:124] doesn't resemble anything else in the series
  (distance=4.77). ...
  Subsequence at [124:148] doesn't resemble anything else (distance=2.05).

RECURRING PATTERNS (motifs):
  Subsequence at [0:24] closely repeats the pattern at index 24
  (distance=0.00, near-zero means an almost exact shape match).

Обе найденные аномалии точно накрывают внедрённый диапазон 120–131 — подтверждено golden-тестом. При top_k=3 отчёт всё равно возвращает только две: нулевые distance после дедупликации — это мотивы, не аномалии, и top_discords их не подмешивает. Мотивы находят точные суточные циклы (окна на границах дней) — корректный фон нормальности.

Ключевая деталь алгоритма: exclusion zone

Без неё у каждого фрагмента "ближайшим соседом" тривиально оказался бы он сам или соседнее перекрывающееся окно (расстояние ~0), и весь профиль был бы бессмысленным. Exclusion zone (половина длины окна вокруг каждой точки) — это не оптимизация, а требование корректности из оригинальной статьи (Yeh et al., 2016). Проверено отдельным тестом, что при её отсутствии все "ближайшие соседи" оказались бы тривиально рядом.

Реальная находка в процессе разработки: дедупликация top-k

При первом запуске top-3 "самых аномальных" фрагментов оказались тремя соседними окнами, покрывающими одну и ту же аномалию — технически корректно, но бесполезно. Решение: top_discords пропускает кандидатов ближе subsequence_length к уже выбранным и останавливается на distance≈0.

Архитектура (Clean Architecture по Мартину)

src/echo/
├── entities/
│   ├── time_series.py      # z-normalize, distance, finite checks
│   ├── matrix_profile.py   # алгоритм + exclusion zone
│   └── findings.py         # Discord/Motif, top-k, preview
├── use_cases/
│   └── analyze_time_series.py
├── interfaces/
│   └── ports.py            # SeriesLoader
├── infrastructure/
│   └── csv_series_loader.py
└── presentation/
    ├── composition_root.py
    ├── formatting.py
    └── mcp_server.py

Алгоритм — brute-force O(n²m), осознанно: корректность важнее скорости для типичных объёмов (сотни–тысячи точек). MASS/FFT не реализован — задокументированное ограничение.

Установка

pip install -e ".[dev]"

Подключение к Cursor / Claude Desktop

Как у остальных серверов серии (надёжнее, чем echo-mcp вне PATH):

{
  "mcpServers": {
    "echo": {
      "command": "C:\\Python314\\python.exe",
      "args": ["-m", "echo.presentation.mcp_server"]
    }
  }
}

MCP Tools

Tool

Назначение

analyze_series(values, subsequence_length, top_k)

Анализ ряда напрямую

analyze_csv(file_path, column, subsequence_length, top_k)

Числовая колонка CSV

Вход отвергает NaN/Inf, пустой CSV, top_k < 1 и неверную длину окна.

Тесты

.\make.ps1

Стена Мартина: black, ruff, mypy, pytest --cov≥90, лимиты функций. Golden stuck-sensor, hypothesis-свойства distance/exclusion zone, дедупликация top-k без фейковых аномалий, MCP-tools.

Лицензия

MIT

Available Tools

2 tools
analyze_csvB

Same as analyze_series, but loads the values from a numeric column of a CSV file.

Args: file_path: Absolute path to the CSV file. column: Name of the numeric column to analyze. subsequence_length: Pattern window length (see analyze_series). top_k: How many top anomalies/patterns to report.

Inputs: column (required), file_path (required), subsequence_length (required), top_k. Returns: result

analyze_seriesA

Find explainable anomalies and recurring patterns in a time series using the Matrix Profile algorithm. Each anomaly is explained by showing its nearest match elsewhere in the series (or the lack of one), not just flagged as a bare score.

Args: values: The time series as a flat list of numbers, in order. subsequence_length: The length of the pattern window to compare (e.g. 12 for a daily cycle sampled hourly). Must be at least 3 and at most half the series length. top_k: How many top anomalies/patterns to report.

Inputs: values (required), subsequence_length (required), top_k. Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.5/5.0

    Scored across 2 tools

    Disambiguation3/5

    The two tools are distinguishable by input source (in-memory list vs. CSV file path), so an agent can pick correctly. However, analyze_csv is explicitly documented as 'same as analyze_series' but with a file loader, meaning they are functionally the same operation with overlapping purpose and only a thin input-format boundary.

    Naming Consistency5/5

    Both names follow a clean, predictable verb_noun snake_case pattern (analyze_series, analyze_csv) with a shared 'analyze_' prefix that signals the common family. No deviation or mixed convention.

    Tool Count3/5

    With only two tools, the surface is thin — it amounts to one core algorithm exposed through two input adapters. That is borderline minimal rather than a well-rounded set, though the narrow scope keeps it from being egregious.

    Completeness3/5

    For time-series anomaly/pattern discovery the pair does cover list and CSV inputs, but there are notable gaps: no output for the raw Matrix Profile, no way to write/export results, and no multi-column or batch analysis. Agents can work around these but the lifecycle feels partial.

    Maintenance

    ActivitySlowing
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      An MCP server that exposes GPU-accelerated anomaly detection to AI assistants via the Model Context Protocol. Provides two MCP tools: waveguard_scan (send training + test data in one call, returns per-sample anomaly scores and top explanatory features) and waveguard_health (check API and GPU status). Works on time series, JSON, numbers, text, and images — fully stateless.
      3
      4
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      Deterministic time-series statistics for AI agents. This MCP server gives any LLM agent unit-tested statistical tools — anomaly detection, changepoint detection, seasonal decomposition, stationarity/trend tests, data-quality audits, baseline forecasts — with schema-validated structured output and no arbitrary code execution.
      17
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables incident detection and analysis by identifying anomalies in metric time series and surfacing root-cause candidates and recommended actions. Supports both mock (synthetic) and VictoriaMetrics backends with identical MCP tool contracts for seamless development-to-production switching.
      MIT