mcpField
C
Context Rot Detection

Context Rot Detection

Local
github.com/milos-product-makerAI & Agents13Updated 36w ago

About Context Rot Detection

An MCP service that assesses AI agent context health using token use, retrieval accuracy, tool-call burden, and session duration. It supports curated models and HuggingFace models, and provides health history and recovery guidance.

Key features

  1. 01Context health score from 0–100
  2. 02Model-specific degradation curves
  3. 03HuggingFace context-window resolution
  4. 04Lost-in-the-middle risk assessment
  5. 05Agent history and service statistics
  6. 06Context recovery recommendations

Use cases

  1. 01Monitor context quality in long sessions
  2. 02Check agent health before critical decisions
  3. 03Assess context risk across models
  4. 04Review health changes for a specific agent

MCP support

The MCP server exposes context-health checks, history lookup, and service statistics to clients. Checks can be tracked by agent ID; HuggingFace model configuration is fetched from repositories and cached.

Configuration

Local server config is the same for every client. Copy it into your client’s MCP config file.

mcp.json · Universal config
{
"mcpServers": {
"context-rot-detection": {
"command": "npx",
"args": [
"-y",
"context-rot-detection"
],
"env": {
"HEALTH_HISTORY_DB": "<HEALTH_HISTORY_DB>"
}
}
}
}
Run commandnpx -y context-rot-detection
Environment variables to set
HEALTH_HISTORY_DB

Local servers need a runtime on your machine (e.g. Node.js 18+). Config file locations differ by client; see your client’s docs.

Packages
npmcontext-rot-detection

Tools

3

Saved tool list · updated 3w ago

ParameterTypeRequiredDescription
context_summarystringNoA brief summary of your current task and recent actions (the tool will analyze patterns, not raw context)
token_countintegerYesYour current estimated token count in context window
session_duration_minutesintegerNoHow long this session has been running
tool_calls_countintegerNoNumber of tool calls made in this session
modelstringNoThe LLM model you're running on. Known models with tuned profiles: claude-3.5-sonnet, claude-3.7-sonnet, claude-sonnet-4, claude-opus-4, claude-opus-4-5, claude-haiku-3.5, gpt-4o, gpt-4o-mini, gpt-4.1, gpt-4.1-mini, o3, o4-mini, gemini-2.0-flash, gemini-2.5-pro, gemini-2.5-flash. You can also pass a HuggingFace repo ID (e.g., "meta-llama/Llama-3.1-70B-Instruct") and the context window will be auto-detected. Any other string falls back to conservative defaults.
agent_idstringNoOptional unique identifier for this agent instance, used for health history tracking

Details

From the project README

Context Rot Detection

MCP service that gives AI agents self-awareness about their cognitive state.

Every long-running AI agent suffers from context rot — measurable performance degradation as the context window fills up. Research from Chroma, Stanford ("lost-in-the-middle"), and Redis confirms this is the #1 practical failure mode in production agent systems.

An agent experiencing context rot doesn't know it's degrading — it just starts making worse decisions. This tool gives agents real-time visibility into their own cognitive health.

Features

  • Health score (0–100) based on token utilization, retrieval accuracy, and session fatigue
  • Model-specific degradation curves for 15+ curated models (Claude, GPT, Gemini, o-series)
  • Auto-resolves any HuggingFace model — pass a repo ID like meta-llama/Llama-3.1-70B and the context window is detected automatically, with results cached in SQLite
  • Lost-in-the-middle risk scoring based on Stanford research
  • Tool-call burden and session fatigue analysis
  • Actionable recovery recommendations — compact context, offload to memory, checkpoint, break into subtasks
  • Per-agent health history tracking (SQLite)
  • Service-wide utilization statistics

Quick Start

npx (zero install)
npx context-rot-detection
npm (global install)
npm install -g context-rot-detection
context-rot-detection

MCP Client Configuration

Claude Code

Add to .mcp.json in your project root:

{
  "mcpServers": {
    "context-rot-detection": {
      "command": "npx",
      "args": ["-y", "context-rot-detection"],
      "env": {
        "HEALTH_HISTORY_DB": "./health.db"
      }
    }
  }
}
Claude Desktop

Add to claude_desktop_config.json:

{
  "mcpServers": {
    "context-rot-detection": {
      "command": "npx",
      "args": ["-y", "context-rot-detection"],
      "env": {
        "HEALTH_HISTORY_DB": "/path/to/health.db"
      }
    }
  }
}
Docker
{
  "mcpServers": {
    "context-rot-detection": {
      "command": "docker",
      "args": [
        "run", "-i", "--rm",
        "-v", "context-rot-data:/data",
        "ghcr.io/milos-product-maker/context-rot-detection:latest"
      ]
    }
  }
}

Configuration

