Skip to main content
Glama

CodeBrain

MCP-сервер, который позволяет Claude Code перекладывать объемную работу на локальную LLM, запущенную на вашем собственном оборудовании.

Status Stack License


Что это (и чем не является)

Является: 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 обращается к нему

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)

Генерация с детерминированным циклом верификации: проверка количества слов / regex-схемы, повтор с уточненными инструкциями при нарушении

codebrain_consensus_generate(prompt, n)

N кандидатов + вызов судьи → лучший единичный результат. Используйте для задач с высокой вариативностью.

codebrain_init(root, force)

Однократная настройка репозитория: определяет стек, записывает шаблон .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скачать для вашей ОС. Протестировано с 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 в списке.

Конфигурация

Переменные окружения, считываемые бэкендом:

Переменная

По умолчанию

Что делает

CODEBRAIN_OLLAMA_URL

http://localhost:11434

Укажите на удаленный Ollama (например, сервер вывода в вашей локальной сети)

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

ParametersJSON Schema
NameRequiredDescriptionDefault
promptsYes
systemNo
use_brainNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.6/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description fully covers behavioral traits: serial processing, inline error handling without aborting, shared system prompt, effect of use_brain parameter, and the exact output format with delimiters. This is comprehensive.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise (~150 words), front-loaded with the purpose, and well-structured with bullet points and an example of the output. Every sentence adds value without redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (batch processing, error handling, output format), the description covers all necessary aspects: parameters, behavior, failure mode, and return structure. There are no gaps.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must explain parameters. It does so effectively: prompts as list of strings, system as optional shared message, and use_brain as flag to prepend a context file. This adds significant meaning beyond the schema's minimal metadata.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: running several generation prompts in sequence and returning all results. It effectively distinguishes itself from siblings by emphasizing batch processing and serial execution.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explains the shared system prompt and serial processing but lacks explicit guidance on when to use this tool versus alternatives like codebrain_generate (single) or codebrain_consensus_generate. It implies usage scenarios but does not state when-not-to-use or name specific alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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.

ParametersJSON Schema
NameRequiredDescriptionDefault
promptYes
systemNo
nNo
use_brainNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.4/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description fully discloses behavior: serial execution, N+1 calls, Qwen selecting the best, clamping of n to [2,5], and use_brain prepending context. It does not cover error handling, but the core behavioral traits are clearly stated.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with a summary sentence, explanation, and Args block. It is slightly verbose but every sentence adds value. It earns a 4 for being clear and organized without excess.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the existence of an output schema (not shown), the description does not need to detail return values. It covers the process, parameter usage, and typical use case. The description provides sufficient context for the tool's operation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 0%, but the description includes an Args section explaining each parameter: prompt (required), system (optional steering), n (default and clamping), and use_brain (context prepending). This adds full meaning beyond the bare schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool generates N candidates and lets Qwen pick the best, returning the winner. It distinguishes itself from single-shot generation by noting it is for high-variance tasks, making the purpose specific and distinct from siblings like codebrain_generate.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description explicitly advises using this tool for high-variance tasks where a single shot drifts, and mentions the cost of N+1 inference calls. While it does not list all alternatives, it provides clear context for when to use it, earning a high score.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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.

ParametersJSON Schema
NameRequiredDescriptionDefault
codeYes
questionNoWhat does this do?

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided, so description carries full burden. It discloses 'read-only, no generation' and mentions 'local model', but lacks details on failure modes, required permissions, or other behavioral traits.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is compact: two sentences plus an Args block. Every line adds value with no redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's simplicity (2 params, output schema exists), the description covers purpose and usage adequately. Parameter details are minimal but sufficient for basic use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 0%, so description must compensate. It provides basic descriptions for 'code' and 'question', but lacks format, constraints, or examples, so it adds minimal value beyond the schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description explicitly states 'explain a snippet of code' and distinguishes from siblings with 'read-only, no generation', directly contrasting with the generation tools like codebrain_generate.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

It clearly indicates when to use: 'for getting quick, token-free explanations without consuming Claude’s context budget on understanding-only tasks.' It implies alternatives by stating 'no generation', but does not explicitly name siblings or exclusions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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.

