Context-first
The Context-First MCP server maintains AI conversation integrity through 37 tools across 7 layers, preventing context drift, contradictions, ambiguity, and hallucinations. It requires zero API keys and deploys via npx, Claude Desktop, Cursor/VS Code, or a remote Vercel instance.
Core Orchestration
context_loop— Single-call orchestrator running 8 stages (ingest → recap → conflict → ambiguity → entropy → abstention → discovery → synthesis), returning a unified directive (proceed,clarify,reset,abstain) and a context health score (0–1).
Context Health (9 tools)
Recap conversations, detect silent contradictions, check ambiguity, verify tool execution, monitor output entropy, check abstention confidence across 5 dimensions, detect intent drift, check response depth, and verify grounding.
State Management (4 tools)
Lock in confirmed facts and decisions as ground truth (
set_state,get_state,clear_state) and retrieve compressed history summaries.
Sandbox & Discovery (3 tools)
Discover relevant tools via TF-IDF semantic search (reducing context bloat by up to 98%), quarantine isolated memory silos for sub-tasks, and merge results back with noise filtering.
Persistent Memory (6 tools)
Store, recall, compact, graph, inspect, and curate findings across a hierarchical memory system (scratchpad → working → episodic → semantic → graph → curation).
Advanced Reasoning (5 tools)
InftyThink (iterative bounded-segment reasoning), Coconut (continuous latent-space reasoning), ExtraCoT (reasoning chain compression), MindEvolution (evolutionary solution search), and KAG-Thinker (knowledge-augmented structured decomposition).
Truthfulness & Verification (7 tools)
Probe internal state, detect truth direction deviants, run neighborhood consistency checks (NCB), verify logical consistency, pre-verify candidate answers (
verify_first), apply confidence-based self-correction (ioe_self_correct, corrects only when confidence < 0.4), and run iterative self-critique cycles.
Research Pipeline & Export (2 tools)
research_pipeline— Multi-phase orchestration (init → gather → review → analyze → verify → finalize) with autonomous file writing, quality gates, and coverage tracking.export_research_files— Writes verified reports and raw evidence batches directly to disk without requiring manual LLM intervention.
Integrates with arXiv research papers as foundational algorithms for core tools, implementing peer-reviewed methods like ERGO for entropy monitoring, RLAAR for calibrated abstention, and MCP-Zero for semantic tool discovery.
Supports deployment of a remote MCP server instance on Vercel, enabling streamable HTTP access to all context management tools without local installation.
Context-First MCP
The MCP server that keeps your AI grounded, coherent, and honest — across every turn.
npx context-first-mcpWorks instantly with Claude Desktop · Cursor · VS Code · any MCP client · Vercel remote — zero API keys needed.
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_loopcall replaces 6–7 individual tools and returns a unified action directive.
Why Your AI Conversations Break Down
Long AI conversations fail in predictable ways. Context-First fixes all four:
Failure Mode | What Goes Wrong | Context-First Solution |
Context Drift | AI forgets earlier decisions and intent as the conversation grows |
|
Silent Contradiction | New inputs silently overrule established facts — the AI doesn't notice |
|
Vague Execution | AI proceeds on underspecified requirements, producing misaligned output |
|
Hallucinated Success | Tool outputs look successful but didn't actually achieve the goal |
|
Related MCP server: nautilus-compass
What You Get
37 production-ready tools grouped into 7 layers — plus 1 orchestrator that runs them all:
context_loop ─────────────────────────────────────────────────────────────────
├─ Layer 1 · Context Health (9 tools) recap, conflict, ambiguity, depth …
├─ Layer 2 · Sandbox (3 tools) discover_tools, quarantine, merge
├─ Layer 3 · Persistent Memory(6 tools) store, recall, compact, graph …
├─ Layer 4 · Advanced Reasoning(5 tools) InftyThink, Coconut, KAG, MindEvo …
├─ Layer 5 · Truthfulness (7 tools) NCB, IOE, verify_first, self_critique…
└─ State + Research Pipeline + Export (7 tools)One call. One directive. One score.
{
"directive": {
"action": "clarify",
"contextHealth": 0.62,
"instruction": "Resolve with the user: (1) Is this a firm requirement? (2) Which framework?",
"autoExtractedFacts": { "deploy_to": "Vercel" },
"suggestedNextTools": ["verify_execution", "quarantine_context"]
}
}Quick Start
npx — zero install
npx context-first-mcpClaude Desktop
{
"mcpServers": {
"context-first": {
"command": "npx",
"args": ["-y", "context-first-mcp"]
}
}
}Cursor / VS Code
{
"mcp": {
"servers": {
"context-first": {
"command": "npx",
"args": ["-y", "context-first-mcp"]
}
}
}
}Remote (Streamable HTTP)
{
"mcpServers": {
"context-first": {
"url": "https://context-first-mcp.vercel.app/api/mcp"
}
}
}Deploy your own Vercel instance
Tool Reference
Layer 1: Core Context Health (9 tools)
Tool | Purpose |
| One-call orchestrator. Runs 8 stages (ingest→recap→conflict→ambiguity→entropy→abstention→discovery→synthesis) and returns a single |
| Extracts hidden intent, key decisions, and produces consolidated state summaries |
| Compares new input against ground truth; surfaces contradictions |
| Identifies underspecified requirements and generates clarifying questions |
| Validates whether tool outputs actually achieved the stated goal |
| Proxy-entropy scoring via lexical diversity, contradiction density, hedge frequency, and n-gram repetition (ERGO) |
| 5-dimension confidence scoring — abstains with questions rather than hallucinating (RLAAR) |
| Detects conversation drift from the original intent |
| Evaluates response depth against question complexity |
Layer 1b: State Management (4 tools)
Tool | Purpose |
| Retrieve confirmed facts and task status |
| Lock in ground truth — subsequent conflict checks run against these values |
| Reset specific keys or all state |
| Compressed conversation history with intent annotations |
Layer 2: Sandbox & Discovery (3 tools)
Tool | Method | Purpose |
| MCP-Zero + ScaleMCP | Natural-language tool routing — returns only semantically relevant tools, reducing context bloat by up to 98% |
| Multi-Agent Quarantine | Create isolated memory silos for sub-tasks, preventing intent dilution |
| Multi-Agent Quarantine | Merge silo results with noise filtering — only promoted keys return to main context |
Layer 3: Persistent Memory (6 tools)
Tool | Purpose |
| Store findings, decisions, and intermediate results with metadata |
| Retrieve relevant memories by semantic query |
| Compress and consolidate memory entries |
| Build and query a knowledge graph from stored memories |
| Inspect memory store contents and statistics |
| Deduplicate and organize memory entries |
Layer 4: Advanced Reasoning (5 tools)
Tool | Method | Purpose |
| InftyThink | Infinite-depth reasoning with adaptive stopping |
| Coconut | Chain-of-Continuous-Thought in latent space |
| ExtraCoT | Compress chain-of-thought while preserving reasoning fidelity |
| MindEvolution | Evolutionary search over the solution space |
| KAG-Thinker | Knowledge-augmented generation with structured thinking |
Layer 5: Truthfulness & Verification (7 tools)
Tool | Purpose |
| Probe model consistency across paraphrased prompts |
| Detect whether model reasoning is trending toward or away from truth |
| Neighborhood consistency check across semantically equivalent inputs |
| Verify logical coherence of reasoning chains |
| Pre-verification before committing to claims |
| Intrinsic-extrinsic self-correction |
| Structured self-critique with improvement suggestions |
Research Pipeline & Export (2 tools)
Tool | Purpose |
| Structured research orchestration across |
| Writes every verified report chunk and/or every raw evidence batch to disk in a single call. |
Built on Peer-Reviewed Research
Every core algorithm traces back to a published paper:
Algorithm | Paper | arXiv | Tool |
MCP-Zero | Active Tool Request |
| |
ScaleMCP | Semantic Tool Grouping |
| |
ERGO | Entropy-based Quality |
| |
RLAAR | Calibrated Abstention |
|
Implementation highlights:
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.
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.
Inference-Time Abstention (RLAAR): 5-dimension confidence scoring replaces the RL training loop. Abstains with targeted questions when confidence < threshold — no hallucination fallback.
Export Helper (1 tool)
Tool | Description |
| Writes research artifacts directly to disk. It can automatically expand and write every verified report chunk without asking the LLM to loop |
context_loop Pipeline
context_loop (single MCP tool call)
├── Stage 1: INGEST — Store messages to session history
├── Stage 2: RECAP — Extract intents, decisions, summaries
├── Stage 3: CONFLICT — Detect contradictions against ground truth
├── Stage 4: AMBIGUITY — Check for underspecified requirements
├── Stage 5: ENTROPY — Monitor output quality degradation (ERGO)
├── Stage 6: ABSTENTION — Multi-dimensional confidence check (RLAAR)
├── Stage 7: DISCOVERY — Suggest relevant next tools (MCP-Zero)
└── Stage 8: SYNTHESIS — Combine signals → action recommendation + LLM directiveSynthesis Priority: abstain > reset > clarify > proceed
Each 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.
LLM Directive (NEW)
The 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:
{
"directive": {
"action": "clarify",
"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?",
"questions": ["Could you specify exactly what you mean?", "Is this a firm requirement?"],
"contextHealth": 0.62,
"autoExtractedFacts": { "framework": "React", "deploy_to": "Vercel" },
"suggestedNextTools": ["verify_execution", "quarantine_context"]
}
}How context_loop Works
context_loop (single MCP tool call)
├── Stage 1: INGEST — Store messages to session history
├── Stage 2: RECAP — Extract intents, decisions, summaries
├── Stage 3: CONFLICT — Detect contradictions against ground truth
├── Stage 4: AMBIGUITY — Check for underspecified requirements
├── Stage 5: ENTROPY — Monitor output quality degradation (ERGO)
├── Stage 6: ABSTENTION — Multi-dimensional confidence check (RLAAR)
├── Stage 7: DISCOVERY — Suggest relevant next tools (MCP-Zero)
└── Stage 8: SYNTHESIS — Combine signals → action + directiveSynthesis priority: abstain > reset > clarify > proceed
Each stage runs with independent error isolation. The directive response field carries everything an LLM needs:
Field | Description |
|
|
| Plain-language guidance for the LLM's next step |
| Aggregated clarifying questions (ambiguity + abstention + conflicts) |
| 0–1 composite score. 1 = healthy, 0 = degraded |
| Key-value facts auto-extracted from user messages and stored as ground truth |
| Relevant tools the LLM should consider next |
Smart defaults: currentInput is auto-inferred from the last user message. Facts like "use React" are extracted and stored automatically.
Usage Protocol: Getting the Most from Context-First
The #1 mistake: LLMs treat
context_loopas optional. It's not — it's the backbone.
Built-in Enforcement (v1.2.1+)
The server ships with four compliance mechanisms that require zero configuration:
Server Instructions — Full usage protocol injected at MCP handshake via
ServerOptions.instructionsBootstrap Gate — First non-
context_loopcall appends a strong redirect reminderCross-Tool Reminders — After 3 consecutive calls without
context_loop, reminders appear in tool responsesMCP Prompts —
context-first-protocolandresearch-protocolprompt templates available on demand
Reinforce in Your System Prompt (Optional)
When using Context-First MCP:
1. Call context_loop BEFORE any complex task
2. Call context_loop every 2–3 tool calls
3. Call context_loop AFTER generating long-form output
4. ALWAYS follow directive.action (proceed/clarify/reset/abstain/deepen/verify)
5. Use memory_store to save findings; memory_recall to retrieve themResearch Task Workflow
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.
Phase 1 · Init research_pipeline(init) → sets up state, enables autonomous file writing
Phase 2 · Gather ONE web search → research_pipeline(gather) → file written to disk → repeat
Phase 3 · Analyze research_pipeline(analyze) → reasoning engines produce clean analysis file
Phase 4 · Verify research_pipeline(verify) → context health gate (non-blocking)
Phase 5 · Finalize research_pipeline(finalize) → synthesis.md + all batch files on disk
Automation shortcut:
export_research_files(outputDir, exportVerifiedReport=true) → write all report chunks
export_research_files(outputDir, exportRawEvidence=true) → write all evidence batchesAutonomous file writing is always on. Files are written to ./context-first-research-output/ by default — no LLM cooperation required. Pass outputDir to override.
Architecture
┌──────────────────────────────────────────────────────────────┐
│ @xjtlumedia/context-first-mcp-server │
│ (Core — shared logic) │
│ │
│ Layer 1: Context Health (9 tools) │
│ Layer 2: Sandbox (3 tools) │
│ Layer 3: Persistent Memory (6 tools) │
│ Layer 4: Advanced Reasoning(5 tools) │
│ Layer 5: Truthfulness (7 tools) │
│ State (4) · Orchestrator · Pipeline · Export │
└──────────────┬───────────────────────┬──────────────────────┘
│ │
┌──────▼──────┐ ┌──────▼────────┐
│ stdio-server │ │ remote-server │
│ (npx local) │ │ (Vercel) │
│ stdio │ │ Streamable │
│ 37 tools │ │ HTTP │
└──────────────┘ │ 37 tools │
└───────────────┘Core library (
@xjtlumedia/context-first-mcp-server): All tool implementations. Zero external API keys — heuristic-based by default.stdio-server (
context-first-mcp):npxentry point, stdio transport, 37 tools.remote-server: Vercel serverless, Streamable HTTP transport, 37 tools.
Frontend Demo
Try all 37 tools live in your browser at context-first-mcp.vercel.app.
Development
git clone https://github.com/XJTLUmedia/Context-First-MCP.git
cd Context-First-MCP
pnpm install
# Build everything
pnpm build
# Run stdio server
cd packages/stdio-server && pnpm start
# Run frontend
cd packages/frontend && pnpm dev
# Tests
pnpm testContributing
See CONTRIBUTING.md.
License
Context-First MCP · @xjtlumedia/context-first-mcp-server · context-first-mcp
Built for every developer tired of watching their AI lose the plot.
Available Tools
8 toolscontext_healthA
[CONTEXT & STATE] 13 sub-tools: recap, conflict, ambiguity, verify, entropy, abstention, grounding, drift, depth, get_state, set_state, clear_state, history. Auto-selects based on params or use 'check' to override. TIP: context_loop runs all health checks automatically — prefer context_loop for comprehensive analysis, use context_health for targeted checks.
Inputs: sessionId, check, params.
context_loopA
[ORCHESTRATOR — CALL THIS FIRST] CALL THIS TOOL every 2-3 turns and at the start of ANY task. It is the single most important tool — it replaces calling recap, conflict, ambiguity, entropy, grounding, drift, depth, and discovery tools individually.
What it does: Runs ALL context health checks in one call. Auto-extracts facts from conversation, detects contradictions, checks answer quality, and tells you exactly what to do next.
Returns a 'directive' object with:
action: proceed | clarify | reset | abstain | deepen | verify
instruction: Plain English telling you what to do
contextHealth: 0-1 score
autoExtractedFacts: Key facts pulled from conversation
suggestedNextTools: What tools to call next
constraints: Machine-readable rules you must follow
ESSENTIAL for: research tasks, multi-step workflows, long conversations, preserving context across turns, knowledge management, and any task requiring memory or fact-checking.
Minimal call: { "messages": [{"role":"user","content":"","turn":1}] } — most fields have smart defaults.
Inputs: sessionId, messages, currentInput, claim, +4 more.
export_research_filesA
[EXPORT] Automatically writes research artifacts to disk. It can 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 yet.
Inputs: outputDir (required), sessionId, baseFileName, exportVerifiedReport, +4 more.
memoryB
[MEMORY] 6 sub-tools: store (hierarchical ingest), recall (adaptive gate retrieval), compact (compress with integrity), graph (knowledge graph with PageRank), inspect (tier status), curate (importance-based curation). Auto-selects based on params or use 'action' to override. TOOL NAME: memory (use underscores).
Inputs: sessionId, action, params.
reasonA
[REASONING] 5 engines: inftythink (iterative bounded reasoning), coconut (multi-perspective latent analysis), extracot (reasoning chain compression), mindevolution (evolutionary search), kagthinker (structured logical decomposition with dependency DAG). Auto-selects based on params or use 'method' to override.
Inputs: sessionId, method, params.
research_pipelineA
[PIPELINE] RECOMMENDED for research tasks. Orchestrates all underlying Context-First layers through 6 phases (init→gather→review→analyze→verify→finalize). NEW: plan→draft→review→fix loop — like compile→test→fix in coding. Init generates a research outline (12+ sections). Each gather adds depth to one section with quality gate (25K char / 500 line min — multiple gathers per section expected). Review runs quality tests and identifies gaps. CRITICAL: Interleave web search and gather — after EACH search, IMMEDIATELY call gather with deeply written content. Do NOT batch searches. Each gather writes a file to disk. After sufficient gathers, call review to run quality tests. Fix failed sections by gathering again with metadata.targetSection=N. Coverage must reach 60% before analyze. Autonomous file writing is ALWAYS ON — files are written to disk during gather, analyze, and finalize phases. Provide outputDir to control destination, or let the pipeline auto-create a temp directory. Finalize works even if verify hasn't passed. It does not browse the web or invent source material for you; use it to structure, preserve, pressure-test, and export sourced findings collected from web, GitHub, fetch, or other MCP tools.
Inputs: phase (required), content (required), sessionId, outputDir, +4 more.
sandboxA
[SANDBOX] 3 sub-tools: discover (semantic tool search via TF-IDF), quarantine (isolated state sandbox), merge (merge/discard silo). Auto-selects based on params or use 'action' to override.
Inputs: sessionId, action, params.
truthcheckA
[TRUTHFULNESS] 7 tools: probe (linguistic truth signals), truth_direction (truth vector projection), ncb (perturbation robustness), logic (formal logical consistency), verify_first (5-dimension verification), ioe (confidence-based correction), self_critique (iterative refinement). Auto-selects or use 'check' to override. Set cascade=true for auto-correction on low scores.
Inputs: sessionId, check, cascade, params.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
The tools have distinct high-level purposes (e.g., context management, memory, reasoning, research), but the sub-tools within each main tool (like context_health's 13 sub-tools or memory's 6 sub-tools) create significant internal overlap and ambiguity. For example, context_health and context_loop both handle context checks, with context_loop described as replacing many individual checks, which could confuse an agent about when to use each. The auto-selection features mitigate this somewhat, but the boundaries between tools like context_health, context_loop, and truthcheck are not clearly defined, leading to potential misselection.
The naming is inconsistent across tools, with a mix of styles: some use snake_case (context_health, context_loop, export_research_files), others use single words (memory, reason, sandbox, truthcheck), and research_pipeline uses a hybrid format. There is no predictable verb_noun pattern, and the sub-tools within each main tool further add to the inconsistency (e.g., inftythink vs. extracot in reason). While the names are readable, the lack of a uniform convention makes the set harder to navigate and predict.
With 8 main tools, the count is reasonable for a server focused on context management and research workflows, as it covers key areas like health checks, memory, reasoning, and pipeline orchestration. However, the extensive sub-tools (e.g., 13 in context_health) make the effective surface larger, which could feel heavy but is justified by the server's complex domain. The count is slightly high but still appropriate given the scope, avoiding extreme over- or under-provisioning.
The tool set provides comprehensive coverage for context-aware AI tasks, including context health monitoring (context_health, context_loop), memory storage and retrieval (memory), reasoning engines (reason), research pipeline management (research_pipeline), truth verification (truthcheck), sandboxing (sandbox), and export functionality (export_research_files). There are no obvious gaps; it supports full lifecycle operations from initialization to analysis and export, with tools like context_loop and research_pipeline ensuring no dead ends in workflows. The domain is well-covered with tools that interlock effectively.
Maintenance
Related MCP Connectors
Persistent memory and drift detection for AI agents across session restarts.
Context integrity for AI agents: evaluate freshness, confidence, provenance, and decision readiness.
Context engineering for AI coding agents: product context, project missions, and 360 memory.
Memory that reasons: continual learning for stateful agents. Better context, fewer tokens.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenancePersistent decision memory and contradiction detection for AI coding agents. Enforces architectural consistency across sessions — the agent cannot code until it loads prior decisions. Human resolves conflicts on a dashboard or in chat.1MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI agents to retain memory of past interactions and detect behavioral drift, preventing repeated mistakes without LLM token extraction.22 npm28 PyPI1,258MIT
- AlicenseAqualityDmaintenanceAutomatically saves and retrieves AI conversation sessions to maintain context continuity, preventing re-explaining architecture decisions.425 npm6Creative Commons Attribution Non Commercial 4.0 International
- AlicenseNot gradedqualityCmaintenanceA visual canary that detects context rot and silent model degradation in long agent conversations by embedding externally verified checkpoints and self-reported status into each response.7 npmMIT