Skip to main content
Glama

codebrain_init

Initialize a .brain/context.md file for a repository. Detects the tech stack, generates an overview, and writes a pre-populated template to guide further scanning.

Instructions

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.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
rootYes
forceNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • MCP tool handler for 'codebrain_init'. Decorated with @mcp.tool(), it accepts a root directory and optional force flag, delegating to brain_init.init_repo().
    @mcp.tool()
    async def codebrain_init(root: str, force: bool = False) -> str:
        """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`.
        """
        return await brain_init.init_repo(root, force=force)
  • The tool's input schema is defined by the function signature: root (str, required) and force (bool, default False). The docstring serves as the description.
    @mcp.tool()
    async def codebrain_init(root: str, force: bool = False) -> str:
        """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`.
        """
        return await brain_init.init_repo(root, force=force)
  • Registration via @mcp.tool() decorator on line 284 of server.py registers 'codebrain_init' as an MCP tool.
    @mcp.tool()
  • Core implementation: init_repo() function that creates .brain/context.md — detects stack, counts extensions, queries Qwen for overview, writes template.
    async def init_repo(root: str, force: bool = False) -> str:
        """Create `.brain/context.md` for the repo rooted at `root`.
    
        Returns a human-readable status report ending with a recommended
        next-step command, or `[codebrain error] ...` on failure.
        """
        root_path = Path(root)
        if not root_path.exists():
            return f"[codebrain error] root not found: {root}"
        if not root_path.is_dir():
            return f"[codebrain error] root is not a directory: {root}"
    
        brain_dir = root_path / ".brain"
        context_path = brain_dir / "context.md"
    
        if context_path.exists() and not force:
            return (
                f"already initialized: {context_path} exists. "
                "Pass `force=True` to overwrite."
            )
    
        extension_counts = count_extensions(root_path)
        total_source_files = sum(extension_counts.values())
        top_extensions = extension_counts.most_common(TOP_EXTENSIONS_REPORTED)
        markers = detect_markers(root_path)
        stacks = infer_stacks(markers)
        top_dirs = list_top_level_dirs(root_path)[:TOP_DIRS_REPORTED]
        project_name = root_path.resolve().name
    
        overview = await _qwen_overview(
            project_name, stacks, markers, top_extensions, top_dirs
        )
    
        generated_at = dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
        content = build_context_md(
            project_name=project_name,
            overview=overview,
            stacks=stacks,
            markers=markers,
            top_extensions=top_extensions,
            total_source_files=total_source_files,
            generated_at=generated_at,
        )
    
        brain_dir.mkdir(exist_ok=True)
        context_path.write_text(content, encoding="utf-8")
    
        stack_report = ", ".join(stacks) if stacks else "unknown"
        ext_report = ", ".join(f"{ext} ({n})" for ext, n in top_extensions) or "none"
        return (
            f"Initialized `.brain/` for {project_name}.\n\n"
            f"Stack: {stack_report}\n"
            f"Top extensions: {ext_report}\n"
            f"Total source files: {total_source_files}\n\n"
            f"Written: {context_path}\n\n"
            f"Recommended next step:\n"
            f'  codebrain_scan_repo("{root_path}")'
        )
  • Helper count_extensions() used by init_repo to tally source file extensions in the repo.
    def count_extensions(
        root: Path,
        extensions: frozenset[str] | None = None,
        exclude_dirs: frozenset[str] | None = None,
    ) -> Counter[str]:
        """Return a counter of source-file extensions under `root`."""
        ext_set = extensions if extensions is not None else DEFAULT_SOURCE_EXTENSIONS
        exclude_set = exclude_dirs if exclude_dirs is not None else DEFAULT_EXCLUDE_DIRS
        counter: Counter[str] = Counter()
        for dirpath, dirnames, filenames in os.walk(root):
            dirnames[:] = [d for d in dirnames if d not in exclude_set]
            for fname in filenames:
                suffix = Path(fname).suffix.lower()
                if suffix in ext_set:
                    counter[suffix] += 1
        return counter
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.

Install Server

Other Tools

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