XJTLUmedia/Context-First-MCP

XJTLUmedia/Context-First-MCP

от xjtlumedia
MCP-сервер предотвращает потерю контекста и противоречия в длинных AI-диалогах. 37 инструментов с оркестратором context_loop автоматически проверяют контекст, выявляют неоднозначности и верифицирую...

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 Mode What Goes Wrong Context-First Solution
Context Drift AI forgets earlier decisions and intent as the conversation grows context_loop + detect_drift continuously re-anchor every turn
Silent Contradiction New inputs silently overrule established facts — the AI doesn't notice detect_conflicts compares every input against locked ground truth
Vague Execution AI proceeds on underspecified requirements, producing misaligned output check_ambiguity + abstention_check ask clarifying questions instead of guessing
Hallucinated Success Tool outputs look successful but didn't actually achieve the goal verify_execution rechecks whether the outcome matches the stated intent
Инструменты были проиндексированы:
context_health

[КОНТЕКСТ И СОСТОЯНИЕ] 13 под-инструментов: recap, conflict, ambiguity, verify, entropy, abstention, grounding, drift, depth, get_state, set_state, clear_state, history. Автоматически выбирает на основе параметров или используйте 'check' для переопределения. СОВЕТ: context_loop запускает все проверки здоровья автоматически: предпочитайте context_loop для всестороннего анализа, используйте context_health для целевых проверок.

Параметры
  • checkenum

    Override: run a specific check. If omitted, auto-selects based on params. clear_state shares params with get_state — use this override to disambiguate.

  • paramsobject

    Parameters for the underlying tool(s), minus sessionId. Multiple checks run if params match more than one tool. recap: {messages[], lookbackTurns?}; conflict: {newMessage}; ambiguity: {requirement, context?}; verify: {goal, output, expectedIndicators?}; entropy: {outputs[], threshold?, autoReset?}; abstention: {claim, requiredKeys[], threshold?}; grounding: {assistantOutput, claim?}; drift: {windowSize, turn?, health?, breakdown?}; depth: {content, minDepthWords?, minDepthSentences?}; get_state: {keys?}; set_state: {key, value, source?}; clear_state: (use check override); history: {maxTokens}

  • sessionIdstring

    Session identifier

context_loop

[ORCHESTRATOR — ВЫЗЫВАЙТЕ ЭТОТ ПЕРВЫМ] ВЫЗЫВАЙТЕ ЭТОТ ИНСТРУМЕНТ каждые 2-3 шага и в начале ЛЮБОЙ задачи. Это самый важный инструмент — он заменяет вызов инструментов recap, conflict, ambiguity, entropy, grounding, drift, depth и discovery по отдельности. Что делает: Запускает ВСЕ проверки здоровья контекста за один вызов. Автоматически извлекает факты из разговора, обнаруживает противоречия, проверяет качество ответов и точно говорит, что делать дальше. Возвращает объект 'directive' с: - action: proceed | clarify | reset | abstain | deepen | verify - instruction: четкий текст на русском, что делать - contextHealth: оценка 0-1 - autoExtractedFacts: ключевые факты, извлеченные из разговора - suggestedNextTools: какие инструменты вызывать дальше - constraints: машиночитаемые правила, которым нужно следовать НЕОБХОДИМ для: исследовательских задач, многошаговых процессов, длинных разговоров, сохранения контекста между шагами, управления знаниями и любых задач, требующих памяти или проверки фактов. Минимальный вызов: { "messages": [{"role":"user","content":"<user msg>","turn":1}] } — большинство полей имеют разумные значения по умолчанию.

Параметры
  • abstentionThresholdnumber

    Abstention confidence threshold (0-1)

  • claimstring

    A specific assertion or answer to fact-check for confidence evaluation

  • currentInputstring

    The current user message or task description. Auto-inferred from last user message in messages array if omitted.

  • discoveryQuerystring

    What capability do you need? e.g. 'store research findings' or 'compress reasoning chain'

  • entropyThresholdnumber

    Entropy spike detection threshold (0-1)

  • lookbackTurnsnumber

    How many turns to analyze (use 15-20 for research or long conversations)

  • messagesobject[]

    Recent conversation messages. Include at least the last 2-3 user/assistant exchanges. Example: [{role:'user', content:'explain X', turn:1}, {role:'assistant', content:'X is...', turn:2}]. If empty, the loop runs with reduced context.

  • sessionIdstring