ParametersJSON Schema
NameRequiredDescriptionDefault
promptYes
systemNo
use_brainNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A3.9/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden. It discloses that the response is raw text and advises reviewing before applying. It also explains the optional system message and use_brain flag, offering good insight into tool behavior without omissions.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise (approx. 100 words), front-loaded with purpose, and structured as a brief intro followed by parameter explanations. Every sentence adds value without redundancy, making it easy for an agent to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity and the presence of an output schema (though not shown), the description covers the core aspects: what it does, when to use it, parameters, and output nature. It omits potential limitations (e.g., model capabilities) but is generally sufficient for selection and invocation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Input schema has 0% description coverage, so the description must compensate. It explains the 'prompt' as task description, 'system' as steering message, and 'use_brain' as prepending context. This adds essential meaning beyond the schema's bare titles, though it could include format hints.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states that the tool delegates a generation task to a local Qwen-Coder model via Ollama, providing specific use cases. It distinguishes the tool's role for bulk or routine work, but does not explicitly differentiate from siblings like codebrain_batch_generate or codebrain_generate_verified, which limits clarity of its niche.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description gives context for when to use the tool ('bulk or routine work where a 14B local model is good enough') and lists example tasks. However, it does not specify when not to use it or mention alternative sibling tools, leaving the agent without explicit decision boundaries.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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.

ParametersJSON Schema
NameRequiredDescriptionDefault
promptYes
systemNo
min_wordsNo
max_wordsNo
must_matchNo
max_retriesNo
use_brainNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.6/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations exist, so the description bears full responsibility. It details retry behavior, warning prefix, and parameter effects. It lacks mention of side effects, permissions, or rate limits, but for a generation tool this is acceptable.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise: a one-line summary followed by a well-organized bullet list of parameters. Every sentence adds value with no redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (7 parameters, no annotations), the description thoroughly explains behavior (verification loop, retries, warning) and all parameters. Output schema existence doesn't weaken completeness.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema has 0% description coverage, but the description provides a detailed Args list explaining each parameter's meaning and defaults, adding significant value beyond the schema types.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states it generates with a verifier loop, enforcing word limits and regex schemas. It distinguishes from sibling tools like codebrain_generate by introducing verification and retry logic.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

It explains the tool's use case: constrained generation with automatic retry on failure. While it doesn't explicitly state when not to use or mention alternatives, the purpose is clear and the description provides context for when to apply verification.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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.

ParametersJSON Schema
NameRequiredDescriptionDefault
rootYes
forceNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.6/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description fully discloses behavior: stack detection, source file counting, LLM query, template writing, and idempotency (force flag). It also notes the expected user edit. No contradictions.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Concise, well-structured paragraph. First sentence states core purpose, followed by step details and idempotency note. No superfluous text.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The description covers the tool's actions (detection, counting, writing) and side effects (context.md creation). Idempotency and user editing are noted. Absence of return value explanation is minor given the side effect focus.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description adds meaning to both parameters: 'root' as the directory to initialize and 'force' enabling overwrite. Despite 0% schema coverage, it compensates well by explaining effects, though it could explicitly state defaults.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Seed .brain/context.md for a repo — one-time setup before scanning.' It specifies the verb (seed), the resource (context.md), and context (one-time setup), distinguishing it from sibling scanning tools.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Description indicates it's a one-time setup before scanning and advises user to edit the '## Notes for Claude' section afterward. It does not explicitly list when not to use it, but the context of sibling tools implies alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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.

ParametersJSON Schema
NameRequiredDescriptionDefault
textYes
instructionsYes
use_brainNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.3/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description effectively explains the transform-mode: preserve meaning and structure, only apply requested change. Also describes the use_brain parameter effect. No mention of destructive or auth details, but adequate for a non-destructive transform.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two paragraphs plus Args section, concise and clearly structured. The Args section is somewhat redundant with schema titles but adds context. Could be slightly tighter.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given low complexity and presence of output schema, description covers core behavior adequately. Does not address errors or edge cases, but sufficient for a simple transform tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 0%, but the description adds detailed parameter explanations in Args section, including examples for instructions and behavior for use_brain. This compensates well for the missing schema descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Description clearly states the tool applies a targeted transform to existing text, not generating from scratch, with specific examples (tighten, shorten, rephrase, formal, translate). This distinguishes it from sibling generation tools like codebrain_generate.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly tells when to use ('when you have a draft and want it...') and implies not for generation. However, it does not explicitly exclude alternatives or provide when-not-to-use guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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.

