Skip to main content
Glama

codebrain_scan_repo

Scan a repository's source files to generate or refresh .brain files, skipping unchanged files via hash comparison. Filters by file extension and excludes directories like .git and node_modules.

Instructions

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.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
rootYes
forceNo
extensionsNo
exclude_dirsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • MCP tool handler for codebrain_scan_repo. Decorated with @mcp.tool(), it delegates to brain_scanner.scan_repo().
    @mcp.tool()
    async def codebrain_scan_repo(
        root: str,
        force: bool = False,
        extensions: list[str] | None = None,
        exclude_dirs: list[str] | None = None,
    ) -> str:
        """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.
        """
        return await brain_scanner.scan_repo(
            root, force=force, extensions=extensions, exclude_dirs=exclude_dirs
        )
  • Core logic implementing scan_repo. Walks source files via iter_source_files(), calls scan_file() for each, and reports generated/skipped/failed counts.
    async def scan_repo(
        root: str,
        force: bool = False,
        extensions: list[str] | None = None,
        exclude_dirs: list[str] | None = None,
    ) -> str:
        """Scan every source file under `root` and generate/refresh its `.brain` file.
    
        Hash-gated: files whose source hash matches the existing `.brain` are
        skipped without invoking the model. Use `force=True` to override.
        Per-file failures do not abort the batch — they are reported at the end.
        """
        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}"
    
        generated: list[str] = []
        skipped: list[str] = []
        failed: list[tuple[str, str]] = []
    
        for source in iter_source_files(root_path, extensions, exclude_dirs):
            display = resolve_display_path(source)
            result = await scan_file(str(source), force=force)
            if result.startswith("generated:"):
                generated.append(display)
            elif result.startswith("skipped"):
                skipped.append(display)
            else:
                failed.append((display, result))
    
        total = len(generated) + len(skipped) + len(failed)
        lines = [
            f"Scanned {total} files: {len(generated)} generated, "
            f"{len(skipped)} skipped, {len(failed)} failed."
        ]
        if generated:
            lines.append("\nGenerated:")
            lines.extend(f"  - {p}" for p in generated)
        if failed:
            lines.append("\nFailed:")
            lines.extend(f"  - {p} — {reason}" for p, reason in failed)
        return "\n".join(lines)
  • Helper: compute SHA256 hash of source file content, used for skip-gating unchanged files.
    def compute_source_hash(content: bytes) -> str:
        """Return `sha256:<hex>` digest of raw file bytes."""
        return "sha256:" + hashlib.sha256(content).hexdigest()
  • Helper: iterates source files under root matching extensions, pruning excluded dirs via os.walk.
    def iter_source_files(
        root: Path,
        extensions: list[str] | None = None,
        exclude_dirs: list[str] | None = None,
    ) -> Iterator[Path]:
        """Yield source files under `root` matching `extensions`, pruning `exclude_dirs`.
    
        Walks the tree with `os.walk` and mutates the dirs list in-place to prune
        excluded directories before descending. Does NOT yield `.brain` files
        (the extension whitelist takes care of that implicitly).
        """
        ext_set = _normalise_extensions(extensions)
        exclude_set = frozenset(exclude_dirs) if exclude_dirs is not None else DEFAULT_EXCLUDE_DIRS
    
        for dirpath, dirnames, filenames in os.walk(root):
            dirnames[:] = [d for d in dirnames if d not in exclude_set]
            for fname in filenames:
                if Path(fname).suffix.lower() in ext_set:
                    yield Path(dirpath) / fname
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.

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