export_research_files

[EXPORT] Автоматически записывает исследовательские артефакты на диск. Может разворачивать и записывать каждый проверенный фрагмент отчёта без необходимости вручную зацикливать финализацию через LLM, а также может записывать каждый собранный пакет сырых доказательств, даже если проверка ещё не пройдена.

Параметры
  • baseFileNamestring

    Base filename prefix for all written research artifacts. The helper sanitizes it into a filesystem-safe ASCII stem.

  • exportRawEvidenceboolean

    When true, writes every gathered research batch as raw evidence files even if verify has not passed, separating evidence capture from narrative approval.

  • exportVerifiedReportboolean

    When true, automatically expands and writes the full verified report by looping all finalize chunks internally. This path remains blocked until verify has passed.

  • finalSummarystring

    Optional final summary override for verified report export. If omitted, the helper uses the stored pipeline summary or existing analysis and verification outputs.

  • maxChunkCharsinteger

    Maximum size for each written markdown file. Large batches are automatically split across multiple files when needed.

  • outputDirstringобязательный

    Directory where research export files will be written. Prefer an absolute path so the caller knows exactly where the artifacts landed.

  • overwriteboolean

    Whether existing export files may be overwritten. Defaults to false so exports do not silently clobber prior artifacts.

  • sessionIdstring
memory

[MEMORY] 6 вспомогательных инструментов: store (иерархическая загрузка), recall (адаптивное извлечение через шлюз), compact (сжатие с сохранением целостности), graph (граф знаний с PageRank), inspect (статус уровня), curate (отбор по важности). Автоматически выбирает на основе параметров или используйте 'action' для переопределения. НАЗВАНИЕ ИНСТРУМЕНТА: memory (используйте подчеркивания).

Параметры
  • actionenum

    Override: run a specific memory action. If omitted, auto-selects based on params. store — pass {role, content}; recall — pass {query}; compact — pass {targetRatio?}; graph — pass {action:'query'|'stats'|'recompute'}; inspect — pass {tier?}; curate — pass {action:'top'|'filterByDomain'|'mostReused'|'prune'}

  • paramsobject

    Parameters for the underlying tool. store: {role, content, metadata?}; recall: {query, maxResults?, turnCount?, entropy?, conflicts?}; compact: {targetRatio?, preserveRecency?}; graph: {action:'query'|'stats'|'recompute', startEntity?, depth?}; inspect: {tier?, runIntegrityCheck?}; curate: {action:'top'|'filterByDomain'|'mostReused'|'prune', domainTag?, threshold?}

  • sessionIdstring

    Session identifier

reason

5 движков: inftythink (итеративное ограниченное рассуждение), coconut (многоаспектный латентный анализ), extracot (сжатие цепочки рассуждений), mindevolution (эволюционный поиск), kagthinker (структурированное логическое разложение с DAG зависимостей). Автоматически выбирает на основе параметров или используйте 'method' для переопределения.

Параметры
  • methodenum

    Override: run a specific reasoning method. If omitted, auto-selects based on params. inftythink — iterative bounded reasoning (default for raw problems); coconut — multi-perspective latent-space analysis; extracot — compress existing reasoning steps; mindevolution — evolutionary search over seed solutions; kagthinker — structured logical decomposition with dependency graph

  • paramsobject

    Parameters for the underlying reasoning engine. inftythink: {problem, priorContext?, maxSegments?, maxSegmentTokens?, summaryRatio?}; coconut: {problem, maxSteps?, breadth?, enableBreadthExploration?}; extracot: {reasoningSteps[], problem?, maxBudget?, targetCompression?, minFidelity?}; mindevolution: {problem, criteria?, populationSize?, maxGenerations?, seedResponses[]}; kagthinker: {problem, knownFacts?, maxDepth?, maxSteps?}

  • sessionIdstring

    Session identifier