ParametersJSON Schema
NameRequiredDescriptionDefault
pathYes
forceNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.3/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description fully discloses the tool's behavior: reads source, computes SHA256, compares with existing .brain file, conditionally skips or regenerates using Qwen, validates output against a spec, performs one retry on validation failure, and guarantees no partial writes. This is thorough and honest.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured: a brief summary sentence, followed by a detailed step-by-step explanation, reference to a format spec, and finally an Args section. Every sentence adds value, and the length is appropriate for the tool's complexity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given that the tool has an output schema (not shown), the description covers the major aspects: input parameters, core logic, validation, retry, and write safety. However, it does not address error scenarios such as file not found or permission issues, which would be helpful for an agent.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema provides only titles and types (0% coverage), so the description carries the full burden. It clearly explains 'path' as the source file to summarise and 'force' as a flag to force regeneration even when hash matches. Both parameters are well-described, adding essential meaning beyond the schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states it generates or refreshes a .brain summary file for a single source file. The verb 'scan' and the process described (hash comparison, validation) differentiate it from siblings like codebrain_scan_repo (which likely scans entire repos), but it does not explicitly name alternatives.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies that this tool is for individual files (via the 'path' argument and talk of source files), but it provides no explicit guidance on when to use this tool versus siblings like codebrain_batch_generate or codebrain_scan_repo. The conditions under which regeneration is skipped are explained, but alternatives are not mentioned.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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.

ParametersJSON Schema
NameRequiredDescriptionDefault
rootYes
forceNo
extensionsNo
exclude_dirsNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.4/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Discloses key behaviors: directory walk, filtering, pruning, hash-gating, failure handling. No annotations exist, so description carries the burden; it does so well.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Concise yet informative: core purpose first, then behavioral details, defaults, and parameter list. No unnecessary verbiage.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Covers overall process, defaults, error handling. Lacks detailed return value explanation but output schema exists. Sufficient for understanding tool's role.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Input schema has 0% description coverage, but the 'Args' section in the description explains each parameter (root, force, extensions, exclude_dirs), adding value where the schema lacks.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Clearly states the action (scan and generate/refresh .brain files) and resource (source files under root). Distinguishes from siblings like codebrain_scan_file (single file) by specifying batch processing.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Provides context on behavior (hash-gated, per-file failures non-aborting) and defaults. Does not explicitly compare to siblings like codebrain_batch_generate, but the batch scope is clear.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.4/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided, but the description indicates a read-only check (report models, verify backend). Does not mention side effects or permissions, but the simple nature of the tool makes this sufficient.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two sentences, 24 words total. Every word adds value. Front-loaded with action ('Report...') followed by usage advice. No wasted text.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a simple, parameterless status tool with an output schema, the description provides the essential purpose and usage context. It is complete enough for an agent to decide when to call it among siblings.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

No parameters in input schema, so description does not need to add parameter info. Schema coverage is 100% (empty). Baseline score of 4 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Clearly states it reports locally available Ollama models and can verify backend reachability. Differentiates from sibling tools like codebrain_generate (which generate responses) and codebrain_init (which sets up context).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly tells the agent to call this to verify backend reachability and discover pulled models. Provides clear context for when to use it, though no mention of when not to use or alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.

  1. 10 tool updatesv0.1.0
    • First observedcodebrain_batch_generate
    • First observedcodebrain_consensus_generate
    • First observedcodebrain_explain
    • First observedcodebrain_generate
    • First observedcodebrain_generate_verified
    • First observedcodebrain_init
    • First observedcodebrain_polish
    • First observedcodebrain_scan_file
    • First observedcodebrain_scan_repo
    • First observedcodebrain_status

TDQS

A4.4/5.0
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
ResponsivenessSyncing

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    C
    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
    B
    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.
    MIT
  • A
    license
    Not graded
    quality
    D
    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.
    12
    MIT

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Tschonsen/CodeBrain'

If you have feedback or need assistance with the MCP directory API, please join our Discord server