Skip to main content

ProjectBrain (projectbrain-mcp)

PyPI License: MIT Python 3.10+

Local-First AST Context Compiler, Closed-World Engineering Dossier, and Surgical Anchor Patch Engine for AI Coding Agents.

ProjectBrain indexes your codebase into a typed AST & call-graph (file, fn, cls, route, mod) in ~90ms using pre-compiled tree-sitter C wheels—no external database, no Docker, no vector embeddings, and no LLM required. It cuts coding-agent token bills by 60%–65% while speeding up multi-file debugging and editing by 30%–42%:

  • Input Token Reduction (-81.3% to -88.3% code tokens, -73.2% to -76.3% billed prompt tokens): Compiles module constants, smart-folded AST function slices, 1–3 hop bidirectional call chains with @L<line> caller windows, and a Closed-World Exhaustive Repo Scan into a single <800-line .projectbrain_dossier.md read in 1 read_file call.
  • Output Token Reduction (-63.2% to -77.3% edit output tokens): Replaces verbatim Target + Replacement repetition (edit_file) with a compact Anchor Patch DSL (@file, @sub, @replace, @insert_after, @delete) validated by Tree-sitter in <5ms.
  • Live ROI & Token Savings Ledger (projectbrain stats --summary): Tracks cumulative input/output tokens saved, file reads avoided, estimated USD saved, and developer wait-time saved in .projectbrain_ledger.json.

Step-by-Step Setup Guide (60 Seconds)

Step 1: Install from PyPI

Install projectbrain-mcp globally (or in your active Python environment):

pip install projectbrain-mcp

(Alternatively, use pipx install projectbrain-mcp or uv tool install projectbrain-mcp.)

Verify both the CLI and MCP server binaries are available:

projectbrain --help
projectbrain-mcp --help

Step 2: Initialize Your Repository (One Command)

Run projectbrain init inside any repository (or pass --path and optional --ide {all,antigravity,claude,cursor,vscode}):

projectbrain --path /path/to/your/repo init

What projectbrain init does automatically across all IDEs:

  1. Builds the AST & Call-Graph Index: Writes .projectbrain.json and .projectbrain_graph.json in ~90ms.
  2. Updates .gitignore: Ensures ephemeral index/cache files stay out of Git.
  3. Configures MCP Across IDEs: Writes/merges .mcp.json (Claude Code / Antigravity), .cursor/mcp.json (Cursor), and .vscode/mcp.json (VS Code Agent Mode).
  4. Installs Agent Rules Across IDEs: Writes AGENTS.md, .agents/rules/projectbrain.md (Antigravity), CLAUDE.md (Claude Code), .cursor/rules/projectbrain.mdc (Cursor), and .github/copilot-instructions.md + .clinerules (VS Code Copilot / Cline / Roo Code).

Step 3: Zero-Install MCP Server Configuration (Optional)

If your IDE or agent loads MCP servers from a global config file (such as .cursor/mcp.json, claude_desktop_config.json, or Antigravity mcp_config.json), add:

{
  "mcpServers": {
    "projectbrain": {
      "command": "projectbrain-mcp",
      "args": ["/path/to/your/repo"]
    }
  }
}

Or run directly with uvx (zero manual install required):

{
  "mcpServers": {
    "projectbrain": {
      "command": "uvx",
      "args": ["projectbrain-mcp", "/path/to/your/repo"]
    }
  }
}

Step 4: Parent / Monorepo Workspace Setup

If you open a parent directory in your IDE that contains multiple sub-projects (e.g., /workspace/my-app-frontend and /workspace/my-app-backend), place an AGENTS.md (or .agents/rules/projectbrain.md) at the workspace root and pass --path "<subfolder>" so the agent targets the indexed sub-repository:

# ProjectBrain Mandatory Codebase Investigation & Editing Rules

Whenever investigating, answering questions about, or modifying `<subfolder>`, ALWAYS use ProjectBrain FIRST before running shell searches (`rg`, `grep`) or multiple `read_file` calls:

1. **Compile a Single-Read Engineering Dossier (`projectbrain dossier`):**
   - Run: `projectbrain --path "<subfolder>" dossier "<question_or_bug>"`
   - Read `<subfolder>/.projectbrain_dossier.md` in one single `read_file` call (`StartLine=1, EndLine=800`).
2. **Surgical Symbol Slicing (`projectbrain slice`):**
   - Run: `projectbrain --path "<subfolder>" slice --summary <file:symbol_or_start-end>`
