{
  "markdown": "<div align=\"center\">\n\n# Context-First MCP\n\n**The MCP server that keeps your AI grounded, coherent, and honest — across every turn.**\n\n[![npm version](https://img.shields.io/npm/v/context-first-mcp?color=blue)](https://www.npmjs.com/package/context-first-mcp)\n[![npm downloads](https://img.shields.io/npm/dm/context-first-mcp?color=brightgreen)](https://www.npmjs.com/package/context-first-mcp)\n[![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE)\n[![MCP Compatible](https://img.shields.io/badge/MCP-compatible-purple)](https://modelcontextprotocol.io)\n[![Smithery](https://img.shields.io/badge/Smithery-listed-orange)](https://smithery.ai)\n[![Glama](https://glama.ai/mcp/servers/badge)](https://glama.ai/mcp/servers)\n[![Node ≥18](https://img.shields.io/badge/node-%3E%3D18-blue)](https://nodejs.org)\n[![TypeScript](https://img.shields.io/badge/built%20with-TypeScript-3178c6)](https://www.typescriptlang.org)\n\n```bash\nnpx context-first-mcp\n```\n\n*Works instantly with Claude Desktop · Cursor · VS Code · any MCP client · Vercel remote — zero API keys needed.*\n\n</div>\n\n---\n\n> **37 research-backed tools** across 7 layers — context health, state, sandboxing, persistent memory, advanced reasoning, truthfulness verification, orchestration, structured research, and autonomous file export. One `context_loop` call replaces 6–7 individual tools and returns a unified action directive.\n\n---\n\n## Why Your AI Conversations Break Down\n\nLong AI conversations fail in predictable ways. Context-First fixes all four:\n\n| Failure Mode | What Goes Wrong | Context-First Solution |\n|---|---|---|\n| **Context Drift** | AI forgets earlier decisions and intent as the conversation grows | `context_loop` + `detect_drift` continuously re-anchor every turn |\n| **Silent Contradiction** | New inputs silently overrule established facts — the AI doesn't notice | `detect_conflicts` compares every input against locked ground truth |\n| **Vague Execution** | AI proceeds on underspecified requirements, producing misaligned output | `check_ambiguity` + `abstention_check` ask clarifying questions instead of guessing |\n| **Hallucinated Success** | Tool outputs *look* successful but didn't actually achieve the goal | `verify_execution` rechecks whether the outcome matches the stated intent |\n\n---\n\n## What You Get\n\n**37 production-ready tools** grouped into 7 layers — plus 1 orchestrator that runs them all:\n\n```\ncontext_loop  ─────────────────────────────────────────────────────────────────\n  ├─ Layer 1 · Context Health   (9 tools)   recap, conflict, ambiguity, depth …\n  ├─ Layer 2 · Sandbox          (3 tools)   discover_tools, quarantine, merge\n  ├─ Layer 3 · Persistent Memory(6 tools)   store, recall, compact, graph …\n  ├─ Layer 4 · Advanced Reasoning(5 tools)  InftyThink, Coconut, KAG, MindEvo …\n  ├─ Layer 5 · Truthfulness     (7 tools)   NCB, IOE, verify_first, self_critique…\n  └─ State + Research Pipeline + Export     (7 tools)\n```\n\n**One call. One directive. One score.**\n\n```json\n{\n  \"directive\": {\n    \"action\": \"clarify\",\n    \"contextHealth\": 0.62,\n    \"instruction\": \"Resolve with the user: (1) Is this a firm requirement? (2) Which framework?\",\n    \"autoExtractedFacts\": { \"deploy_to\": \"Vercel\" },\n    \"suggestedNextTools\": [\"verify_execution\", \"quarantine_context\"]\n  }\n}\n```\n\n---\n\n## Quick Start\n\n### npx — zero install\n\n```bash\nnpx context-first-mcp\n```\n\n### Claude Desktop\n\n```json\n{\n  \"mcpServers\": {\n    \"context-first\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"context-first-mcp\"]\n    }\n  }\n}\n```\n\n### Cursor / VS Code\n\n```json\n{\n  \"mcp\": {\n    \"servers\": {\n      \"context-first\": {\n        \"command\": \"npx\",\n        \"args\": [\"-y\", \"context-first-mcp\"]\n      }\n    }\n  }\n}\n```\n\n### Remote (Streamable HTTP)\n\n```json\n{\n  \"mcpServers\": {\n    \"context-first\": {\n      \"url\": \"https://context-first-mcp.vercel.app/api/mcp\"\n    }\n  }\n}\n```\n\n### Deploy your own Vercel instance\n\n[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/XJTLUmedia/Context-First-MCP&root-directory=packages/remote-server)\n\n---\n\n## Tool Reference\n\n### Layer 1: Core Context Health (9 tools)\n\n| Tool | Purpose |\n|------|---------|\n| `context_loop` | **One-call orchestrator.** Runs 8 stages (ingest→recap→conflict→ambiguity→entropy→abstention→discovery→synthesis) and returns a single `directive` with `action`, `contextHealth` score, extracted facts, and suggested next tools |\n| `recap_conversation` | Extracts hidden intent, key decisions, and produces consolidated state summaries |\n| `detect_conflicts` | Compares new input against ground truth; surfaces contradictions |\n| `check_ambiguity` | Identifies underspecified requirements and generates clarifying questions |\n| `verify_execution` | Validates whether tool outputs actually achieved the stated goal |\n| `entropy_monitor` | Proxy-entropy scoring via lexical diversity, contradiction density, hedge frequency, and n-gram repetition (ERGO) |\n| `abstention_check` | 5-dimension confidence scoring — abstains with questions rather than hallucinating (RLAAR) |\n| `detect_drift` | Detects conversation drift from the original intent |\n| `check_depth` | Evaluates response depth against question complexity |\n\n### Layer 1b: State Management (4 tools)\n\n| Tool | Purpose |\n|------|---------|\n| `get_state` | Retrieve confirmed facts and task status |\n| `set_state` | Lock in ground truth — subsequent conflict checks run against these values |\n| `clear_state` | Reset specific keys or all state |\n| `get_history_summary` | Compressed conversation history with intent annotations |\n\n### Layer 2: Sandbox & Discovery (3 tools)\n\n| Tool | Method | Purpose |\n|------|--------|---------|\n| `discover_tools` | MCP-Zero + ScaleMCP | Natural-language tool routing — returns only semantically relevant tools, reducing context bloat by up to 98% |\n| `quarantine_context` | Multi-Agent Quarantine | Create isolated memory silos for sub-tasks, preventing intent dilution |\n| `merge_quarantine` | Multi-Agent Quarantine | Merge silo results with noise filtering — only promoted keys return to main context |\n\n### Layer 3: Persistent Memory (6 tools)\n\n| Tool | Purpose |\n|------|---------|\n| `memory_store` | Store findings, decisions, and intermediate results with metadata |\n| `memory_recall` | Retrieve relevant memories by semantic query |\n| `memory_compact` | Compress and consolidate memory entries |\n| `memory_graph` | Build and query a knowledge graph from stored memories |\n| `memory_inspect` | Inspect memory store contents and statistics |\n| `memory_curate` | Deduplicate and organize memory entries |\n\n### Layer 4: Advanced Reasoning (5 tools)\n\n| Tool | Method | Purpose |\n|------|--------|---------|\n| `inftythink_reason` | InftyThink | Infinite-depth reasoning with adaptive stopping |\n| `coconut_reason` | Coconut | Chain-of-Continuous-Thought in latent space |\n| `extracot_compress` | ExtraCoT | Compress chain-of-thought while preserving reasoning fidelity |\n| `mindevolution_solve` | MindEvolution | Evolutionary search over the solution space |\n| `kagthinker_solve` | KAG-Thinker | Knowledge-augmented generation with structured thinking |\n\n### Layer 5: Truthfulness & Verification (7 tools)\n\n| Tool | Purpose |\n|------|---------|\n| `probe_internal_state` | Probe model consistency across paraphrased prompts |\n| `detect_truth_direction` | Detect whether model reasoning is trending toward or away from truth |\n| `ncb_check` | Neighborhood consistency check across semantically equivalent inputs |\n| `check_logical_consistency` | Verify logical coherence of reasoning chains |\n| `verify_first` | Pre-verification before committing to claims |\n| `ioe_self_correct` | Intrinsic-extrinsic self-correction |\n| `self_critique` | Structured self-critique with improvement suggestions |\n\n### Research Pipeline & Export (2 tools)\n\n| Tool | Purpose |\n|------|---------|\n| `research_pipeline` | Structured research orchestration across `init → gather → analyze → verify → finalize`. Covers all 34 underlying tool-equivalents — state, sandboxing, memory, reasoning, truthfulness, context health. **Writes files autonomously to disk** as the pipeline runs; no LLM cooperation needed for file output. |\n| `export_research_files` | Writes every verified report chunk and/or every raw evidence batch to disk in a single call. |\n\n---\n\n## Built on Peer-Reviewed Research\n\nEvery core algorithm traces back to a published paper:\n\n| Algorithm | Paper | arXiv | Tool |\n|-----------|-------|-------|------|\n| MCP-Zero | Active Tool Request | [2506.01056](https://arxiv.org/abs/2506.01056) | `discover_tools` |\n| ScaleMCP | Semantic Tool Grouping | [2505.06416](https://arxiv.org/abs/2505.06416) | `discover_tools` registry |\n| ERGO | Entropy-based Quality | [2510.14077](https://arxiv.org/abs/2510.14077) | `entropy_monitor` |\n| RLAAR | Calibrated Abstention | [2510.18731](https://arxiv.org/abs/2510.18731) | `abstention_check` |\n\n**Implementation highlights:**\n- **Proxy Entropy (ERGO):** 4 response-level proxy signals (lexical diversity, contradiction density, hedge-word frequency, n-gram repetition) replace inaccessible token-level logprobs. Composite score above threshold triggers adaptive context reset.\n- **TF-IDF Discovery (MCP-Zero):** Pure TypeScript, zero external dependencies. Indexes all tool descriptions at startup; cosine similarity routes queries to the top-k relevant tools only.\n- **Inference-Time Abstention (RLAAR):** 5-dimension confidence scoring replaces the RL training loop. Abstains with targeted questions when confidence < threshold — no hallucination fallback.\n\n### Export Helper (1 tool)\n\n| Tool | Description |\n|------|-------------|\n| `export_research_files` | Writes research artifacts directly to disk. It can automatically expand and write every verified report chunk without asking the LLM to loop `finalize` manually, and it can also write every gathered raw-evidence batch even when `verify` has not passed. |\n\n#### context_loop Pipeline\n\n```\ncontext_loop (single MCP tool call)\n├── Stage 1: INGEST     — Store messages to session history\n├── Stage 2: RECAP      — Extract intents, decisions, summaries\n├── Stage 3: CONFLICT   — Detect contradictions against ground truth\n├── Stage 4: AMBIGUITY  — Check for underspecified requirements\n├── Stage 5: ENTROPY    — Monitor output quality degradation (ERGO)\n├── Stage 6: ABSTENTION — Multi-dimensional confidence check (RLAAR)\n├── Stage 7: DISCOVERY  — Suggest relevant next tools (MCP-Zero)\n└── Stage 8: SYNTHESIS   — Combine signals → action recommendation + LLM directive\n```\n\n**Synthesis Priority:** `abstain` > `reset` > `clarify` > `proceed`\n\nEach stage runs with independent error isolation — a failure in one stage doesn't block the others. The result includes per-stage timing, status, and detailed results for observability.\n\n#### LLM Directive (NEW)\n\nThe `context_loop` response includes a top-level `directive` object designed for LLM consumption — a compact, actionable instruction that replaces the need to parse nested stage results:\n\n```json\n{\n  \"directive\": {\n    \"action\": \"clarify\",\n    \"instruction\": \"Before proceeding, resolve these issues with the user:\\n1. Could you specify exactly what you mean?\\n2. Is this a firm requirement or still open for discussion?\",\n    \"questions\": [\"Could you specify exactly what you mean?\", \"Is this a firm requirement?\"],\n    \"contextHealth\": 0.62,\n    \"autoExtractedFacts\": { \"framework\": \"React\", \"deploy_to\": \"Vercel\" },\n    \"suggestedNextTools\": [\"verify_execution\", \"quarantine_context\"]\n  }\n}\n```\n\n---\n\n## How `context_loop` Works\n\n```\ncontext_loop (single MCP tool call)\n├── Stage 1: INGEST     — Store messages to session history\n├── Stage 2: RECAP      — Extract intents, decisions, summaries\n├── Stage 3: CONFLICT   — Detect contradictions against ground truth\n├── Stage 4: AMBIGUITY  — Check for underspecified requirements\n├── Stage 5: ENTROPY    — Monitor output quality degradation (ERGO)\n├── Stage 6: ABSTENTION — Multi-dimensional confidence check (RLAAR)\n├── Stage 7: DISCOVERY  — Suggest relevant next tools (MCP-Zero)\n└── Stage 8: SYNTHESIS  — Combine signals → action + directive\n```\n\n**Synthesis priority:** `abstain` > `reset` > `clarify` > `proceed`\n\nEach stage runs with independent error isolation. The `directive` response field carries everything an LLM needs:\n\n| Field | Description |\n|-------|-------------|\n| `action` | `proceed` · `clarify` · `reset` · `abstain` |\n| `instruction` | Plain-language guidance for the LLM's next step |\n| `questions` | Aggregated clarifying questions (ambiguity + abstention + conflicts) |\n| `contextHealth` | 0–1 composite score. 1 = healthy, 0 = degraded |\n| `autoExtractedFacts` | Key-value facts auto-extracted from user messages and stored as ground truth |\n| `suggestedNextTools` | Relevant tools the LLM should consider next |\n\n**Smart defaults:** `currentInput` is auto-inferred from the last user message. Facts like \"use React\" are extracted and stored automatically.\n\n---\n\n## Usage Protocol: Getting the Most from Context-First\n\n> **The #1 mistake:** LLMs treat `context_loop` as optional. It's not — it's the backbone.\n\n### Built-in Enforcement (v1.2.1+)\n\nThe server ships with four compliance mechanisms that require zero configuration:\n\n1. **Server Instructions** — Full usage protocol injected at MCP handshake via `ServerOptions.instructions`\n2. **Bootstrap Gate** — First non-`context_loop` call appends a strong redirect reminder\n3. **Cross-Tool Reminders** — After 3 consecutive calls without `context_loop`, reminders appear in tool responses\n4. **MCP Prompts** — `context-first-protocol` and `research-protocol` prompt templates available on demand\n\n### Reinforce in Your System Prompt (Optional)\n\n```\nWhen using Context-First MCP:\n1. Call context_loop BEFORE any complex task\n2. Call context_loop every 2–3 tool calls\n3. Call context_loop AFTER generating long-form output\n4. ALWAYS follow directive.action (proceed/clarify/reset/abstain/deepen/verify)\n5. Use memory_store to save findings; memory_recall to retrieve them\n```\n\n### Research Task Workflow\n\n`research_pipeline` orchestrates memory, phase control, reasoning, and autonomous file writing. It is not a web crawler — bring your own sources from web search, GitHub, fetch tools, PDFs, or any other MCP.\n\n```\nPhase 1 · Init     research_pipeline(init) → sets up state, enables autonomous file writing\nPhase 2 · Gather   ONE web search → research_pipeline(gather) → file written to disk → repeat\nPhase 3 · Analyze  research_pipeline(analyze) → reasoning engines produce clean analysis file\nPhase 4 · Verify   research_pipeline(verify) → context health gate (non-blocking)\nPhase 5 · Finalize research_pipeline(finalize) → synthesis.md + all batch files on disk\n\nAutomation shortcut:\n  export_research_files(outputDir, exportVerifiedReport=true)  → write all report chunks\n  export_research_files(outputDir, exportRawEvidence=true)     → write all evidence batches\n```\n\n**Autonomous file writing is always on.** Files are written to `./context-first-research-output/` by default — no LLM cooperation required. Pass `outputDir` to override.\n\n---\n\n## Architecture\n\n```\n┌──────────────────────────────────────────────────────────────┐\n│               @xjtlumedia/context-first-mcp-server            │\n│                     (Core — shared logic)                     │\n│                                                               │\n│  Layer 1: Context Health    (9 tools)                         │\n│  Layer 2: Sandbox           (3 tools)                         │\n│  Layer 3: Persistent Memory (6 tools)                         │\n│  Layer 4: Advanced Reasoning(5 tools)                         │\n│  Layer 5: Truthfulness      (7 tools)                         │\n│  State (4) · Orchestrator · Pipeline · Export                 │\n└──────────────┬───────────────────────┬──────────────────────┘\n               │                       │\n        ┌──────▼──────┐         ┌──────▼────────┐\n        │ stdio-server │         │ remote-server │\n        │ (npx local)  │         │   (Vercel)    │\n        │   stdio      │         │ Streamable    │\n        │  37 tools    │         │    HTTP       │\n        └──────────────┘         │   37 tools    │\n                                 └───────────────┘\n```\n\n- **Core library** (`@xjtlumedia/context-first-mcp-server`): All tool implementations. Zero external API keys — heuristic-based by default.\n- **stdio-server** (`context-first-mcp`): `npx` entry point, stdio transport, 37 tools.\n- **remote-server**: Vercel serverless, Streamable HTTP transport, 37 tools.\n\n---\n\n## Frontend Demo\n\nTry all 37 tools live in your browser at **[context-first-mcp.vercel.app](https://context-first-mcp.vercel.app)**.\n\n---\n\n## Development\n\n```bash\ngit clone https://github.com/XJTLUmedia/Context-First-MCP.git\ncd Context-First-MCP\npnpm install\n\n# Build everything\npnpm build\n\n# Run stdio server\ncd packages/stdio-server && pnpm start\n\n# Run frontend\ncd packages/frontend && pnpm dev\n\n# Tests\npnpm test\n```\n\n## Contributing\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md).\n\n## License\n\n[MIT](LICENSE)\n\n---\n\n<div align=\"center\">\n\n**Context-First MCP** · [@xjtlumedia/context-first-mcp-server](https://www.npmjs.com/package/@xjtlumedia/context-first-mcp-server) · [context-first-mcp](https://www.npmjs.com/package/context-first-mcp)\n\n*Built for every developer tired of watching their AI lose the plot.*\n\n</div>\n",
  "bytes": 17408,
  "sha": "c493c47856ec3a31051905042b84387023faa10db508dc668ee1a7ff0858003c",
  "repo_slug": "xjtlumedia/context-first-mcp",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_xjtlumedia_context_first_mcp_3851cb4f/readme"
}