Skip to main content
Glama
DevContext

DevContext

by sid-stack001
README.md
# DevContext


![Python](https://img.shields.io/badge/python-3.10%2B-blue?logo=python&logoColor=white)
![MCP](https://img.shields.io/badge/MCP-Model%20Context%20Protocol-purple)
![License: MIT](https://img.shields.io/badge/license-MIT-green)

> **DevContext is a prototype Model Context Protocol (MCP) server and CLI tool that provides AI coding assistants and engineers with runtime observability data (logs, deploys, and health metrics) to assist in incident triage.**

---

## Overview

Coding assistants can inspect source repositories and draft fixes, but they often lack visibility into what happens during runtime incidents (such as recent deployments, error rate spikes, disk saturation, or downstream API outages). DevContext is a proof-of-concept tool that exposes runtime context via a command-line interface (CLI) and standard MCP tool calls.

---

## CLI & Tool Commands

DevContext can be run directly from the command line or registered as an MCP server.

### 1. `devcontext diagnose`
Runs automated incident triage against built-in datasets or custom files/folders:
```bash
# Diagnose built-in service dataset
devcontext diagnose --service order-processing

# Output raw JSON format
devcontext diagnose --service order-processing --json

# Point at custom log, deploy, and health paths (files or log directories)
devcontext diagnose --log-path /var/log/app/ --deploys-path deploys.json --health-path health.json

# Enable optional OpenAI-compatible LLM log extraction
devcontext diagnose --service order-processing --use-llm
```

### 2. `devcontext serve`
Starts the stdio MCP server for connection to MCP hosts (e.g. Claude Desktop, Antigravity):
```bash
devcontext serve
```
<img width="1920" height="1080" alt="demo_devcontext" src="https://github.com/user-attachments/assets/aaad8db0-bfff-4301-ac6d-c825fbe08aa6" />




---

## Log Parsing Options

1. **Deterministic Parser (`parser.py`)**: Uses heuristics to sample log lines and attempt structure matching (JSON-lines, CSV, key-value pairs, or basic bracketed/space-delimited timestamps).
   - *Limitation*: Best suited for simple single-line logs. Complex multi-line stack traces or non-standard custom formats may fall back to basic line matching.
2. **Optional LLM Extraction (`extraction.py`)**: Optionally sends log chunks to an OpenAI-compatible API (`response_format={"type": "json_object"}`) to extract structured event objects.
   - *Limitation*: Incurs API latency (~200–400ms) and token costs; falls back to the deterministic parser if the API key is missing or calls time out.

---

## Data Source Options

- **Built-in Mock Data**: Pass a service name (e.g. `service_name="order-processing"`) to query the included demo data.
- **Custom File or Directory Paths**:
  - `log_path`: Path to a single log file or a directory containing split `.log` / `.txt` files.
  - `deploys_path`: Path to a custom `deploys.json` file.
  - `health_path`: Path to a custom `health.json` file.

---

## Benchmark

`eval.py` scores any diagnosis method against 50 scenarios: 5 handwritten (easy) and 45 generated by a seeded script (`benchmark/generate.py`). Scoring is strict: the predicted root-cause type must match ground truth, and for bad deploys the blamed commit must match too. There is no pass-by-default branch, and a crash counts as a failure.

```bash
python eval.py                    # all 50, rule-based method
python eval.py --set generated --verbose --json results/rule.json
```

Generated scenarios cover 5 root causes (bad deploy, disk, memory leak, downstream outage, DB connection pool) across variants:

| Variant | What it tests |
|---|---|
| `clean` | One clear signal, sparse logs |
| `noisy` | 300+ lines, benign WARNs right before the incident, decoy health metrics |
| `red_herring_deploy` | Unrelated deploy 2-8 minutes before a non-deploy incident |
| `delayed` | Bad deploy whose errors only start 25-90 minutes later |

Logs alternate between plain text and JSON-lines.

### Results: rule-based `diagnose()`

| Set | Accuracy |
|---|---|
| Handwritten (5) | 100% (5/5) |
| `clean` (15) | 80% (12/15) |
| `noisy` (15) | 40% (6/15) |
| `red_herring_deploy` (12) | 0% (0/12) |
| `delayed` (3) | 0% (0/3) |
| **Overall (50)** | **46% (23/50)** |

What this shows:
- **Deploy-blaming is too eager:** any deploy within 10 minutes of the first flagged line gets blamed, so an unrelated deploy beats clear disk, memory, or outage evidence (0/12).
- **Benign WARNs break correlation:** `first_error_timestamp` counts WARN lines, so a harmless warning before a deploy hides a real regression.
- **Keyword rules misfire:** a moderately high disk metric (86-89%) trips the disk branch on unrelated incidents.
- **No DB-pool rule exists:** all 9 connection-pool scenarios fail by design (0/9), a coverage gap rather than a bug.
- **The parser is not the bottleneck:** JSON-lines and plain text score the same within each variant.

### LLM Agent Methods & Evaluation Protocol

`agent.py` adds three LLM methods, all scored by the same strict, zero-pass-by-default benchmark harness. The LLM layer is provider-agnostic, using the `openai` SDK to connect to any OpenAI-compatible endpoint (e.g. self-hosted vLLM on Kaggle/local GPU, or cloud endpoints).

| Method | What it is |
|---|---|
| `llm_raw` | Baseline: last 150 log lines + deploys + health pasted into one prompt, no tools |
| `agent` | Investigator: tool-calling loop over the same `tools.py` functions (`get_recent_errors`, `get_recent_deploys`, `get_service_health`) that the MCP server exposes, ending in `submit_diagnosis` with quoted evidence |
| `agent_verified` | Two-stage Investigator + Verifier pipeline: adds a skeptical verifier pass that checks evidence grounding and can overturn the draft |

The investigator does NOT receive `diagnose()`, so it cannot echo the rule-based heuristic. During benchmarking (`eval.py`), tool calls invoke `tools.py` functions directly rather than going through the MCP stdio JSON-RPC transport.

#### Environment Variables
The LLM layer requires three environment variables (with a clear error naming any missing variable):
- `DEVCONTEXT_BASE_URL`: Base URL of the OpenAI-compatible endpoint (e.g. `http://localhost:8000/v1` for vLLM).
- `DEVCONTEXT_API_KEY`: API key for the endpoint (use `dummy` for local vLLM).
- `DEVCONTEXT_MODEL`: Model name (do not assume or hardcode; verify via `python eval.py --list-models`).

Optional configuration:
- `DEVCONTEXT_MIN_INTERVAL`: Optional delay in seconds between consecutive API calls to prevent rate limits.
- `DEVCONTEXT_CACHE`: Directory for cached responses (defaults to `.llm_cache/`). Cache keys include `base_url + model + prompt + tools`.

#### Evaluation Protocol
To maintain scientific and empirical rigor:
1. **Tune Prompts Only on Dev**: Tune system instructions and few-shot guidance strictly on `--split dev` (handwritten scenarios + seed 0).
2. **Freeze Prompts**: Once finalized, freeze all prompt templates.
3. **Evaluate on Test**: Run `--split test` (seeds 1 and 2, held out by generator seed while sharing generator templates and failure classes with `dev`) once per method with `--runs 3` to verify run-to-run consistency.
4. **Fair Comparison**: All methods (`llm_raw`, `agent`, `agent_verified`) must be evaluated against the exact same model and endpoint.
5. **Report Complete Metadata**: Every reported benchmark table must specify:
   - **Model Name**
   - **Provider / Serving Engine** (e.g. vLLM on Kaggle T4 GPU)
   - **Evaluation Date**
6. **No Hand Edits**: Benchmark results must be generated directly by `eval.py` without manual modification.

```bash
# Query available model IDs from the endpoint
python eval.py --list-models

# Run evaluation on test split (3 runs per scenario)
python eval.py --method llm_raw --runs 3 --split test --json results/llm_raw.json
python eval.py --method agent --runs 3 --split test --json results/agent.json
python eval.py --method agent_verified --runs 3 --split test --json results/agent_verified.json
```

---

### Running Rate-Limit-Free on Kaggle GPU with vLLM

To benchmark without API rate limits or commercial token costs, run on a Kaggle GPU (T4 x 2 or P100):

- **Script**: [`scripts/kaggle_vllm.sh`](scripts/kaggle_vllm.sh)
- **Notebook**: [`notebooks/kaggle_vllm.ipynb`](notebooks/kaggle_vllm.ipynb)

#### How It Works:
1. **Model Selection**: Uses `Qwen/Qwen2.5-7B-Instruct-AWQ` on Hugging Face (4-bit AWQ, ~5.3 GB VRAM weights). It fits easily on a 16GB Kaggle GPU with generous KV-cache headroom.
2. **vLLM Serving**: Starts an OpenAI-compatible server with native Hermes tool calling:
   ```bash
   vllm serve Qwen/Qwen2.5-7B-Instruct-AWQ \
       --quantization awq \
       --enable-auto-tool-choice \
       --tool-call-parser hermes \
       --port 8000
   ```
3. **Health Check Polling**: Waits for `http://127.0.0.1:8000/health` before initiating benchmark runs.
4. **Resumable Cache**: Restores any previously saved `.llm_cache/` from an attached Kaggle dataset (`/kaggle/input/**/.llm_cache`). If a 9-hour Kaggle GPU session times out, the next run resumes instantly from where it left off.
5. **Artifact Export**: Copies `.llm_cache/` and `results/` to `/kaggle/working` for persistence and dataset creation.

### Benchmark Results

**Model:** `Qwen/Qwen2.5-7B-Instruct-AWQ` (4-bit AWQ)  
**Serving Engine:** `vLLM 0.34.0` (`--max-model-len 16384` on Kaggle Tesla T4 GPU)  
**Split & Sample Size:** `test` split (30 scenarios, seeds 1–2; `--runs 3` at `temperature=0` produced identical predictions across repeats with `0/30` unstable scenarios, so effective `n = 30`)  
**Date:** December 2026 (`2026-12-04`)  

| Method | Test Accuracy (`n = 30`) | 95% Wilson CI | Crashes | Avg Tokens | Latency | Key Characteristics & Failure Modes |
|---|---|---|---|---|---|---|
| **`rule`** (Heuristic) | **40.0%** (`12/30`) | 24.6%–57.7% | 0 | 0 | <0.1s | 46.0% (`23/50`) across all 50 scenarios; 0% on red-herring deploys & DB-pool |
| **`llm_raw`** (Single-shot) | **83.3%** (`25/30`) | 66.4%–92.7% | 0 | 4,210 | 4.0s | 6/6 on `db_pool`, `disk`, `downstream_dependency`, `memory_leak`; weak on `bad_deploy` (**16.7%**, `1/6`) |
| **`agent`** (Investigator, tool layer) | **90.0%** (`27/30`) | 74.4%–96.5% | 0 | 3,304 | 13.7s | Invokes `tools.py` directly (same layer exposed by the MCP server); `bad_deploy` **66.7%** (`4/6`) |
| **`agent_verified`** (Investigator + Verifier pipeline) | **93.3%** (`28/30`) | **78.7%–98.2%** | 0 | 5,029 | 2.2s* | +1 scenario over `agent` (`db_pool__noisy__2`), **within noise at `n = 30`**; `bad_deploy` **66.7%** (`4/6`) |

*\*Latency reflects cached warm-run investigator calls plus uncached verifier passes; all 30 scenarios ran with 0 crashes under `--max-model-len 16384`.*

#### Detailed Breakdown by Incident Family & Stress Variant (`test` Split, `n = 30` Scenarios)

Because all 3 greedy (`temperature=0`) runs per scenario were identical (`0/30` unstable scenarios), counts below are reported per unique scenario (`n = 30`) so repeats are not double-counted as independent samples. `rule` is shown on the same 30 `test` scenarios for an apples-to-apples comparison.

```text
====================================================================================================
ACCURACY BREAKDOWN (Test Split: Seeds 1-2, n = 30 Unique Scenarios; 3 Deterministic Runs/Scenario)
====================================================================================================
Incident Family         rule (Test Split)   llm_raw (16k ctx)     agent (Tool Layer)   agent_verified (Pipeline)
----------------------------------------------------------------------------------------------------
bad_deploy                 33.3% (2/6)        16.7% (1/6)           66.7% (4/6)           66.7% (4/6)
db_pool                     0.0% (0/6)       100.0% (6/6)           83.3% (5/6)          100.0% (6/6)
disk                       66.7% (4/6)       100.0% (6/6)          100.0% (6/6)          100.0% (6/6)
downstream_dependency      33.3% (2/6)       100.0% (6/6)          100.0% (6/6)          100.0% (6/6)
memory_leak                66.7% (4/6)       100.0% (6/6)          100.0% (6/6)          100.0% (6/6)
----------------------------------------------------------------------------------------------------
Variant
----------------------------------------------------------------------------------------------------
clean                      80.0% (8/10)       80.0% (8/10)         100.0% (10/10)        100.0% (10/10)
delayed                     0.0% (0/2)        50.0% (1/2)           50.0% (1/2)           50.0% (1/2)
noisy                      40.0% (4/10)       80.0% (8/10)          80.0% (8/10)          90.0% (9/10)
red_herring_deploy          0.0% (0/8)       100.0% (8/8)          100.0% (8/8)          100.0% (8/8)
====================================================================================================
OVERALL (n = 30):          40.0% (12/30)      83.3% (25/30)         90.0% (27/30)         93.3% (28/30)
====================================================================================================
```

#### Core Insights, Weak Spots & Limitations:
1. **Honest Tool-Layer Gain (`agent` 90.0% vs `llm_raw` 83.3%) & Prompt Size**:
   With `--max-model-len 16384`, `llm_raw` had **0 crashes** and solved **24/24** non-deploy scenarios (`db_pool`, `disk`, `downstream_dependency`, `memory_leak`). The gap between `llm_raw` (**83.3%**) and `agent` (**90.0%**) comes from **`bad_deploy`** (**1/6** vs **4/6**), where calling `get_recent_deploys` lets the investigator inspect older deploys/diffs cleanly, and from keeping noisy prompts compact (**3,304** avg tokens vs **4,210** avg and **8,250–8,472** peak tokens for `llm_raw`).
2. **Weak Spot — `bad_deploy` Is Still at 66.7% (`4/6`)**:
   Both `agent` and `agent_verified` missed `bad_deploy__delayed__1` and `bad_deploy__noisy__1` (`delayed` variant overall is `1/2 = 50.0%`). Deployment attribution remains the hardest class.
3. **Investigator + Verifier Pipeline (`agent_verified` vs `agent`)**:
   In `agent`, `db_pool__noisy__2` was misclassified as `disk`, and `agent_verified`'s verifier pass overturned that draft to `db_pool`. On `n = 30`, however, a **1-scenario difference (`28/30` vs `27/30`, overlapping 95% Wilson CIs of `78.7%–98.2%` vs `74.4%–96.5%`) is within noise** and does not establish a statistically significant advantage.
4. **Scope & Generalization Limits**:
   The `test` split is **held out by generator seed only** (seeds 1–2 vs seed 0 + handwritten in `dev`). Both splits share the exact same synthetic generator templates and 5 root-cause classes, and the prompts in `agent.py` were written knowing those failure modes. Consequently, these numbers show that the model can use prompt hints and the diagnostic tools on synthetic logs with noise, delays, and red-herring deploys — **not** that it generalizes to real production incidents.

---

## Architecture

```text
┌─────────────────────────────────────────────────────────┐
│              CLI / MCP Clients                          │
│     (devcontext CLI / Claude Desktop / Antigravity)     │
└───────────────────────────┬─────────────────────────────┘
                            │ CLI Args / stdio JSON-RPC
┌───────────────────────────▼─────────────────────────────┐
│              DevContext Entry Point                     │
│               (cli.py / server.py)                      │
└───────────────────────────┬─────────────────────────────┘
                            │
┌───────────────────────────▼─────────────────────────────┐
│                 Diagnostic Core (tools.py)               │
└───────┬───────────────────┬─────────────────────┬───────┘
        │                   │                     │
┌───────▼───────────┐ ┌─────▼─────────────┐ ┌─────▼─────────────┐
│ Structure Parser  │ │ Deployment Engine │ │ Health Observer   │
│   (parser.py)     │ │ (deploys.json)    │ │ (health.json)     │
└───────┬───────────┘ └───────────────────┘ └───────────────────┘
        │
┌───────┴─────────────────────────────────────────┐
│  OpenAI-compatible API (Optional extraction)    │
└─────────────────────────────────────────────────┘
```

---

## Quickstart & Setup

### 1. Installation
```bash
git clone https://github.com/sid-stack001/devcontext.git
cd devcontext
pip install -e .
```

### 2. Diagnose a Service via CLI
```bash
devcontext diagnose --service order-processing
```

### 3. Register as an MCP Server (Claude Desktop)
Add DevContext to your `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "devcontext": {
      "command": "devcontext",
      "args": [
        "serve"
      ]
    }
  }
}
```

### 4. Run Tests and Benchmark
```bash
pip install -e .[dev]
pytest
python eval.py
```

### 5. Environment Configuration
Copy `.env.example` to `.env` to configure your OpenAI-compatible endpoint:
```bash
cp .env.example .env
```

---

## Dependencies & Requirements

- Python 3.10+
- `mcp` (Model Context Protocol SDK)
- `openai` (Provider-agnostic API client)
- `pytest` (Optional, for test execution)

---

## Future Extensions

- **Pluggable Adapters**: Connect directly to CloudWatch, Datadog, Grafana Loki, or Prometheus APIs.
- **Probabilistic Confidence Scores**: Output root-cause probability distributions (e.g. `95% confidence: bad deploy`) instead of single deterministic strings.
- **Automated Rollback Proposals**: Generate validated git revert commits or Kubernetes patch specs alongside the diagnosis.

---

## License

Distributed under the [MIT License](LICENSE).