3. **Surgical Anchor Patching (`projectbrain patch`):**
   - Run: `projectbrain --path "<subfolder>" patch --spec "<Anchor Patch DSL>" --apply`

Step 5: Keep Git Clean (.gitignore)

If you want all local ProjectBrain caches, dossiers, diffs, and local agent configs completely ignored by Git, add the following to your .gitignore:

# ProjectBrain (local dev only)
.projectbrain*
*.projectbrain*
**/.projectbrain*
project_brain.py
test_projectbrain.json
.mcp.json
.agents/
AGENTS.md
CLAUDE.md
.claude/settings.json

(Tip: If AGENTS.md is already tracked in your repo and you want to customize it locally without Git showing it as modified, run git update-index --skip-worktree AGENTS.md.)


Daily CLI Workflow & Commands

1. Compile a Single-Read Engineering Dossier (dossier)

Before investigating a question or bug, compile a self-contained <800-line dossier (.projectbrain_dossier.md) with module globals, smart-folded AST slices, 1–3 hop call chains, and a Closed-World Exhaustive Repo Scan:

projectbrain --path /path/to/repo dossier "what role does questionnaire have in onboarding"

2. Surgically Slice Symbols or Line Ranges (slice)

Fetch exact source lines (start_line–end_line) for 1–2 symbols without reading the entire file:

projectbrain --path /path/to/repo slice --summary src/App.tsx:ProtectedRoute src/data/questionnaireData.ts:calculatePersona

3. Apply Surgical Anchor Patches (patch)

Cut output tokens by 65%–80% using the Anchor Patch DSL (@file, @sub, @replace, @insert_after, @insert_before, @delete), automatically syntax-checked by Tree-sitter:

