Context First Mcp

io.github.XJTLUmedia由 GitHub 帳號 XJTLUmedia 發布v1.2.2更新於 Oct 25, 2026

37-tool MCP server: context health, memory, reasoning, truthfulness & research pipeline.

概覽

AI 產生的概覽

一個本機 MCP 伺服器,為助理提供上下文健康、記憶、推理與真實性檢查,讓長對話保持有憑有據、前後一致。

可以做什麼
執行一次上下文迴圈,回顧意圖、標記衝突、歧義與漂移,並回傳帶健康分數和釐清問題的單一動作指令。鎖定並讀取已確認事實與任務狀態,檢視壓縮後的對話歷史。儲存、召回、壓縮、整理並建立持久記憶圖譜,並把子任務上下文隔離到可合併的隔離區。依自然語言查詢路由到相關工具,並執行結構化推理與自我批評流程。執行分階段研究流程,把報告片段和原始證據批次寫入磁碟。
適用情境
適合長時間、多步驟的對話,尤其是助理容易忘記先前的決定、與已鎖定的事實矛盾,或未經驗證就宣稱成功的情況。也適合需要最終把結果寫成磁碟檔案的結構化研究任務。
執行需求
透過 stdio 在本機執行,通常以 npx 啟動,因此需要 Node.js。README 也提到可改用託管的遠端端點。未宣告任何 API 金鑰或環境變數。
安裝前請注意
研究流程與匯出工具會自動將檔案寫入磁碟,預設寫入研究輸出目錄,且即使驗證未通過也能寫出原始證據。狀態與記憶工具會在本機保存對話內容。伺服器會在工具回應中注入使用提醒,促使助理呼叫其上下文迴圈。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 Context First Mcp,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

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]

bash
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.

json
{  "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

bash
npx context-first-mcp

Claude Desktop

json
{  "mcpServers": {    "context-first": {      "command": "npx",      "args": ["-y", "context-first-mcp"]    }  }}

Cursor / VS Code

json
{  "mcp": {    "servers": {      "context-first": {        "command": "npx",        "args": ["-y", "context-first-mcp"]      }    }  }}

Remote (Streamable HTTP)

json
{  "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:

json
{  "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 task2. Call context_loop every 2–3 tool calls3. Call context_loop AFTER generating long-form output4. 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 writingPhase 2 · Gather   ONE web search → research_pipeline(gather) → file written to disk → repeatPhase 3 · Analyze  research_pipeline(analyze) → reasoning engines produce clean analysis filePhase 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

bash
git clone https://github.com/XJTLUmedia/Context-First-MCP.gitcd Context-First-MCPpnpm install
# Build everythingpnpm build
# Run stdio servercd packages/stdio-server && pnpm start
# Run frontendcd packages/frontend && pnpm dev
# Testspnpm 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.

來源:README.md,提交 2732b90

工具

0
SourceWeft 尚未在沙箱中啟動過該軟體包,因此其工具未知。

版本歷史

1
  1. v1.2.2最新Sep 16, 2026

評分

已滿足適用檢查項的 50%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分

    請保持端點能夠回應 MCP 握手;SourceWeft 每 30 天探測一次。

  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具15 分

    請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。

  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分