mcp-root-cause-detective
# 🕵️♂️ mcp-root-cause-detective
[](https://www.python.org/downloads/)
[](https://modelcontextprotocol.io/)
[](LICENSE)
**Çok kaynaklı uygulama, veritabanı, Nginx, Kubernetes, Docker ve Git değişiklik geçmişini UTC ekseninde normalleştiren; Drain şablon madenciliği, dağıtık `trace_id` izleme ve nedensellik puanlamasıyla yapay zeka ajanlarına doğrudan "kök neden analizi" sunan Model Context Protocol (MCP) sunucusu.**
---
## 🎯 Neden `mcp-root-cause-detective`?
Geleneksel yaklaşımlarda yapay zeka asistanına binlerce satırlık ham log dosyası yapıştırılır. Bu durum hem **context penceresini hızla tüketir**, hem hassas verileri (API anahtarı, şifre, PII) sızdırabilir hem de farklı servislerdeki zincirleme hataların gözden kaçmasına yol açar.
`mcp-root-cause-detective`, veriyi LLM'e göndermeden önce Python katmanında şu işlemleri yapar:
1. **Sıfır Kayıplı Çoklu Format Ayrıştırma ([parser.py](src/mcp_root_cause_detective/parser.py)):** ISO-8601, Docker nanosaniye, JSON/OpenTelemetry/Pino, PostgreSQL (`ERROR`/`DETAIL`/`STATEMENT`), Nginx/Apache access (otomatik `5xx -> ERROR`, `4xx -> WARN`), Syslog ve çok satırlı stack trace çıktılarını UTC zaman ekseninde tekilleştirir.
2. **Otomatik Secret & PII Maskeleme ([redactor.py](src/mcp_root_cause_detective/redactor.py)):** Bearer token, JWT, AWS/GitHub/API anahtarları, DB bağlantı şifreleri, e-posta ve kart numaralarını LLM'e ve belleğe ulaşmadan `<REDACTED_*>` etiketleriyle temizler.
3. **Drain Tabanlı Şablon Madenciliği ([template_miner.py](src/mcp_root_cause_detective/template_miner.py)):** Dinamik değişkenleri (`<UUID>`, `<IP>`, `<URL>`, `<NUM>`, `<*>`) maskeleyerek tekrarlayan binlerce hatayı tek bir okunabilir şablona indirger.
4. **Nedensellik Puanlaması & Trace Korelasyonu ([correlator.py](src/mcp_root_cause_detective/correlator.py)):**
- Aynı `trace_id` / `request_id` / W3C `traceparent` değerine sahip servis adımlarını uçtan uca birleştirir.
- Hata öncesi `WARN`, `deadlock`, `timeout`, yüksek gecikme (`latency_ms`) ve servisler arası öncelik sinyallerini güven skoruyla (`root_cause_hypotheses`) sıralar.
- Ani hata patlamalarını (`error_spikes`) yakalar ve çoklu servis akışları için otomatik **Mermaid `sequenceDiagram`** üretir.
5. **Aşamalı Keşif (Progressive Disclosure):** İlk adımda kompakt özet (`analysis_id`) döndürür; ajan ihtiyaç duyduğunda `inspect_error_cluster`, `trace_request_flow` ve `get_timeline_slice` araçlarıyla detaya iner.
---
## 🏗️ Mimari Akış
```text
┌───────────────────┐ ┌───────────────────┐ ┌───────────────────┐
│ Dosya / .gz Log │ │ Docker / K8s Pods │ │ Git Geçmişi / │
│ (.log/.jsonl/.gz) │ │ (+ K8s Events) │ │ Ham Stack Trace │
└─────────┬─────────┘ └─────────┬─────────┘ └─────────┬─────────┘
│ │ │
└──────────────────────┼──────────────────────┘
▼
┌─────────────────────────────┐
│ parser.py + redactor.py │
│ UTC + Stack Folding + PII │
└──────────────┬──────────────┘
▼
┌─────────────────────────────┐
│ template_miner + correlator │
│ Drain + Trace + Causal Skor │
└──────────────┬──────────────┘
▼
┌─────────────────────────────┐
│ MCPServer (v1 & v2 SDK) │
│ Tools · Resources · Prompts │
└──────────────┬──────────────┘
│ stdio / streamable-http / sse
▼
┌─────────────────────────────┐
│ Cursor / Claude / VS Code │
│ Kanıta Dayalı Teşhis │
└─────────────────────────────┘
```
---
## 🛠️ Sunulan MCP Araçları, Kaynaklar ve Promptlar
### Araçlar (Tools — Tümü `readOnlyHint=True` & `structured_output=True`)
| Araç Adı | Açıklama | Temel Parametreler |
| :--- | :--- | :--- |
| **`analyze_log_files`** | Yerel, glob (`*.log`) ve sıkıştırılmış (`.gz`) log dosyalarını bellek dostu sondan okumayla analiz eder. | `file_paths`, `window_seconds=5`, `tail_lines=1000` |
| **`analyze_docker_containers`** | Çalışan Docker konteynerlerinin loglarını zaman aşımı korumasıyla toplar ve ilişkilendirir. | `container_names`, `tail_lines=300`, `window_seconds=5`, `since` |
| **`analyze_kubernetes_pods`** | `kubectl logs` ve `kubectl get events` (`OOMKilling`, `BackOff`) sinyallerini birleştirir. | `namespace="default"`, `label_selector`, `pod_names`, `include_events=True` |
| **`diagnose_raw_stacktrace`** | Terminalden yapıştırılan stack trace çıktılarını katlayıp kök çerçeveyi (`root_frame`) ayıklar. | `raw_log_text`, `source_name="terminal_output"` |
| **`inspect_error_cluster`** | Belirli bir hata kümesinin (`signature`) tam stack trace ve ham örneklerini getirir. | `signature`, `analysis_id`, `max_samples=5` |
| **`trace_request_flow`** | Belirli bir `trace_id` / `request_id` akışını tüm servislerde kronolojik izler. | `correlation_id`, `analysis_id` |
| **`get_timeline_slice`** | Şüpheli bir UTC zaman damgası etrafındaki filtrelenmiş ham log kesitini döndürür. | `center_timestamp`, `window_seconds=5`, `sources`, `min_level="DEBUG"` |
| **`correlate_with_git_changes`** | Olay başlangıç zamanından önceki son Git commit'lerini şüpheli olarak işaretler. | `repo_path="."`, `incident_timestamp`, `lookback_hours=24` |
### Kaynaklar (Resources) ve İstem Şablonları (Prompts)
- **Resources:** `detective://sessions`, `detective://analysis/latest`, `detective://analysis/{analysis_id}`
- **Prompts:** `incident_postmortem`, `k8s_pod_triage`, `db_bottleneck_investigation`
---
## 🚀 Kurulum ve Çalıştırma
### 1. Repoyu Klonlayın ve `uv` (veya `pip`) ile Kurun
```bash
git clone https://github.com/tarihte1110/mcp-root-cause-detective.git
cd mcp-root-cause-detective
# uv ile sanal ortam + bağımlılık kurulumu
uv sync --extra dev
# veya klasik pip ile:
python -m venv .venv
source .venv/bin/activate # Windows için: .venv\Scripts\activate
pip install -e ".[dev]"
```
### 2. MCP İstemcinize Ekleyin
#### Cursor (`.cursor/mcp.json` veya `~/.cursor/mcp.json`)
```json
{
"mcpServers": {
"root-cause-detective": {
"command": "/tam/yol/mcp-root-cause-detective/.venv/bin/mcp-root-cause-detective",
"args": ["--allowed-roots", "/var/log", "/app/logs"]
}
}
}
```
#### Claude Desktop (`claude_desktop_config.json`)
```json
{
"mcpServers": {
"root-cause-detective": {
"command": "uv",
"args": [
"--directory",
"/tam/yol/mcp-root-cause-detective",
"run",
"mcp-root-cause-detective"
]
}
}
}
```
### 3. Uzak Sunucu (`streamable-http`) veya Docker ile Çalıştırma
```bash
# Streamable HTTP modu
mcp-root-cause-detective --transport streamable-http --host 127.0.0.1 --port 8000 --allowed-roots ./logs
# Docker ile çalıştırma
docker build -t mcp-root-cause-detective .
docker run -p 8000:8000 -v /var/log:/logs:ro -e MCP_RCA_ALLOWED_ROOTS=/logs mcp-root-cause-detective
```
---
## 🔐 Güvenlik Seçenekleri
- **`--allowed-roots <dizin1> <dizin2>` (veya `MCP_RCA_ALLOWED_ROOTS`):** Dosya okuma ve `git log` erişimini yalnızca izin verilen dizinlerle sınırlar (path traversal koruması).
- **Otomatik Secret & PII Maskeleme:** Varsayılan olarak aktiftir. Yalnızca yerel güvendiğiniz testlerde kapatmak isterseniz `--no-redact` bayrağını kullanabilirsiniz.
---
## 🧪 Test, Lint ve MCP Inspector
```bash
# Tüm birim ve entegrasyon testlerini çalıştır
uv run pytest -v
# Statik kod kontrolü
uv run ruff check src tests
# Tarayıcı üzerinden interaktif MCP testi
npx @modelcontextprotocol/inspector mcp-root-cause-detective
```
---
## 📄 Lisans
Bu proje [MIT Lisansı](LICENSE) altında lisanslanmıştır.
TDQS
Scored across 8 tools
Each tool has a distinct role: three analyze_* tools are separated by evidence source (files, Docker, Kubernetes), and the remaining tools map to clear drill-down actions such as error cluster inspection, request tracing, timeline slicing, raw stacktrace parsing, and Git correlation. The only potential overlap—analyze_log_files vs. diagnose_raw_stacktrace—is resolved by input type (log files vs. pasted stacktrace).
All tool names use snake_case and begin with a verb, predominantly following a verb_noun pattern. The analyze_* family is consistent, and the drill-down tools are equally predictable.
Eight tools are well scoped for a root-cause investigation server: three source collectors, three focus/drill-down tools, one raw stacktrace parser, and one Git correlation tool. No tool appears redundant, and the set is neither too thin nor too heavy.
The surface covers the major evidence sources and follow-up analysis steps—log files, containers, Kubernetes, stacktraces, error clusters, request flows, timeline slices, and Git changes—forming a coherent investigation loop. Minor gaps remain, such as no generic keyword search or report/export operation, but agents can work around these using the existing analyze_* and timeline tools.