Environment VariableDescriptionDefault
HEALTH_HISTORY_DBPath to SQLite database for health history. Use :memory: for ephemeral storage.:memory:
LOG_FILEPath to append structured JSON log lines. Omit to disable file logging.(none)

Tools

check_my_health

Analyze the current context window health. Call this periodically during long sessions or before critical decisions.

Parameters:

ParameterTypeRequiredDescription
token_countintegerYesCurrent estimated token count in context window
modelstringNoLLM model identifier — a curated name (e.g., claude-opus-4, gpt-4o), a HuggingFace repo ID (e.g., meta-llama/Llama-3.1-70B), or any string (falls back to conservative defaults)
session_duration_minutesintegerNoHow long this session has been running
tool_calls_countintegerNoNumber of tool calls made in this session
context_summarystringNoBrief summary of current task and recent actions
agent_idstringNoUnique agent identifier for history tracking

Example response:

{
  "health_score": 62,
  "status": "warning",
  "token_utilization": {
    "current": 155000,
    "max_effective": 170000,
    "percentage": 91.2,
    "danger_zone_starts_at": 170000
  },
  "quality_estimate": {
    "retrieval_accuracy": "degrading",
    "middle_content_risk": "high",
    "estimated_hallucination_risk": "moderate"
  },
  "session_fatigue": {
    "tool_call_burden": "moderate",
    "session_length_risk": "low",
    "recommendation": "Consider breaking into sub-tasks if complexity increases."
  },
  "recommendations": [
    {
      "priority": "high",
      "action": "compact_context",
      "reason": "You are approaching the effective quality threshold. Summarize older context and remove completed task details.",
      "estimated_quality_gain": 15
    },
    {
      "priority": "high",
      "action": "offload_to_memory",
      "reason": "High risk of lost-in-the-middle effect. Store critical information to external memory before it is effectively lost.",
      "estimated_quality_gain": 8
    }
  ]
}
get_health_history

Retrieve health check history for a specific agent.

Parameters:

ParameterTypeRequiredDescription
agent_idstringYesUnique agent identifier
limitintegerNoMax records to return (default: 20, max: 100)
get_service_stats

Get service-wide utilization statistics. No parameters required.

Returns total calls, unique agents, average health score, model distribution, status distribution, and recent activity (last hour / last 24h).

Supported Models

ModelMax TokensDanger ZoneMiddle-Loss Risk
claude-opus-4-5200K175KLow
claude-opus-4200K170KLow
claude-sonnet-4200K165KLow
claude-3.7-sonnet200K160KLow–Medium
claude-3.5-sonnet200K152KMedium
claude-haiku-3.5200K130KMedium
gpt-4.11M500KMedium
gpt-4.1-mini1M450KMedium
gpt-4o128K105KMedium
gpt-4o-mini128K95KMedium–High
o3200K160KLow–Medium
o4-mini200K150KMedium
gemini-2.5-pro1M600KMedium
gemini-2.5-flash1M520KMedium–High
gemini-2.0-flash1M500KHigh
HuggingFace Auto-Resolution

Any model string containing / is treated as a HuggingFace repo ID. The server fetches config.json from the repo, extracts the context window size (max_position_embeddings, n_positions, or max_seq_len), and generates a conservative degradation profile:

  • 65% of max tokens → degradation onset
  • 80% of max tokens → danger zone

Results are cached in SQLite — subsequent lookups are instant.

model: "meta-llama/Llama-3.1-70B"       → 131K context, danger at 105K
model: "mistralai/Mistral-7B-v0.1"      → 32K context, danger at 26K
model: "mosaicml/mpt-7b"                → 65K context, danger at 52K

If the fetch fails (network error, gated model, missing config), the server falls back silently to conservative defaults.

Fallback

Any unrecognized model string without / falls back to conservative defaults (128K max, 100K danger zone).

How It Works

The health score is a weighted composite of four signals:

SignalWeightSource
Token utilization quality40%Model-specific sigmoid degradation curve
Retrieval accuracy25%Base accuracy minus lost-in-the-middle penalty
Tool-call burden20%Compounding quality loss after 10+ tool calls
Session length15%Time-based fatigue heuristic

The degradation curves are derived from empirical research:

Development

git clone https://github.com/milos-product-maker/context-rot-detection.git
cd context-rot-detection
npm install
npm run dev        # Run with tsx (hot reload)
npm test           # Run unit tests
npm run build      # Compile TypeScript
Testing with MCP Inspector
npx @modelcontextprotocol/inspector node dist/index.js

License

MIT

Comments

Markdown supported

New to MCP?

From what the protocol is to installing your first server, these answers cover most first questions.

An open protocol that defines how AI applications connect to external tools and data in a uniform way. Clients talk to the model; MCP servers provide tools, resources and prompt templates. They exchange standard messages, so one server can be reused by many clients.