ProjectBrain (projectbrain-mcp v1.3.0)

Zero-LSP SQLite Code Graph, <1.5s Deep Semantic & Cross-Stack Anomaly Triage, <8 KB Inline MCP Context Compiler & Sub-2s Contract Guardrail for AI Coding Agents.
ProjectBrain gives Claude Code, Cursor, Antigravity, Windsurf, and CI pipelines both Offense (<1.5s whole-repo semantic anomaly triage check --audit, <8 KB zero-spillover architectural dossiers, <20ms surgical PDG + React monolith maps, and verb-agnostic ${baseUrl} -> FastAPI/Express route tracing) and Defense (cross-stack HTTP request/response schema verification PB011, React stateful remount & async race verification PB012, Python Pydantic partial-update clobber & silent I/O swallow detection PB013, PR merge-base verification, Governance Tamper Lock, and SARIF v2.1.0) backed by a local SQLite WAL + FTS5 graph (.projectbrain.db) and lazy-loaded tree-sitter / Python ast. No LSP servers, no Docker, no cloud embeddings, and no API keys.
What's New in v1.3.0 (Deep Semantic Contracts & <1.5s Repo-Wide Anomaly Triage)
PB011Cross-Stack HTTP Request & Response Schema Solver: Deterministically verifies JS/TSfetch,axios, 1-hop client functions, and cross-file 2-hop transport wrappers against mounted FastAPI, Pydantic v1/v2 (BaseModel,SQLModel,TypedDict,@dataclass), and Express route schemas — catching missing required fields (422),camelCase <-> snake_case/ renamed payload drift,extra="forbid"violations, missingQuery(...)params, response property mismatches (includinglist[Model].map(...)items), and HTTP verb mismatches while respecting{...spread},Field(alias=...),alias_generator,extra="allow",Depends(...), and Axios.dataenvelopes with zero false positives.PB012React Stateful Lifecycle, Remount & Async Race Verifier: Catches post-mount loading/saving early-returns and ternaries that unmount stateful child components (tracking directuseState/useReducerand transitive custom hooks across files while skipping mount-only bootstrap spinners and explicitkey={...}boundaries), inline nestedPascalCasecomponent definitions (nested_component_remount), and uncancelleduseEffect([dep])asyncsetStateraces (uncancelled_async_effect_race).PB013Python Pydantic Partial-Update & Transactional I/O Hazard Verifier: CatchesPATCH/PUT/update handlers calling.model_dump()/.dict()withoutexclude_unset=Trueand overwriting persisted columns viasetattr(...)loops,.sqlmodel_update(...),.update(...), or{**existing, **dump}merges, plus completely silent broadexcept: passswallows around.commit()or outbound email/HTTP calls.<1.5sWhole-Repo Semantic Anomaly Triage (brain_check(audit=True)/projectbrain check --audit): Audits every production file in the repo (on both clean and dirty git trees, or narrowed via--scope <glob>) in<1.5s(even on939Django production files) and returnsranked_hotspotswith exactrecommended_readline spans so agents read only the flagged files instead of 80+ blindread_filecalls — strictly capped<= 7,800chars inline (0output.txtspillovers).- Retains All v1.2 Speed & Monolith Guarantees:
<8 KBinline MCP payload cap (structured_output=False), React monolith internal maps +undeclared_state_setter(Law 6), batchedgit cat-file --batchPR diffs, and built-indirect_read_hintguidance for small scopes (<=6files or<=350lines).
Why ProjectBrain? (Offense + Team/CI Defense)
AI coding agents edit fast with native Edit / edit_file tools, but routinely break uninspected callers across files, violate layer boundaries, silently delete governance rules in PRs, or burn 50k+ tokens grep-crawling monoliths. ProjectBrain solves both without forcing agents to learn a custom edit DSL:
1. Defense: Active Real-Time Hooks, PR Merge-Base CI Gate & Governance Tamper Lock
Installed automatically by projectbrain init (or OS-portable projectbrain init --team --learn for git-shared team configs and .github/workflows/projectbrain.yml):
- Silent When Clean (
0Token Tax): Non-code edits (.md,.json,.toml) exit in<30mson a pure-stdlib fast path without importing Tree-sitter. Clean body-only code edits verify incrementally via Salsa early-cutoff and emit zero bytes (exit 0). - True PR Merge-Base Diffing (
check --base main/ Automatic CI PR Detection): Audits committed multi-commit PR branches againstgit merge-base(auto-detectingGITHUB_BASE_REF,CI_MERGE_REQUEST_TARGET_BRANCH_NAME, Bitbucket, and Azure PR envs) even when the CI working tree is 100% clean — catching cross-file arity/return-key breaks, signature blast radius, broken imports from deleted/renamed files, stale invariants, and git co-change drift. - Governance Tamper Lock (
.projectbrain_memory.json): Compares.projectbrain_memory.jsonagainst the base branch and blocks--ci(UNSAFE_GOVERNANCE_TAMPER) if an agent deletes/weakens--forbidboundary rules, deletes/modifies AST invariants, wipesast_hash, or removesco_change_ruleswithout explicit human--allow-governance-change. - Zero-Config Day-1 Onboarding (
projectbrain learn/init --learn): Automatically discovers zero-violation directional layer--forbidboundaries (routes/* -> db/*,db/* -> services/*), mines high-confidence git co-change contracts, and ranks high-fan-in hub symbols on Day 1. - OASIS SARIF v2.1.0 & Zero-Noise Sticky PR Comments:
--format sarifemits Code Scanning SARIF (PB001–PB013);--format pr-commentemits sticky<!-- projectbrain-pr-guardrail -->Markdown (1-line green pass when clean; full Mermaidgraph LRblast-radius diagram + covering test suite when impactful).
2. Offense: Lean 5-Tool Zero-LSP MCP & CLI Surface (server.py)
By default (projectbrain-mcp --lean), ProjectBrain exposes 5 non-overlapping power tools so it never bloats the agent's tool-schema budget:
| MCP Tool / CLI Command | Purpose |
|---|---|
brain_dossier (projectbrain dossier) |
1-Turn Architecture Compiler: Ranks relevant files & symbols via sub-identifier BM25 + 1–2 hop call/import/state-flow edges, returning class-qualified code slices, neighbor skeletons, covering tests, and pinned invariants in ~0.2s. |
brain_slice (projectbrain slice) |
<20ms Surgical Symbol & PDG Slicer: Reads exact functions, methods (Class.method, res.send), file skeletons, or intra-function Program Dependence Graph (--focus var) slices (backward defs + forward uses + enclosing guards) directly from SQLite. |
brain_explore (projectbrain explore) |
Unified Code Graph Navigator: Traces callers/callees, shortest call/import path between target and target_b, full-stack /api/... route flows, and git co_changes. |
brain_check (projectbrain check) |
Pre-Flight Verifier, Whole-Repo Semantic Triage (--audit), PR Merge-Base Gate & SARIF/PR Reporter: Runs <1.5s whole-repo semantic & cross-stack anomaly triage (audit=True / --audit --scope), fact-checks 3-valued claims (SUPPORTED / REFUTED / UNKNOWN), audits working-tree or --base <ref> PR diffs, enforces Governance Tamper Lock, and outputs text, json, markdown, pr-comment, github, or sarif. |
brain_remember (projectbrain remember / memories) |
Git-Tracked Repo Governance (.projectbrain_memory.json): Pins symbol invariants anchored to normalized AST hashes, --forbid "<src_glob> -> <dst_glob>" layer rules, and --co-change "<file_a> <-> <file_b>" coupling contracts. |
(Pass --full or PROJECTBRAIN_FULL_TOOLS=1 to also expose auxiliary tools: brain_learn, brain_context, brain_stats, brain_run, brain_patch.)
Quick Start (60 Seconds)
1. Install (uv Recommended — Zero PEP 668 Friction)
# Recommended: isolated global CLI + MCP binaries via uv (or pipx)
uv tool install projectbrain-mcp
# Alternative: pipx
pipx install projectbrain-mcp
# Or inside an active Python virtual environment:
pip install projectbrain-mcp
2. Initialize Your Repository (Local or OS-Portable Team + CI Mode)
# Personal / local workstation setup (ENOENT-proof absolute IDE paths):
projectbrain --path /path/to/your/repo init --git-hook
# Team + CI setup (OS-portable .claude/settings.json, .cursor/hooks.json, GitHub Action, & Day-1 rule discovery):
projectbrain --path /path/to/your/repo init --team --learn
What init sets up non-destructively:
- Indexes your repository into
.projectbrain.db(SQLite WAL + FTS5) honoring.gitignoreand.git/info/exclude. - Writes
.mcp.jsonand non-destructive<!-- projectbrain:start -->workflow rules inAGENTS.md(with--team, emits zero local user/workspace paths so.claude/settings.json,.cursor/hooks.json, and.github/workflows/projectbrain.ymlcommit cleanly across macOS/Linux/Windows). - Optionally runs
learn(--learn) to auto-discover zero-violation--forbidlayer boundaries and git co-change contracts into.projectbrain_memory.json. - Keeps
.projectbrain.dbgit-ignored while leaving.projectbrain_memory.jsongit-trackable and Tamper-Locked across PRs.
3. MCP Server Configuration (or Zero-Install via uvx)
{
"mcpServers": {
"projectbrain": {
"command": "uvx",
"args": ["--from", "projectbrain-mcp", "projectbrain-mcp", "--lean", "/path/to/your/repo"]
}
}
}
4. Core CLI Workflow
# 1. Auto-discover zero-violation architectural boundaries, co-change rules & hub symbols (dry-run or --apply)
projectbrain --path /path/to/repo learn
projectbrain --path /path/to/repo learn --apply
# 2. Compile a 1-turn architecture dossier or <20ms PDG variable slice
projectbrain --path /path/to/repo dossier "how are exceptions routed to error handlers"
projectbrain --path /path/to/repo slice billing.py:compute_invoice --focus discount_total
# 3. Pin an enforceable boundary rule, co-change contract, or AST symbol invariant (git-tracked)
projectbrain --path /path/to/repo remember --forbid "routes/* -> db/*" --reason "Routes must go through services/*"
projectbrain --path /path/to/repo remember --co-change "schema.sql <-> models/user.py" --reason "Keep ORM synced"
projectbrain --path /path/to/repo remember settle_invoice "Must remain idempotent on duplicate invoice_id"
# 4. Run <1.5s whole-repo semantic anomaly triage or PR merge-base contract & governance gate
projectbrain --path /path/to/repo check --audit
projectbrain --path /path/to/repo check --base main --ci
projectbrain --path /path/to/repo check --base main --format pr-comment
projectbrain --path /path/to/repo check --base main --format sarif > projectbrain.sarif
# 5. View regression interception & code-graph scorecard
projectbrain --path /path/to/repo stats --summary
5. <2s GitHub Actions CI / PR Guardrail
name: ProjectBrain Architecture & Contract Gate
on: [pull_request]
jobs:
guardrail:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: astral-sh/setup-uv@v4
- name: Verify cross-file contracts, boundaries & blast radius
run: uvx --from projectbrain-mcp projectbrain check --ci
System Architecture
flowchart LR
subgraph Indexer["1. Lazy Tree-sitter + SQLite WAL (.projectbrain.db)"]
A["Source Files (20+ Exts)"] --> B["Lazy Tree-sitter CST + Python AST"]
B --> C["Interface Hash (Salsa Early-Cutoff)"]
C --> D[("SQLite WAL + FTS5\nfiles | symbols | edges")]
end
subgraph Offense["2. Offense: 5-Tool MCP & CLI"]
D --> DO["dossier: BM25 + 1-2 Hop Call/State Graph"]
D --> S["slice: <20ms Lookup + PDG --focus"]
D --> EX["explore: Paths + HTTP Routes + Co-Change"]
D --> CH["check: 3-Valued Verify + 4-Pillar Contracts"]
D --> RM["remember: AST-Hash Invariants + --forbid Rules"]
end
subgraph Defense["3. Defense: Real-Time Hooks & CI"]
E["Native Edit / Write / git commit"] --> F["<30ms Stdlib Filter"]
F --> G["5-Layer Audit (Silent When Clean)"]
D --> G
RM --> G
end
Honest Tradeoffs, Limitations & When to Use rg
ProjectBrain is a deterministic static AST + lexical/graph engine, not an embedding model or runtime tracer:
- When plain
rg+read_fileis better: If you already know an exact literal string, if the repo/feature touches<=6well-named files, if a file is<=350lines (<=12 KB), or if you are auditing a single giant React JSX monolith component end-to-end, nativerg+read_filein 1 turn beats adding a code-graph middleman — then runbrain_checkonce at the end as a<2scross-file & hook contract gate. - Lexical + Graph Ranking vs. Embeddings (
dossier): Indexing takes~0.1–1.5slocally with zero API keys or model downloads. If a query uses completely different words from the codebase's identifiers and docstrings (naming zero symbols), lexical ranking can miss entry points until you supply a domain term. - Static Analysis vs. Dynamic Dispatch (
verify/check): Calls through runtime-assigned variables (adapter = self.get_adapter(url); adapter.send(req)) cannot be proven to hit a single concrete class statically.dossiersurfaces candidate edges (send -> HTTPAdapter.send), whileverifyhonestly returnsUNKNOWNrather than fabricating a falseREFUTEDorSUPPORTED. - Language Tier Depth:
- Tier 1 (Python, TypeScript/JavaScript): Full AST/CST parsing (CommonJS, prototypes,
@typing.overloaddedup), intra-function PDG--focusslicing, relative/barrel/tsconfigalias resolution, route inference (FastAPI, Flask, Django, Next.js, Express, Hono), and 4-pillar cross-file contract verification. - Tier 2 (Go, Rust, Java, Kotlin, C/C++, C#, Ruby, PHP): Tree-sitter structural symbol extraction, call/import graph edges, CST PDG slicing (
.go,.rs,.java), skeletons, and boundary/syntax guardrails. - Tier 3 (SQL, GraphQL, Prisma, Protobuf, Vue/Svelte, Scala, Swift): DDL table/column/
NOT NULLconstraint extraction, schema-to-code linking, SFC script extraction, and symbol/line slicing.
- Tier 1 (Python, TypeScript/JavaScript): Full AST/CST parsing (CommonJS, prototypes,
Reproducible Benchmarks (projectbrain/eval/)
All evaluation scripts are checked into projectbrain/eval/ and enforced in CI:
# 1. Fixture regression guards, self-dogfooding, and zero-ID adversarial evaluation
python projectbrain/eval/run_eval.py
# 2. 200-file polyglot scale, incremental Salsa early-cutoff, FTS5, and recursive CTE latency benchmark
python projectbrain/eval/bench_scale.py
# 3. External repository benchmarks: pallets/flask, django/django, psf/requests, pallets/click, expressjs/express
python projectbrain/eval/bench_external.py --suite all
# 4. Full unit, guardrail, anti-leakage, security, and regression test suite (265 tests)
pytest projectbrain/tests -q
1. Held-Out External Repository Benchmark (python projectbrain/eval/bench_external.py --suite heldout)
| Repository | Dossier Questions | Target Symbol Slice Recall | Cost per Hit | Structural & Slicing Checks |
|---|---|---|---|---|
psf/requests |
4 questions (proxies, redirects/auth, cookies, adapters/pool) |
15 / 15 (100%) |
3.99 KB |
verify_claim("Session.send", "calls", "HTTPAdapter.send") -> UNKNOWN (dynamic receiver adapter.send, never false REFUTED); slice_symbols(["should_strip_auth", "get_environ_proxies"]) -> 2 / 2 |
pallets/click |
3 questions (option/arg parsing, Group subcommand dispatch, ParamType converters) |
11 / 11 (100%) |
4.35 KB |
0 bare __init__ headers (all methods qualified as ClassName.method, e.g. Group.invoke, Group.resolve_command, ParamType.convert) |
expressjs/express |
3 questions (res.send content-type, app.use mounting, app.handle dispatch) |
6 / 6 (100%) |
2.81 KB |
lib/response.js: 32 functions indexed; lib/application.js: 18 functions indexed; slice_symbols(["res.send", "app.use", "app.handle"]) -> 3 / 3 |
| Combined Held-Out Total | 10 questions | 32 / 32 (100%) |
3.89 KB |
— |
2. Scale & Incremental Latency (pallets/flask & django/django)
| Benchmark | Result |
|---|---|
pallets/flask (6 Architectural Questions) — Target Function Slice Recall |
20 / 21 (95.2%) (2.96 KB / hit) |
Whole-Repo Semantic Audit (check --audit) Across 5 OSS Repos (1,077 prod files) |
0 false positives (SAFE_TO_PROCEED on flask, requests, click, express, django; 26ms–1.03s) |
django/django (3,051 files) — Single-File Body Edit incremental_index() |
~515 ms (salsa_early_cutoff: True) |
django/django (3,051 files) — Single-File Signature Edit incremental_index() |
~894 ms (O(Δ) subgraph update) |
Cold Python Import (from projectbrain.brain import ProjectBrain) |
~150 ms (3.15x faster via lazy Tree-sitter C grammar loading) |
Non-Code Hook Bailout (projectbrain hook post-edit on .md / .json) |
< 30 ms (pure stdlib fast-path, 0 bytes emitted) |
3. Built-In Verification, Self-Dogfood & Adversarial Suite (python projectbrain/eval/run_eval.py)
| Suite | Scope | Metric | Result |
|---|---|---|---|
File Localization (eval/tasks.json) |
Fixture repos (10 tasks) | Precision / Recall | 100% / 100% |
Multi-Hop Graph vs. Grep (eval/relationship_tasks.json) |
Fixture repos (8 tasks, incl. negative controls) | Pass Rate | 8 / 8 (100%) |
Closed-World Claim Verification (eval/claim_tasks.json) |
Fixture repos (22 tasks) | Exact Verdict Accuracy | 22 / 22 (100%, 0 false refutations) |
Self-Dogfooding (compile_context) |
ProjectBrain repo (3 tasks, 6 target symbols) | Symbol Recall | 100% (6 / 6 symbols) |
Adversarial Zero-Identifier (compile_context) |
ProjectBrain repo (4 tasks, 8 target symbols; zero function names in prompt) | Symbol Recall | 87.5% (7 / 8 symbols vs 50.0% for disciplined grep) |
Metadata
Release files for projectbrain-mcp 1.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| projectbrain_mcp-1.3.0.tar.gz | 417.4 kB | Without provenance | Details for projectbrain_mcp-1.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| projectbrain_mcp-1.3.0-py3-none-any.whl | Python 3 | none | any | Details for projectbrain_mcp-1.3.0-py3-none-any.whl |
Total release size: 752.3 kB
Release files / projectbrain_mcp-1.3.0.tar.gz
| Download URL | projectbrain_mcp-1.3.0.tar.gz |
|---|---|
| Size | 417.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e3270ed703706d560b8e113047274849c159fe747e72b031af44b9c24414d291
|
|
BLAKE2b-256 checksum How to use checksums |
aed35b79922fa480cc4ee92257af8ff8d593fa7e0b740fa09f1004384f28c026
|
| 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-1.3.0-py3-none-any.whl
| Download URL | projectbrain_mcp-1.3.0-py3-none-any.whl |
|---|---|
| Size | 334.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
9eae6e875549e0a02359ba84fb0b1ebc25a8605427a76229c833b6078cca57c4
|
|
BLAKE2b-256 checksum How to use checksums |
07ecc3e36e74dde53ac657a6cee846c2da94858af3b12597dbbd2774edc5db26
|
| 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 1.3.0
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.
To learn more about protecting yourself from malicious actors, visit our package security documentation.