C
Health: Not checked yetWe have not completed a health check for this listing yet.No health check has run yet.

Context First MCP

XJTLUmedia
🧠 Knowledge & Memory
0 Views
0 Installs

πŸ“‡ ☁️ 🏠 🍎 πŸͺŸ 🐧 - Session memory, context health monitoring, reasoning quality, and truthfulness verification MCP server with 37 tools and tiered memory storage. npx -y context-first-mcp

Quick Install

One-Click IDE Configuration
claude_desktop_config.json
{
  "mcpServers": {
    "xjtlumedia-context-first-mcp": {
      "command": "npx",
      "args": [
        "-y",
        "xjtlumedia-context-first-mcp"
      ]
    }
  }
}
Or

Using an AI coding agent (Claude Code, Cursor, etc.)? Copy a ready-made prompt that tells it to fetch the setup instructions and install this server for you.

Documentation Overview

Context-First MCP

The MCP server that keeps your AI grounded, coherent, and honest β€” across every turn.

npm version npm downloads License: MIT MCP Compatible Smithery Glama Node β‰₯18 TypeScript

npx context-first-mcp

Works 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_loop call 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 ModeWhat Goes WrongContext-First Solution
Context DriftAI forgets earlier decisions and intent as the conversation growscontext_loop + detect_drift continuously re-anchor every turn
Silent ContradictionNew inputs silently overrule established facts β€” the AI doesn't noticedetect_conflicts compares every input against locked ground truth
Vague ExecutionAI proceeds on underspecified requirements, producing misaligned outputcheck_ambiguity + abstention_check ask clarifying questions instead of guessing
Hallucinated SuccessTool outputs look successful but didn't actually achieve the goalverify_execution rechecks whether the outcome matches the stated intent

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-mcp

Claude 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

Deploy with Vercel


Tool Reference

Layer 1: Core Context Health (9 tools)

ToolPurpose
context_loopOne-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
recap_conversationExtracts hidden intent, key decisions, and produces consolidated state summaries
detect_conflictsCompares new input against ground truth; surfaces contradictions
check_ambiguityIdentifies underspecified requirements and generates clarifying questions
verify_executionValidates whether tool outputs actually achieved the stated goal
entropy_monitorProxy-entropy scoring via lexical diversity, contradiction density, hedge frequency, and n-gram repetition (ERGO)
abstention_check5-dimension confidence scoring β€” abstains with questions rather than hallucinating (RLAAR)
detect_driftDetects conversation drift from the original intent
check_depthEvaluates response depth against question complexity

Layer 1b: State Management (4 tools)

ToolPurpose
get_stateRetrieve confirmed facts and task status
set_stateLock in ground truth β€” subsequent conflict checks run against these values
clear_stateReset specific keys or all state
get_history_summaryCompressed conversation history with intent annotations

Layer 2: Sandbox & Discovery (3 tools)

ToolMethodPurpose
discover_toolsMCP-Zero + ScaleMCPNatural-language tool routing β€” returns only semantically relevant tools, reducing context bloat by up to 98%
quarantine_contextMulti-Agent QuarantineCreate isolated memory silos for sub-tasks, preventing intent dilution
merge_quarantineMulti-Agent QuarantineMerge silo results with noise filtering β€” only promoted keys return to main context

Layer 3: Persistent Memory (6 tools)

ToolPurpose
memory_storeStore findings, decisions, and intermediate results with metadata
memory_recallRetrieve relevant memories by semantic query
memory_compactCompress and consolidate memory entries
memory_graphBuild and query a knowledge graph from stored memories
memory_inspectInspect memory store contents and statistics
memory_curateDeduplicate and organize memory entries

Layer 4: Advanced Reasoning (5 tools)

ToolMethodPurpose
inftythink_reasonInftyThinkInfinite-depth reasoning with adaptive stopping
coconut_reasonCoconutChain-of-Continuous-Thought in latent space
extracot_compressExtraCoTCompress chain-of-thought while preserving reasoning fidelity
mindevolution_solveMindEvolutionEvolutionary search over the solution space
kagthinker_solveKAG-ThinkerKnowledge-augmented generation with structured thinking