research_pipeline

[PIPELINE] РЕКОМЕНДУЕТСЯ для исследовательских задач. Оркестрирует все базовые слои Context-First в 6 этапов (init→gather→review→analyze→verify→finalize). НОВЫЙ: цикл plan→draft→review→fix — как compile→test→fix в программировании. Init генерирует план исследования (12+ разделов). Каждый gather добавляет глубину одному разделу с проверкой качества (мин. 25K символов / 500 строк — ожидается несколько gather на раздел). Review запускает проверки качества и выявляет пробелы. ВАЖНО: чередуйте веб-поиск и gather — после КАЖДОГО поиска НЕМЕДЛЕННО вызывайте gather с глубоко проработанным содержимым. НЕ группируйте поиски. Каждый gather записывает файл на диск. После достаточного количества gather вызывайте review для проверки качества. Исправляйте не пройденные разделы, снова вызывая gather с metadata.targetSection=N. Охват должен достичь 60% перед analyze. Автономная запись файлов ВСЕГДА ВКЛЮЧЕНА — файлы записываются на диск во время фаз gather, analyze и finalize. Укажите outputDir для управления путем назначения, или позвольте конвейеру автоматически создать временную директорию. Finalize работает даже если verify не пройден. Он не просматривает веб и не выдумывает исходные материалы; используйте его для структурирования, сохранения, проверки на прочность и экспорта собранных данных из веб, GitHub, fetch или других MCP-инструментов.

Параметры
  • baseFileNamestring

    Base filename prefix for autonomously written files when outputDir is set. Produces files like research.batch-001.topic-slug.md, research.analysis-001.md, research.synthesis.md

  • claimstring

    Specific claim to fact-check (verify phase)

  • contentstringобязательный

    Phase-specific content: init=task description, gather=WRITE a deeply researched section based on your LATEST web search. CRITICAL WORKFLOW: Do ONE web search, then IMMEDIATELY call gather. Repeat. Do NOT do multiple searches before calling gather — content gets lost to compaction. You are a research AUTHOR: use the search result as input to write a comprehensive section with specific facts, data, analysis, relationships, and expert commentary. Each gather call writes one file to disk immediately — this is the pipeline's core output. analyze=problem/question to reason about (runs on accumulated gather files), verify=draft output to verify (runs on accumulated files), finalize=final summary to persist (synthesizes all files)

  • messagesobject[]

    Recent conversation messages for context_loop

  • metadataobject

    Optional metadata for memory storage and finalize/export controls. Supported conventions: sourceTools during gather, maxChunkChars during finalize, exportChunkIndex during finalize chunk retrieval, outline (Array<{title, description}>) during gather to set the research outline, targetSection (number) during gather to expand/append depth to a specific outline section (multi-gather accumulation).

  • outputDirstring

    RECOMMENDED. When provided, the pipeline autonomously writes enriched research files to this directory during gather, analyze, and finalize phases. This eliminates the need for the LLM to write files manually — the pipeline writes them itself, like how export_research_files works but incrementally per-phase. Files survive context compaction because they are on disk, not just in memory. Prefer an absolute path.

  • phaseenumобязательный

    Pipeline phase. Call in order: init → gather (repeatable) → review → analyze → verify → finalize. Each phase auto-chains the appropriate layer tools internally. Analyze is blocked until gathered evidence clears the weak-evidence gate and coverage ≥ 60%.

  • sessionIdstring
sandbox

[SANDBOX] 3 под-инструмента: discover (семантический поиск инструментов через TF-IDF), quarantine (изолированная песочница состояния), merge (слияние/отбрасывание silo). Автоматически выбирает на основе параметров или используйте 'action' для переопределения.

