Skip to main content
Glama

CodeBrain

Claude Code가 자신의 하드웨어에서 실행되는 로컬 LLM으로 대량의 작업을 오프로드할 수 있게 해주는 MCP 서버입니다.

Status Stack License


이것은 무엇인가 (그리고 무엇이 아닌가)

무엇인가: Claude Code가 서브 에이전트 백엔드로 등록하는 MCP(Model Context Protocol) 서버입니다. 세션에 14B 로컬 코더 모델이 잘 처리할 수 있는 작업(이벤트 템플릿 50개 생성, React 컴포넌트 20개 다듬기, 보일러플레이트 작성 등)이 포함될 때, Claude Code는 자신의 출력 토큰을 소모하는 대신 CodeBrain을 호출합니다. 로컬 모델이 초안을 작성하고, Claude는 이를 검토하고 적용합니다.

무엇이 아닌가: Claude 대체재가 아닙니다. 추론, 아키텍처 결정, 디버깅 및 "적당히 좋은" 것으로는 부족한 모든 작업은 Claude가 담당합니다. CodeBrain은 Claude 경쟁자가 아니라 Claude 오프로더입니다.

이유: 대량의 콘텐츠 및 다듬기 작업은 Claude의 컨텍스트와 속도 제한을 빠르게 소모합니다. 무제한으로 실행할 수 있는 로컬 모델은 호출당 추가 비용이 들지 않으며, 세션의 어려운 부분을 위해 고가치의 컨텍스트를 자유롭게 유지할 수 있게 해줍니다.

Related MCP server: ollama-mcp

상태

1~4단계 완료, 5단계 보류. 9개의 도구 노출, .brain/context.md 패스스루 라이브, 파일별 브레인 요약 스캐너, 검증 루프, 합의 디코딩이 구현되었습니다. 실제 Claude Code 세션에서 MCP 통합이 검증되었습니다. 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가 이 도구를 사용하는 경우

codebrain_generate(prompt, system, use_brain)

대량 콘텐츠, 보일러플레이트, 반복적인 변환, 초안 작성

codebrain_batch_generate(prompts, system, use_brain)

공유 시스템 메시지를 사용하는 N개의 프롬프트, 직렬 실행, 인덱스 안정적 오류(하나의 실패가 배치를 중단시키지 않음)

codebrain_polish(text, instructions, use_brain)

기존 텍스트에 대한 타겟 변환 — 단축, 재구문, 번역, 다듬기. 출력 변경 없음 시 자동 재시도.

codebrain_explain(code, question)

Claude 컨텍스트를 소모하지 않는 빠른 읽기 전용 설명

codebrain_generate_verified(prompt, min_words, max_words, must_match, max_retries)

결정론적 검증 루프가 포함된 생성: 단어 수 / 정규식 스키마 검사, 위반 시 강화된 지침으로 재시도

codebrain_consensus_generate(prompt, n)

N개의 후보 + 판단 호출 → 최상의 단일 출력. 분산이 큰 작업에 사용.

codebrain_init(root, force)

1회성 저장소 온보딩: 스택 감지, .brain/context.md 템플릿 작성

codebrain_scan_file(path, force)

하나의 <source>.brain 요약 파일 생성 또는 새로 고침

codebrain_scan_repo(root, force, extensions, exclude_dirs)

트리 탐색 + 스캔; 해시 게이트 방식, 파일별 실패가 배치를 중단시키지 않음

codebrain_status()

로컬에 설치된 모델 확인

생성 도구의 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_* 도구가 사용 가능한 도구 목록에 나타납니다.

브레인 파일을 자동으로 동기화 유지

저장소에서 codebrain_init을 실행하고 codebrain_scan_repo로 스캔한 후에는 Claude가 소스를 편집할 때마다 브레인 파일이 자동으로 새로 고쳐지기를 원할 것입니다. 이를 위해 두 가지를 설정합니다:

1. 프로젝트 CLAUDE.md 스니펫 — 소스를 열기 전에 브레인 파일을 읽도록 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 훅 — 모든 편집/쓰기 작업 후 브레인을 재생성합니다.

저장소 루트의 .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가 표시됩니다.

구성

백엔드에서 읽는 환경 변수:

변수

기본값

설명

CODEBRAIN_OLLAMA_URL

http://localhost:11434

원격 Ollama를 가리킴 (예: LAN의 추론 박스)

CODEBRAIN_MODEL

qwen2.5-coder:14b

풀링한 모델로 변경

CODEBRAIN_TIMEOUT

300

단일 생성에 대한 대기 시간(초)

프로젝트 구조

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단계 — 브레인 시스템 ✓

파일별 <source>.brain 요약이 각 소스 파일 옆에 위치합니다. Claude는 브레인을 먼저 읽고 브레인으로 부족할 때만 소스를 엽니다.

  • [x] codebrain_scan_file(path, force) — 브레인 파일 생성 또는 새로 고침

  • [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 추론 호출, 분산이 큰 작업의 품질 향상.

  • 다중 패스 skeleton→logic→edges→polish: 보류 (측정된 가치가 낮음; 개별 도구로 이미 구성 가능).

5단계 — RAG (보류 — 병목 현상 아님)

브레인 파일이 이미 인덱스 역할을 합니다. 파일 간 RAG는 향후 인덱싱이 병목 현상임이 입증될 때만 의미가 있습니다. 현재는 그런 신호가 없어 구축하지 않았습니다.

라이선스

MIT — LICENSE 참조.

Available Tools

10 tools
codebrain_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

    A4.4/5.0

    Scored across 10 tools

    Disambiguation5/5

    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.

    Naming Consistency5/5

    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.

    Tool Count5/5

    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.

    Completeness4/5

    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

    ActivityInactive
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      MCP 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.
      -
    • A
      license
      Not graded
      quality
      C
      maintenance
      A 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.
      1
      MIT
    • A
      license
      A
      quality
      C
      maintenance
      An 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.
      7
      MIT