Layer 5: Truthfulness & Verification (7 tools)

ToolPurpose
probe_internal_stateProbe model consistency across paraphrased prompts
detect_truth_directionDetect whether model reasoning is trending toward or away from truth
ncb_checkNeighborhood consistency check across semantically equivalent inputs
check_logical_consistencyVerify logical coherence of reasoning chains
verify_firstPre-verification before committing to claims
ioe_self_correctIntrinsic-extrinsic self-correction
self_critiqueStructured self-critique with improvement suggestions

Research Pipeline & Export (2 tools)

ToolPurpose
research_pipelineStructured 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.
export_research_filesWrites 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:

AlgorithmPaperarXivTool
MCP-ZeroActive Tool Request2506.01056discover_tools
ScaleMCPSemantic Tool Grouping2505.06416discover_tools registry
ERGOEntropy-based Quality2510.14077entropy_monitor
RLAARCalibrated Abstention2510.18731abstention_check

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)

ToolDescription
export_research_filesWrites 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.

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 directive

Synthesis 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 + directive

Synthesis priority: abstain > reset > clarify > proceed

Each stage runs with independent error isolation. The directive response field carries everything an LLM needs:

FieldDescription
actionproceed Β· clarify Β· reset Β· abstain
instructionPlain-language guidance for the LLM's next step
questionsAggregated clarifying questions (ambiguity + abstention + conflicts)
contextHealth0–1 composite score. 1 = healthy, 0 = degraded
autoExtractedFactsKey-value facts auto-extracted from user messages and stored as ground truth
suggestedNextToolsRelevant 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_loop as 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:

  1. Server Instructions β€” Full usage protocol injected at MCP handshake via ServerOptions.instructions
  2. Bootstrap Gate β€” First non-context_loop call appends a strong redirect reminder
  3. Cross-Tool Reminders β€” After 3 consecutive calls without context_loop, reminders appear in tool responses
  4. MCP Prompts β€” context-first-protocol and research-protocol prompt 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 them

Research 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 batches

Autonomous 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): npx entry 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 test

Contributing

See CONTRIBUTING.md.

License

MIT


Context-First MCP Β· @xjtlumedia/context-first-mcp-server Β· context-first-mcp

Built for every developer tired of watching their AI lose the plot.

Related MCP Servers

S
Server Memory
Verified

πŸ“‡ 🏠 - Knowledge graph-based persistent memory system for maintaining context

🧠 Knowledge & Memory2 views
M
Mcp Summarizer

πŸ“• ☁️ - AI Summarization MCP Server, Support for multiple content types: Plain text, Web pages, PDF documents, EPUB books, HTML content

🧠 Knowledge & Memory0 views
C
Claude Engram

🐍 🏠 - Persistent memory and session intelligence for Claude Code. Auto-tracks mistakes, decisions, and context via hooks. Mines session history for patterns and cross-session search. Loop detection, pre-edit warnings, context compaction survival. Runs locally with Ollama.

🧠 Knowledge & Memory0 views
A
A2cr

🐍 ☁️ 🏠 🍎 πŸͺŸ 🐧 - MCP server for AI-agent handoffs. Saves client-encrypted WorkBaton checkpoints and WorkStash notes so Codex, Claude Code, Roo Code, and other MCP clients can resume work without passing full chat history.

🧠 Knowledge & Memory0 views
β˜… Featured

Moxie Docs MCP

MCP & Agent Skills for Automated Documentation, and codebase conventions + context

View ServerFeature your own server β†’

Own this project?

This directory is pre-filled from public sources. Claim via GitHub README, site badge, or DNS TXT to get the verified badge and attach your website.

Claim this listing

Promote this listing

Optional paid placement. Free listings stay free forever.

Share & Embed

Add our SVG badge (dark/light directory styles) or embeddable widget to your site.