CodeBrain
CodeBrain
MCP-сервер, который позволяет Claude Code перекладывать объемную работу на локальную LLM, запущенную на вашем собственном оборудовании.
Что это (и чем не является)
Является: MCP-сервером (Model Context Protocol), который Claude Code регистрирует в качестве бэкенда для вспомогательного агента. Когда сессия включает задачи, с которыми хорошо справляется локальная модель кодинга на 14B параметров — создание 50 шаблонов событий, доработка 20 React-компонентов, написание шаблонного кода — Claude Code обращается к CodeBrain вместо того, чтобы тратить свои собственные выходные токены. Локальная модель делает черновой вариант, а Claude проверяет и применяет его.
Не является: Заменой Claude. Рассуждения, архитектурные решения, отладка и все, где «достаточно хорошо» недостаточно, остаются за Claude. CodeBrain — это разгрузчик для Claude, а не конкурент Claude.
Зачем: Большие объемы контента и работа по доработке быстро расходуют контекст и лимиты Claude. Локальная модель, которую можно запускать без ограничений, не требует дополнительных затрат на вызов и оставляет ценный контекст свободным для сложных частей сессии.
Related MCP server: ollama-mcp
Статус
Фазы 1–4 завершены, Фаза 5 отложена. Доступно девять инструментов, реализована передача .brain/context.md, сканер сводок по файлам, цикл верификации, консенсусное декодирование. Интеграция MCP проверена в реальной сессии Claude Code. Фаза 5 (RAG) была явно определена как «только при необходимости», и текущее использование не показывает, что поиск по нескольким файлам является узким местом, поэтому она остается отложенной.
Как это работает
Claude Code session CodeBrain MCP server Local machine
───────────────────── stdio ─────────────────── ─────────────
Claude delegates a ────────► codebrain_generate() ────► Ollama HTTP
bulk / polish task codebrain_explain() (localhost:11434)
codebrain_status() │
▼
Qwen2.5-Coder 14B
(GPU)
Claude reviews, ◄──────── tool result string ◄──── streamed response
applies, or pushes backНа данный момент доступно девять инструментов:
Инструмент | Когда Claude обращается к нему |
| Объемный контент, шаблонный код, повторяющиеся преобразования, черновики |
| N промптов с одним общим системным сообщением, последовательное выполнение, ошибки с сохранением индекса, чтобы один сбой не прерывал пакет |
| Целевое преобразование существующего текста — сокращение, перефразирование, перевод, улучшение. Автоматический повтор при отсутствии изменений. |
| Быстрые объяснения в режиме только для чтения без расходования контекста Claude |
| Генерация с детерминированным циклом верификации: проверка количества слов / regex-схемы, повтор с уточненными инструкциями при нарушении |
| N кандидатов + вызов судьи → лучший единичный результат. Используйте для задач с высокой вариативностью. |
| Однократная настройка репозитория: определяет стек, записывает шаблон |
| Создание или обновление одного файла сводки |
| Обход + сканирование дерева; с хеш-защитой, сбои в отдельных файлах не прерывают пакет |
| Проверка того, какие модели установлены локально |
Флаг use_brain в инструментах генерации автоматически добавляет .brain/context.md из текущей рабочей директории к системному промпту, поэтому контекст проекта передается с каждым вызовом без необходимости ручной передачи со стороны Claude.
Требования
Python 3.11+
Ollama — скачать для вашей ОС. Протестировано с Ollama на Windows (нативная версия), взаимодействие через
localhost:11434.Локально загруженная модель для кодинга:
ollama pull qwen2.5-coder:14b~9 ГБ загрузки. Помещается в 12 ГБ видеопамяти при Q5. Другие модели также работают (DeepSeek-Coder, Qwen3, если доступны) — задается через переменную окружения
CODEBRAIN_MODEL.Claude Code CLI на машине, которая будет вызывать сервер (очевидно).
Установка
git clone <this repo> CodeBrain
cd CodeBrain
python -m venv .venv
.venv\Scripts\activate # on Windows
# source .venv/bin/activate # on macOS / Linux
pip install -e .Настройка Claude Code
Добавьте CodeBrain в конфигурацию MCP Claude Code. В Windows это обычно ~/.claude.json (отрегулируйте путь к месту, куда вы клонировали репозиторий):
{
"mcpServers": {
"codebrain": {
"command": "C:\\Users\\YOU\\Desktop\\CodeBrain\\.venv\\Scripts\\python.exe",
"args": ["-m", "codebrain"]
}
}
}Перезапустите любую сессию Claude Code — пять инструментов codebrain_* теперь должны появиться в списке доступных инструментов.
Автоматическая синхронизация brain-файлов
После того как вы запустили codebrain_init в репозитории и просканировали его с помощью codebrain_scan_repo, вы, вероятно, захотите, чтобы brain-файлы обновлялись автоматически всякий раз, когда Claude редактирует исходный код. Это настраивается двумя способами:
1. Фрагмент CLAUDE.md — скажите Claude читать brain-файлы перед открытием исходного кода:
## Brain files
This repo has per-file `.brain` summaries next to each source file.
Before reading a full source file, read its `<path>.brain` sibling first.
Only open the source when the brain file is insufficient for the task.2. Хук PostToolUse — пересоздавайте brain после каждого Edit/Write.
Добавьте в .claude/settings.json в корне репозитория:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "python -c \"import asyncio, json, sys; from codebrain.brain_scanner import scan_file; d = json.load(sys.stdin); p = d.get('tool_input', {}).get('file_path'); p and p.endswith(('.py', '.ts', '.tsx', '.js', '.jsx', '.java', '.go', '.rs')) and print(asyncio.run(scan_file(p)))\""
}
]
}
]
}
}Хук проверяет отредактированный путь, пропускает файлы, не являющиеся исходным кодом, через фильтр расширений и запускает сканирование. С хеш-защитой: неизмененные файлы не отправляются в Qwen.
Проверка работоспособности
Внутри сессии Claude Code спросите Claude:
Вызови
codebrain_statusи скажи мне, что установлено.
Если Ollama запущена и модель загружена, вы получите qwen2.5-coder:14b в списке.
Конфигурация
Переменные окружения, считываемые бэкендом:
Переменная | По умолчанию | Что делает |
|
| Укажите на удаленный Ollama (например, сервер вывода в вашей локальной сети) |
|
| Переключитесь на любую загруженную вами модель |
|
| Секунды ожидания для одной генерации |
Структура проекта
CodeBrain/
├── codebrain/
│ ├── __init__.py
│ ├── __main__.py # `python -m codebrain` entry
│ ├── backend.py # Ollama HTTP client
│ ├── server.py # FastMCP server + tool definitions
│ ├── brain_scanner.py # scan_file / scan_repo + hash gate
│ ├── brain_init.py # one-shot .brain/context.md seeding
│ ├── verifier.py # deterministic output checks
│ └── prompts/
│ └── brain_few_shot.md # few-shot for brain-file generation
├── tests/ # 96 unit + integration tests
├── .spec/
│ ├── CURRENT.md # phase state
│ └── brain-file-format.md # brain-file format v1
├── pyproject.toml
├── LICENSE
└── README.mdДорожная карта
Фаза 1 — каркас ✓
[x] HTTP-клиент Ollama с обработкой ошибок
[x] FastMCP-сервер с транспортом stdio
[x] Три основных инструмента:
generate,explain,status[x] Документированная настройка + конфигурация Claude Code
[x] Проверено в реальной сессии Claude Code
Фаза 2 — пакетная обработка и контекст ✓
[x]
codebrain_batch_generateдля массового контента с одним общим системным промптом, ошибки с сохранением индекса[x]
codebrain_polishдля целевых преобразований (сокращение / перефразирование / перевод) вместо перегенерации[x] Передача
.brain/context.md— контекст проекта из cwd автоматически добавляется к каждому вызову генерации[x] Dogfooding: задачи по кодингу работают стабильно, задачи по преобразованию текста выявили реальные ограничения (информирует Фазу 3)
Фаза 2.5 — система brain ✓
Сводки <source>.brain для каждого файла располагаются рядом с исходным файлом. Claude сначала читает brain и открывает исходный код только тогда, когда информации в brain недостаточно.
[x]
codebrain_scan_file(path, force)— создание или обновление одного brain-файла[x]
codebrain_scan_repo(root, force, extensions, exclude_dirs)— массовый обход + сканирование[x]
codebrain_init(root, force)— инициализация.brain/context.mdс определением стека[x] Перегенерация с хеш-защитой (SHA256) — идемпотентные повторные запуски
[x] Программный frontmatter — детерминированные
source,source_hash,model; Qwen записывает только пять разделов[x] Глубокая проверка: удаление ограждений, пропуск пустых исходников (<10 символов), наличие/порядок разделов, повтор при невалидности
[x] Соглашение CLAUDE.md + фрагмент хука PostToolUse в этом README
Фаза 3 — цикл ВЕРИФИКАТОРА ✓
Dogfooding показал, что локальная модель «уплывает» при преобразовании текста. Верификатор детерминированно отлавливает отсутствие изменений, нарушения длины и несоответствия схеме до того, как они попадут к Claude.
[x]
detect_noop— проверка на равенство с нормализацией пробелов (автоматический повтор внутриcodebrain_polish)[x]
check_word_count(min_words, max_words)— ограничение по количеству слов[x]
check_regex_schema(pattern)— проверка структурированного вывода[x]
codebrain_generate_verified(prompt, min_words, max_words, must_match, max_retries)— цикл с уточненными инструкциями для повтора, возвращает[codebrain warning] ...если верификация не проходит после повторов
Фаза 4 — консенсусное декодирование ✓
[x]
codebrain_consensus_generate(prompt, n)— генерация N кандидатов (ограничено [2,5]), Qwen выбирает лучший дословно. N+1 вызовов вывода, повышает качество в задачах с высокой вариативностью.Многопроходный скелет→логика→границы→полировка: отложено (низкая измеренная ценность; отдельные инструменты уже компонуются).
Фаза 5 — RAG (отложено — не является узким местом)
Brain-файлы уже действуют как индекс; RAG по нескольким файлам имеет смысл только в том случае, если будущее использование действительно покажет, что индексация является блокирующим фактором. Сейчас таких сигналов нет, поэтому не реализовано.
Лицензия
MIT — см. LICENSE.
Available Tools
10 toolscodebrain_batch_generateA
Run several generation prompts in sequence and return all results.
One shared system prompt applies to every item. Prompts are processed
serially (Ollama serialises on a single GPU anyway). A failure on one
prompt is captured inline as [codebrain error] ... at that index, so
the whole batch never aborts.
Returns a single string with per-item delimiters:
--- [0] ---
<result for prompts[0]>
--- [1] ---
<result for prompts[1]>Args:
prompts: List of prompts to run with the same system message.
system: Optional shared system message.
use_brain: If true, prepend .brain/context.md from cwd to the system prompt.
Inputs: prompts (required), system, use_brain. Returns: result
codebrain_consensus_generateA
Generate N candidates, let Qwen pick the best, return the winner.
Runs prompt N times (serial — Ollama serialises on single GPU anyway),
then does one additional call where Qwen is shown all candidates and
asked to return the best one verbatim. Useful for high-variance tasks
where a single shot drifts but majority-vote style sampling tightens
quality at the cost of N+1 inference calls.
Args:
prompt: The task description or content request.
system: Optional system message to steer tone / format / constraints.
n: Number of candidates to generate (default 3, clamped to [2, 5]).
use_brain: If true, prepend .brain/context.md to the system prompt.
Inputs: prompt (required), system, n, use_brain. Returns: result
codebrain_explainA
Ask the local model to explain a snippet of code (read-only, no generation).
Useful for getting quick, token-free explanations without consuming Claude's context budget on understanding-only tasks.
Args: code: The code snippet to explain. question: The specific question to answer about the code.
Inputs: code (required), question. Returns: result
codebrain_generateA
Delegate a generation task to the local Qwen-Coder model via Ollama.
Use this for bulk or routine work where a 14B local model is good enough: generating event templates, headlines, company descriptions, UI polish drafts, boilerplate, or repetitive transformations. The response is returned as raw text — review before applying.
Args:
prompt: The task description or content request.
system: Optional system message to steer tone / format / constraints.
use_brain: If true, prepend .brain/context.md from cwd to the system prompt.
Inputs: prompt (required), system, use_brain. Returns: result
codebrain_generate_verifiedA
Generate with verifier loop — enforces word limits and regex schemas.
Runs codebrain_generate, then checks the output against the requested
constraints. On failure, retries with a tightened instruction that
names the specific problem. Gives up after max_retries attempts and
returns the last output with a [codebrain warning] ... prefix.
Args:
prompt: The task description or content request.
system: Optional system message to steer tone / format / constraints.
min_words: Minimum output word count (None = unbounded).
max_words: Maximum output word count (None = unbounded).
must_match: Regex pattern the output must match (re.search semantics).
max_retries: Max retry attempts on verification failure (default 2).
use_brain: If true, prepend .brain/context.md to the system prompt.
Inputs: prompt (required), system, min_words, max_words, +3 more. Returns: result
codebrain_initA
Seed .brain/context.md for a repo — one-time setup before scanning.
Detects the stack (python / js / ts / rust / go / java) from marker
files, counts source-file extensions, asks Qwen for a short overview,
and writes .brain/context.md with a pre-populated template. The user
is expected to edit the ## Notes for Claude section afterwards.
Idempotent: existing context.md is not overwritten unless force=True.
Args:
root: Directory to initialise.
force: If true, overwrite an existing .brain/context.md.
Inputs: root (required), force. Returns: result
codebrain_polishA
Apply a targeted transform to existing text — do not regenerate from scratch.
Use this when you have a draft and want it tightened, shortened, rephrased, made more formal, translated, or similar. The system prompt forces the model into transform-mode: it must preserve meaning and structure and only apply the requested change.
Args:
text: The existing text to polish.
instructions: What transformation to apply (e.g. "shorten to 2 lines",
"make tone more formal", "translate to German").
use_brain: If true, prepend .brain/context.md from cwd to the system prompt.
Inputs: text (required), instructions (required), use_brain. Returns: result
codebrain_scan_fileA
Generate or refresh the <path>.brain summary file for a source file.
Reads the source at path, computes its SHA256, and compares to the
existing .brain file's source_hash frontmatter. If they match and
force is false, generation is skipped. Otherwise Qwen produces a new
brain file (Purpose / Key exports / Collaborators / Gotchas /
Conventions), the output is validated against the format spec, and on
validation failure one retry with a sharper instruction is attempted
before giving up. No partial or broken brain files are ever written.
Format spec: .spec/brain-file-format.md.
Args: path: Path to the source file to summarise. force: If true, regenerate even when the hash matches.
Inputs: path (required), force. Returns: result
codebrain_scan_repoA
Scan every source file under root and generate/refresh its .brain file.
Walks the directory tree, filters by file extension, prunes excluded
directories, and runs codebrain_scan_file on each match. Hash-gated:
unchanged files skip the model call. Per-file failures do not abort the
batch — they are reported at the end.
Defaults:
extensions: .py .js .ts .tsx .jsx .java .go .rs
exclude_dirs: .git .venv venv node_modules pycache dist build target
Args: root: Directory to scan recursively. force: If true, regenerate every brain file even when source hash matches. extensions: Override default source extensions (e.g. [".py", ".rb"]). exclude_dirs: Override default directory-name exclusion list.
Inputs: root (required), force, extensions, exclude_dirs. Returns: result
codebrain_statusA
Report which Ollama models are available locally.
Call this to verify the local backend is reachable and discover which models the user has pulled.
Inputs: no named parameters. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 10 tools
Each tool has a clearly distinct purpose: batch generation, consensus generation, explanation, single generation, verified generation, initialization, polishing, file scanning, repo scanning, and status. While some involve generation, they differ in process (e.g., batch vs consensus) or constraints, and descriptions make them easy to differentiate.
All tool names follow the consistent pattern 'codebrain_verb_noun' in snake_case (e.g., codebrain_batch_generate, codebrain_scan_file). The verb is always present and descriptive, with no mixing of conventions.
With 10 tools, the server is well-scoped for its purpose of local AI code assistance. Each tool earns its place, covering core operations like generation, verification, file analysis, and setup without unnecessary bloat.
The tool set covers the full lifecycle for the domain: setup (init), generation (generate, batch, consensus, verified), analysis (explain, scan_file, scan_repo), and polishing. A minor gap is the lack of a tool to delete or clear generated brain files, but this is not essential for the core workflow.
Maintenance
Related MCP Connectors
Shared memory MCP server for Claude Code, Codex, Gemini CLI and Cursor. Cited, editable.
Augments MCP Server - A comprehensive framework documentation provider for Claude Code
MCP server that gives every AI tool the same memory. Save once in Claude, use it in ChatGPT, Cursor or any MCP client: your knowledge, preferences and decisions go with you, and it learns how you work.
Persistent memory and cross-session learning for AI coding assistants (hosted remote MCP).
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceMCP server that lets Claude Code delegate mechanical tasks to a local LLM for summarization, classification, extraction, and drafting.15MIT
- FlicenseNot gradedqualityDmaintenanceMCP server that lets Claude Code offload simple tasks like code explanation, writing tests, and adding comments to a local Ollama model, saving Claude API tokens.-
- AlicenseNot gradedqualityCmaintenanceA local MCP server that delegates coding tasks to local Qwen and cloud Gemini models, enabling orchestrators like Claude Code to offload routine code generation and receive verified results with automatic correction logging.1MIT
- AlicenseAqualityCmaintenanceAn MCP server that allows Claude Code to offload mechanical tasks such as summarization, classification, and drafting to a local LLM, reducing API costs while keeping Claude in control of complex reasoning and quality review.7MIT