# Dry-run (writes unified diff to .projectbrain_patch.diff)
projectbrain --path /path/to/repo patch --spec "@file src/App.tsx
@sub L84 \`!profileCompleted\` -> \`isHydrated && !profileCompleted\`"

# Apply directly to disk
projectbrain --path /path/to/repo patch --apply --spec "@file src/App.tsx
@sub L84 \`!profileCompleted\` -> \`isHydrated && !profileCompleted\`"

4. View Live ROI & Token Savings Dashboard (stats)

Check how many input/output tokens and tool calls ProjectBrain has saved across your sessions:

projectbrain --path /path/to/repo stats --summary

Example output:

===============================================================
  ProjectBrain Live ROI & Token Savings Ledger
===============================================================
  Repository         : /path/to/repo
  Total Operations   : 4
  Input Tokens Saved : 504,441 tok (16,156 delivered vs 520,597 baseline -> -96.9%)
  Output Tokens Saved: 190 tok (85 spec vs 275 edit_file -> -69.1%)
  Tool Calls Avoided : 22 file reads / multi-turn edits
===============================================================

Live auto-refreshing dashboard in terminal:

  • PowerShell (Windows):
    while ($true) { cls; projectbrain --path "/path/to/repo" stats --summary; Start-Sleep 2 }
    
  • Bash / Zsh (macOS / Linux):
    watch -n 2 projectbrain --path /path/to/repo stats --summary
    
  • Reset the ledger:
    projectbrain --path /path/to/repo stats --reset
    

5. Additional Granular CLI Tools

# Re-index repository manually (auto-updates via mtime on every command)
projectbrain --path /path/to/repo index

# Explore symbol neighborhood, route flows, or shortest path between A and B
projectbrain --path /path/to/repo explore Questionnaire setItem

# Compute blast radius (direct importers, callers, and affected tests)
projectbrain --path /path/to/repo impact src/context/CloudStateContext.tsx

# Pin an AST-anchored architectural invariant (auto-flags [STALE] if AST hash changes)
projectbrain --path /path/to/repo remember calculatePersona "Thresholds: >=22 Advanced, >=16 Intermediate, <16 Beginner"

# Fact-check a structural claim (SUPPORTED / REFUTED / UNKNOWN)
projectbrain --path /path/to/repo verify Questionnaire calls calculatePersona

# Check index coverage & parse health
projectbrain --path /path/to/repo health

MCP Tools Reference (projectbrain-mcp)

MCP Tool Purpose
brain_dossier Primary entry point. Compiles a <800-line .projectbrain_dossier.md containing module globals, smart-folded AST slices, 1–3 hop bidirectional call chains, and a Closed-World Exhaustive Repo Scan.
brain_patch Applies or dry-runs a Surgical Anchor Patch spec (@file, @sub, @replace, @insert_after, @delete) with instant Tree-sitter syntax validation.
brain_slice Fetches exact source code lines (start_line–end_line) for specific functions, classes, or file:start-end ranges without reading full files.
brain_stats Returns cumulative input/output token savings, tool calls avoided, and ROI metrics from .projectbrain_ledger.json.
brain_context Compiles a JSON surgical context packet (target_slices + skeletons + memories + session deduplication).
brain_explore Unified graph explorer (mode="neighbors", "path", "flow", or "impact") for call/dependency traversal and blast-radius analysis.
brain_check Unified 3-valued verification & safety checker (mode="claim", "batch", "plan", or "health" returning SUPPORTED / REFUTED / UNKNOWN).
brain_remember Saves or lists persistent AST-anchored architectural notes in .projectbrain_memory.json.

Verified A/B Benchmark Results (142-File Production Repo)

Benchmark Scenario Metric Baseline Agent (No Brain) ProjectBrain Agent Improvement
Scenario 1: Targeted 3-Part Engineering Analysis Code Output Ingested 67,319 tok 12,569 tok -81.3% (5.35x smaller)
Total Prompt Tokens Billed 655,391 tok 155,052 tok -76.3% (4.23x fewer)
File Reads (read_file) 16 2 -87.5%
Net API Cost $0.6723 $0.2590 -61.5% (2.60x cheaper)
Scenario 2: Unseen Open-Ended Bug Report (Zero Identifiers) Code Output Ingested 351,658 tok (1.40M chars) 40,982 tok (163.9k chars) -88.3% (8.58x smaller)
Total Prompt Tokens Billed 4,561,692 tok 1,220,579 tok -73.2% (-3.34M tokens)
File Reads (read_file) 84 (19 re-reads) 6 (0 re-reads) -92.9% (14.0x fewer reads)
Multi-File Patch Output Tokens 3,359 tok (edit_file) 529 – 1,237 tok -63.2% to -77.3% edit output
Net API Cost $3.2712 $1.1557 -64.7% (2.83x cheaper)

Project Layout

projectbrain/
├── src/projectbrain/
│   ├── brain.py        # Primary API: compile_dossier, compile_context, slice_symbols, explore, check
│   ├── slicer.py       # Surgical AST line extraction, smart folding & signature-only skeletons
│   ├── patcher.py      # Surgical Anchor Patch DSL engine + Tree-sitter syntax verifier
│   ├── ledger.py       # Live ROI & Token Savings Ledger (.projectbrain_ledger.json)
│   ├── memory.py       # Persistent AST-anchored repo memory (.projectbrain_memory.json)
│   ├── graph.py        # Typed symbol graph, qualified call resolution, BFS & shortest path
│   ├── parsers.py      # Tree-sitter extraction (signatures, schemas, AST hashes, bindings)
│   ├── resolve.py      # Python module/symbol import resolution & TS path alias resolution
│   ├── frameworks.py   # Next.js App & Pages Router convention route inference
│   ├── cli.py          # CLI entry point (init, dossier, patch, slice, stats, compile, explore, etc.)
│   └── server.py       # FastMCP server entry point (brain_dossier, brain_patch, brain_stats, etc.)
├── tests/              # Comprehensive pytest suite
└── eval/               # Evaluation harness, fixtures, and self-dogfooding benchmark

Metadata

Release files for projectbrain-mcp 0.2.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for projectbrain-mcp 0.2.2
File Size Uploaded Provenance
projectbrain_mcp-0.2.2.tar.gz 104.6 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for projectbrain-mcp 0.2.2
File Interpreter ABI Platform
projectbrain_mcp-0.2.2-py3-none-any.whl Python 3 none any Details

Total release size: 191.6 kB

Release files / projectbrain_mcp-0.2.2.tar.gz

Download URL projectbrain_mcp-0.2.2.tar.gz
Size 104.6 kB
Tags Source
SHA-256 checksum
How to use checksums
c932f02f7551cb50eaa90e217d1ee073034b61ae5b25d587bd3ac3e6b5b6c89d
BLAKE2b-256 checksum
How to use checksums
d61f3dbc4495683777adc20817054a59c7fcc202d0e4032e1dded700041da303
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.5

Release files / projectbrain_mcp-0.2.2-py3-none-any.whl

Download URL projectbrain_mcp-0.2.2-py3-none-any.whl
Size 87.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e8e94a61636d6ad4fd29ed51021ad45276255906ad167600d83aa1d993f657d8
BLAKE2b-256 checksum
How to use checksums
f547092d4e37569dc8629bfe0ca32496cfd743df5657f0835e96e30f25f0b706
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.5

Security for projectbrain-mcp 0.2.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page