CodeBrain
CodeBrain
Claude Codeが、自身のハードウェアで実行されているローカルLLMに大量の作業をオフロードできるようにするMCPサーバーです。
これは何なのか(何ではないのか)
何なのか: Claude Codeがサブエージェントのバックエンドとして登録するModel Context Protocol (MCP) サーバーです。14Bクラスのローカルコーダーモデルが得意とするタスク(イベントテンプレートの50個生成、Reactコンポーネント20個の推敲、ボイラープレートの作成など)が含まれるセッションにおいて、Claude Codeは自身の出力トークンを消費する代わりにCodeBrainを呼び出します。ローカルモデルがドラフトを作成し、Claudeがそれをレビューして適用します。
何ではないのか: Claudeの代替品ではありません。推論、アーキテクチャの決定、デバッグ、そして「そこそこ」では不十分なあらゆる作業はClaudeが担当します。CodeBrainはClaudeのオフローダーであり、Claudeの競合相手ではありません。
なぜ必要なのか: 大量のコンテンツ作成や推敲作業は、Claudeのコンテキストとレート制限を急速に消費します。無制限に実行できるローカルモデルは呼び出しごとの追加コストがかからず、セッションの重要な部分のためにClaudeの貴重なコンテキストを温存できます。
Related MCP server: ollama-mcp
ステータス
フェーズ1〜4完了、フェーズ5は延期。 9つのツールを公開済み。.brain/context.mdのパススルー機能、ファイルごとのBrain要約スキャナー、検証ループ、コンセンサスデコーディングが実装されています。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現在、9つのツールが公開されています:
ツール | Claudeが呼び出すタイミング |
| 大量のコンテンツ、ボイラープレート、反復的な変換、初稿作成 |
| 共通のシステムメッセージを用いたN個のプロンプトの逐次実行。インデックス安定エラーにより、1つの失敗でバッチ全体が中断されない |
| 既存テキストに対するターゲット変換(短縮、言い換え、翻訳、引き締め)。出力が変化しない場合は自動再試行 |
| Claudeのコンテキストを消費しない、読み取り専用のクイック解説 |
| 決定論的な検証ループを伴う生成:単語数/正規表現スキーマチェック、違反時の指示強化再試行 |
| N個の候補を生成し、判定呼び出しを経て最適な出力を選択。分散の大きいタスクに使用 |
| リポジトリのワンショットオンボーディング:スタックを検出し、 |
| 1つの |
| ツリーを走査してスキャン。ハッシュ管理されており、ファイルごとの失敗でバッチ全体が中断されない |
| ローカルにインストールされているモデルを確認 |
生成ツールにあるuse_brainフラグは、現在の作業ディレクトリにある.brain/context.mdをシステムプロンプトの先頭に自動的に追加します。これにより、Claudeが手動で渡さなくても、プロジェクト固有のコンテキストがすべての呼び出しに引き継がれます。
要件
Python 3.11+
Ollama — OS用をダウンロード。Windowsネイティブで
localhost:11434経由の通信でテスト済み。ローカルにプルされたコーダーモデル:
ollama pull qwen2.5-coder:14b約9GBのダウンロード。Q5設定で12GBのVRAMに収まります。他のモデル(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の設定
Claude CodeのMCP設定にCodeBrainを追加します。Windowsの場合、通常は~/.claude.jsonです(パスはクローンした場所に合わせて調整してください):
{
"mcpServers": {
"codebrain": {
"command": "C:\\Users\\YOU\\Desktop\\CodeBrain\\.venv\\Scripts\\python.exe",
"args": ["-m", "codebrain"]
}
}
}Claude Codeセッションを再起動すると、5つのcodebrain_*ツールが利用可能なツールリストに表示されるはずです。
Brainファイルを自動的に同期する
リポジトリでcodebrain_initを実行し、codebrain_scan_repoでスキャンした後、Claudeがソースを編集するたびにBrainファイルを自動的に更新したい場合があるでしょう。以下の2つを設定します:
1. プロジェクトのCLAUDE.mdスニペット — ソースを開く前にBrainファイルを読み込むようClaudeに指示します:
## 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を再生成します。
リポジトリルートの.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を指定(例:LAN上の推論ボックス) |
|
| プルした任意のモデルに切り替え可能 |
|
| 1回の生成を待機する秒数 |
プロジェクト構造
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] エラーハンドリング付きOllama HTTPクライアント
[x] stdioトランスポートを備えたFastMCPサーバー
[x] 3つのコアツール:
generate,explain,status[x] ドキュメント化されたセットアップ + Claude Code設定
[x] 実際のClaude Codeセッションでの検証
フェーズ2 — バッチとコンテキスト ✓
[x] 共通のシステムプロンプトを用いた大量コンテンツ生成用の
codebrain_batch_generate、インデックス安定エラー[x] 再生成ではなくターゲット変換(短縮/言い換え/翻訳)を行う
codebrain_polish[x]
.brain/context.mdパススルー — すべての生成呼び出しにcwdプロジェクトコンテキストを自動付与[x] ドッグフーディング: コーディングタスクは堅牢、テキスト変換タスクで真の限界が判明(フェーズ3に反映)
フェーズ2.5 — Brainシステム ✓
ファイルごとの<source>.brain要約が各ソースファイルの隣に配置されます。ClaudeはまずBrainを読み、Brainで不十分な場合にのみソースを開きます。
[x]
codebrain_scan_file(path, force)— 1つのBrainファイルを生成または更新[x]
codebrain_scan_repo(root, force, extensions, exclude_dirs)— 一括走査 + スキャン[x]
codebrain_init(root, force)— スタック検出付きで.brain/context.mdをシード[x] ハッシュ管理された再生成 (SHA256) — 冪等な再実行
[x] プログラムによるフロントマター — 決定論的な
source,source_hash,model; Qwenは5つのセクションのみを記述[x] 多層防御バリデーション: フェンス除去、空ソースのスキップ(10文字未満)、セクションの存在/順序、無効時の再試行
[x] CLAUDE.md規約 + このREADME内のPostToolUseフックスニペット
フェーズ3 — VERIFIERループ ✓
ドッグフーディングにより、ローカルモデルがテキスト変換でドリフトすることが判明しました。検証機能は、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