Параметры
  • actionenum

    Override: run a specific action. If omitted, auto-selects based on params. discover — pass {query}; quarantine — pass {name}; merge — pass {siloId, action:'merge'|'discard'}

  • paramsobject

    Parameters for the underlying tool. discover: {query, maxResults?, minScore?}; quarantine: {name, inheritKeys?, ttl?}; merge: {siloId, action:'merge'|'discard', promoteKeys?}

  • sessionIdstring

    Session identifier (used by quarantine/merge)

truthcheck

[TRUTHFULNESS] 7 инструментов: probe (лингвистические сигналы правдивости), truth_direction (проекция вектора правдивости), ncb (устойчивость к возмущениям), logic (формальная логическая согласованность), verify_first (5-мерная верификация), ioe (коррекция на основе уверенности), self_critique (итеративное уточнение). Автоматический выбор или используйте 'check' для переопределения. Установите cascade=true для автоматической коррекции при низких оценках.

Параметры
  • cascadeboolean

    If true, after primary checks, auto-run ioe_self_correct → self_critique when any extracted truthfulness score falls below 0.5.

  • checkenum

    Override: run a specific truthfulness check. If omitted, auto-selects based on params. probe — linguistic truth proxy signals; truth_direction — truth vector projection; ncb — perturbation robustness; logic — formal logical consistency; verify_first — 5-dimension verification; ioe — confidence-based self-correction; self_critique — iterative multi-criteria refinement

  • paramsobject

    Parameters for the underlying tool(s), minus sessionId. probe: {assistantOutput, includeHistory?}; truth_direction: {assistantOutput, includePriorOutputs?}; ncb: {originalQuery, response}; logic: {claims[], includeGroundTruth?}; verify_first: {candidateAnswer, question, context?}; ioe: {response, question?, priorAttempts?}; self_critique: {solution, criteria?, maxIterations?, question?}

  • sessionIdstring

    Session identifier

Похожие MCP-сервера

cyberchitta/llm-context.py

cyberchitta/llm-context.py

LLM Context - MCP-сервер для умного управления контекстом при работе с ИИ. Использует правила для автоматического подбора и передачи нужных файлов проекта, экономя токены. Полезен разработчикам и A...

Python306
gzoonet/cortex

gzoonet/cortex

Сервер GZOO Cortex — локальный граф знаний для разработчиков: мониторит файлы проектов, извлекает сущности и связи с помощью LLM. MCP инструмент для Claude Code с 12 инструментами позволяет задавать вопросы о проектах и выявлять противоречия прямо из диалога.

TypeScript21
rinadelph/Agent-MCP

rinadelph/Agent-MCP

MCP сервер для координации нескольких AI-агентов при разработке. Агенты работают параллельно, используют общую память и граф знаний, что исключает потерю контекста и конфликты. Подходит для крупных...

TypeScript1291
BrowseAI-HQ/BrowserAI-Dev

BrowseAI-HQ/BrowserAI-Dev

MCP-сервер BrowseAI Dev добавляет AI-агентам веб-поиск с верификацией фактов: каждый ответ сопровождается источниками, оценкой уверенности и обнаружением противоречий. Полезен разработчикам агентов...

TypeScript20
i-am-bee/acp-mcp

i-am-bee/acp-mcp

Лёгкий MCP сервер-адаптер, соединяющий ACP-агентов с MCP-приложениями. Автоматически обнаруживает ACP-агентов, делая их доступными как MCP-ресурсы и инструменты. Полезен для интеграции агентов из ACP в экосистему Claude Desktop и других MCP-клиентов.

Python36
hubinoretros/deep-thinker

hubinoretros/deep-thinker

MCP сервер с графом мыслей (DAG) и 10 стратегиями рассуждений: от последовательной до метапознания. Включает 17 инструментов для глубокого анализа, диалектики, абдукции и автоматического выбора стратегии. Полезен разработчикам и исследователям в решении сложных задач.

TypeScript13
© Каталог MCP, 2026. Все права защищены.
Проект не аффилирован с Anthropic и любыми упомянутыми продуктами.
Все названия и торговые марки принадлежат их владельцам.
Контакты для связи: hi@mcp-katalog.ru

Лука Никитин