Metadata-Version: 2.4
Name: cortex-kg
Version: 0.5.0
Summary: Cortex: a local code knowledge graph that gives AI coding agents context over MCP.
Author-email: Roshan Gamage <roshangamage01@users.noreply.github.com>
License: MIT
Project-URL: Homepage, https://github.com/RoshanGamage01/Cortex
Project-URL: Repository, https://github.com/RoshanGamage01/Cortex
Project-URL: Documentation, https://github.com/RoshanGamage01/Cortex/tree/main/docs
Project-URL: Issues, https://github.com/RoshanGamage01/Cortex/issues
Project-URL: Changelog, https://github.com/RoshanGamage01/Cortex/releases
Keywords: knowledge-graph,mcp,engineering,ai,local-first,rag,cursor,claude-code,coding-agents,code-search
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: kuzu>=0.11
Requires-Dist: lancedb>=0.15
Requires-Dist: pyarrow>=15
Requires-Dist: fastapi>=0.110
Requires-Dist: uvicorn[standard]>=0.29
Requires-Dist: watchdog>=4.0
Requires-Dist: tree-sitter>=0.21
Requires-Dist: tree-sitter-python>=0.23
Requires-Dist: tree-sitter-javascript>=0.23
Requires-Dist: tree-sitter-typescript>=0.23
Requires-Dist: tree-sitter-go>=0.23
Requires-Dist: tree-sitter-java>=0.23
Requires-Dist: pypdf>=4.0
Requires-Dist: pillow>=10.0
Requires-Dist: cryptography>=42.0
Requires-Dist: networkx>=3.2
Requires-Dist: pydantic>=2.6
Requires-Dist: mcp<2,>=1.10
Requires-Dist: httpx>=0.27
Requires-Dist: gitpython>=3.1
Requires-Dist: pyyaml>=6.0
Requires-Dist: neo4j>=5.19
Requires-Dist: jsonschema>=4.21
Requires-Dist: python-ulid>=2.2
Requires-Dist: sse-starlette>=2.0
Requires-Dist: python-multipart>=0.0.9
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Requires-Dist: httpx2>=2.0; extra == "dev"
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: twine>=5.0; extra == "dev"
Provides-Extra: ocr
Requires-Dist: pytesseract>=0.3; extra == "ocr"
Provides-Extra: server
Requires-Dist: neo4j>=5.19; extra == "server"
Dynamic: license-file

# Cortex — a code knowledge graph for AI coding agents

Cortex indexes a repository into a local knowledge graph — every function,
class and file with its signature, location, callers and callees, plus the
docs, decisions and notes around them — and serves it to coding agents
(Claude Code, Cursor, Copilot, Codex, Gemini CLI, …) over MCP, HTTP and the
shell.

Instead of grepping and reading whole files, an agent asks one question and
gets back what it needs to act:

````text
$ cortex context "how is the natural key index kept in sync"

# Cortex context: how is the natural key index kept in sync

### `KuzuGraphStore._natural_keys` · method · src/cortex/storage/graph_store.py:211-229
`def _natural_keys(self) -> dict[tuple[str, str, str], str]`
Caller must hold ``self._lock``.
- calls: _symbol_leaf (src/cortex/storage/graph_store.py:169-173)
- called by: KuzuGraphStore.find_by_natural_key (src/cortex/storage/graph_store.py:382-385), KuzuGraphStore.find_by_natural_keys (src/cortex/storage/graph_store.py:387-403), KuzuGraphStore.symbols_named (src/cortex/storage/graph_store.py:269-279)
- member of: KuzuGraphStore (src/cortex/storage/graph_store.py:181-730)
…
````

Everything runs locally (Kuzu + LanceDB + SQLite, all embedded). No account,
no network, no model download.

## Quick start

```bash
pipx install cortex-kg        # or: python -m pip install cortex-kg

cd your-repo
cortex init                   # index it + connect the coding agents it uses
```

`cortex init` binds the repo to its own workspace, indexes it (about 3 seconds for a ~200-file repo, under 30 for 400k lines of
Python; re-runs only touch changed files) and writes the
MCP config and a short instruction block for the agents it finds in the
project. Choose explicitly with `--agents claude-code,cursor,codex` or
`--agents all`.

Then ask your agent something about the code — or try it yourself:

```bash
cortex context "what is this project?"
cortex symbol AuthService            # where is it defined?
cortex read AuthService.login        # its current source
cortex refs AuthService.login        # who calls it
cortex impact src/auth_service.py    # what breaks if this changes + tests to run
```

**Windows:** if `cortex` is “not recognized”, run `pipx ensurepath` and open a
new terminal, or use `python -m cortex …` (same CLI). Details:
[docs/installation.md](docs/installation.md#windows).

## What agents get

| Tool | Use it for |
|---|---|
| `get_context(query)` | **Start here.** A token-budgeted brief: for each result its `path:line` range, signature, docstring, what it calls / what calls it, and current source for the top hits. “What depends on X” adds an impact list; “how do I run the tests” answers from the docs. |
| `find_symbol(name)` | Where a function / class / method is defined. |
| `read_symbol(target)` | Current source of a symbol or file — no line numbers needed. |
| `file_outline(path)` | Every symbol in a file with line ranges and signatures. |
| `find_references(target)` | Direct callers, importers, subclasses (or callees with `direction="out"`). |
| `explain_impact(target)` | Transitive blast radius, affected files, tests to run. |
| `search_knowledge(query)` | Ranked candidates rather than a written brief. |
| `get_orientation()` | One-page tour of an unfamiliar repo. |
| `add_note(...)` | Record a decision or gotcha so it outlives the session. |
| `workspace_status()` / `index_path(path)` | What is indexed; index more. |

Plus review tools (`review_delta`, `review_analysis`), raw graph access
(`get_node`, `traverse`), and multi-project / multi-workspace search — 24 in
all. `cortex serve-mcp --tools core` exposes just the 11 above for agents
where every tool definition costs context.

Three properties make these safe to rely on:

- **Targets are what the agent already has.** A symbol name, a path,
  `path:line` from a stack trace, or `path#Symbol` from an earlier result.
  Node ids are never required.
- **Answers follow the working tree.** Before a result is returned, the files
  behind it are checked against the index and re-synced if they changed — so
  line ranges and call graphs reflect the agent's own uncommitted edits.
  Deleted functions and files leave the graph. Source is always read live
  from disk, never from a stored copy.
- **Output is built for a context window.** Repo-relative locations, compact
  rows, bounded lists that say when they are truncated, and a hint for what
  to do when the answer is empty.

## Supported agents

`cortex init` / `cortex setup agents --write` handle these; config files are
merged (never overwritten) and instructions go in a marked block you can
re-generate safely.

| Agent | MCP config | Instructions |
|---|---|---|
| Claude Code | `.mcp.json` | `CLAUDE.md` |
| Cursor | `.cursor/mcp.json` | `.cursor/rules/cortex.mdc` |
| VS Code (Copilot) | `.vscode/mcp.json` + `.mcp.json` | `.github/copilot-instructions.md` |
| OpenAI Codex CLI | `.codex/config.toml` (`--global` for `~/.codex`) | `AGENTS.md` |
| Gemini CLI | `.gemini/settings.json` | `GEMINI.md` |
| OpenCode | `opencode.json` | `AGENTS.md` |
| Roo Code | `.roo/mcp.json` | `.roo/rules/cortex.md` |
| Windsurf, Cline, Zed | printed for you to paste (`cortex setup <tool>`) | rules file / `AGENTS.md` |
| Claude Desktop | `cortex setup claude --write` | — |
| anything else | `cortex setup mcp` prints the generic entry | `AGENTS.md` |

Agents with only a shell can use the same tools as commands (`cortex context`,
`cortex symbol`, … or `cortex tool <name> key=value`). Anything that speaks
HTTP can `POST /tools/{name}` on the daemon.

More: **[docs/agents.md](docs/agents.md)**.

## The shared daemon and the Brain UI (optional)

The embedded graph database allows one writer process. For a single agent
that is fine — the MCP server it spawns owns the graph. To use several
clients at once (two editors, the CLI, the web UI), start the daemon and
everything talks to it instead:

```bash
cortex up        # http://127.0.0.1:8420 — REST API, /mcp, and the web UI
cortex down
```

The daemon binds to loopback, only accepts loopback `Host` headers and only
lets localhost pages read its responses: it is unauthenticated and can read
your source, so it is not exposed to the network unless you ask
(`serve-api --host`, `CORTEX_ALLOWED_HOSTS`, `CORTEX_CORS_ORIGINS`).

Open that address in a browser for the web UI: an overview of what is
indexed, a module map that stays readable on large repositories, a 3D
"universe" of every file and symbol and how they use each other, a view of
any symbol's callers / source / impact, and a preview of exactly what an
agent receives for a question. See [docs/cortex-brain.md](docs/cortex-brain.md).

## What gets indexed

- **Code** (Python, JavaScript/TypeScript, Go, Java via tree-sitter): files,
  classes, interfaces, functions and methods — private ones included — with
  signature, docstring / doc comment, line range, and `contains` / `imports` /
  `calls` / `extends` / `implements` edges. Method calls through attributes
  (`self.store.search()`) are resolved across files using the receiver's name
  as a hint and marked lower-confidence.
- **Docs**: Markdown documents and their sections (with the section text,
  commands included), ADRs, notes, PDFs, OpenAPI specs, SQL schemas. Links
  between docs, and from docs to code files, become edges.
- **History**: authors and co-change from git.
- **What agents write back** with `add_note` / `link`.

Not indexed: anything your `.gitignore` ignores, dependency and build
directories, lockfiles, minified or generated bundles, `.env` and key files,
and editor/agent config. Add a `.cortexignore` (gitignore syntax) to exclude
more or to re-include something with `!path`.

## Useful commands

```bash
cortex ingest . --project MyApp     # (re)index; incremental
cortex watch . --project MyApp      # re-sync on every save
cortex search "rate limit" --json
cortex review delta --staged        # blast radius of what you are about to commit
cortex orient                       # orientation report
cortex doctor                       # diagnose binding / config problems
cortex workspaces list
cortex tool list                    # every agent tool, callable from the shell
```

Data lives in `~/.cortex/<workspace>/` (override with `CORTEX_HOME`).

| Setting | Effect |
|---|---|
| `CORTEX_HOME` | Where workspaces are stored |
| `CORTEX_MCP_TOOLS=core` | Lean MCP tool profile |
| `CORTEX_AUTO_REFRESH=0` | Disable read-time / background re-sync |
| `CORTEX_RESPECT_GITIGNORE=0` | Index git-ignored files too |
| `CORTEX_MAX_FILE_BYTES` | Size above which a source file is treated as generated |
| `CORTEX_ALLOWED_HOSTS`, `CORTEX_CORS_ORIGINS` | Widen who may call the daemon |
| `CORTEX_DEBUG=1` | Full tracebacks from the CLI |

## Guides

| Guide | |
|---|---|
| [docs/agents.md](docs/agents.md) | **Connecting coding agents; tool reference** |
| [docs/installation.md](docs/installation.md) | Install, first run |
| [docs/project-workflow.md](docs/project-workflow.md) | Workspaces, projects, keeping the index current |
| [docs/cursor.md](docs/cursor.md) | Cursor specifics and troubleshooting |
| [docs/other-platforms.md](docs/other-platforms.md) | REST API, SDKs, CI |
| [docs/cortex-brain.md](docs/cortex-brain.md) | The web UI |
| [docs/automation.md](docs/automation.md) | Watch mode, hooks, cron |
| [SECURITY.md](SECURITY.md) | Supply-chain guards, incident record, reporting |
| [CHANGELOG.md](CHANGELOG.md) | Release notes |

## How it works

```
Sources (code, git, docs, PDFs, schemas, API specs, notes, plugins)
   -> Extractors      deterministic parsers emit candidate nodes/edges
   -> Entity resolver merges candidates, replaces what a re-extracted source
                      said before, prunes what it no longer says
   -> Storage         Kuzu (graph) · SQLite FTS5 (keyword) · LanceDB (vectors)
                      · SQLite (provenance, sync manifest, jobs, ACLs, ontology)
   -> Retrieval       keyword + vector seeds -> rank fusion -> relevance re-rank
                      -> one-hop graph expansion
   -> Context         token-budgeted briefs with live source
   -> Access          MCP (stdio / HTTP) · REST · CLI · Python/TS SDKs
```

Node and edge types are data, not code: the ontology is a registry
(`cortex.ontology.registry`) that extractors, plugins and clients extend at
runtime.

```
src/cortex/
  cli.py                 the `cortex` command
  daemon.py              CortexDaemon: owns every store for one workspace
  extractors/            code (tree-sitter), markdown, git, schema, OpenAPI, PDF, notes, …
  ingestion/             pipeline, entity resolver, ignore rules
  storage/               graph, keyword, vector and provenance stores
  retrieval/             search, ranking, target lookup, traversal / impact
  context/               context briefs and agent-facing presentation
  mcp_server/            tools.py (the one tool implementation) + transports
  setup/                 agent config generators
  sync/                  watcher, read-time freshness, change feed, job queue
  api/                   REST API, HTTP tool endpoint, Brain UI backend
  analysis/, review/     hubs, flows, orientation, change review
  security/, workspace/, versioning/, plugins/, replication/, server_profile/
sdk/                     Python and TypeScript REST clients
web/                     Web UI source (built into src/cortex/static/brain)
tests/                   213 tests
```

Design notes:

- **Embeddings are lexical by default** (`HashingEmbeddingProvider`, a hashed
  character-trigram vector) so nothing is downloaded and everything works
  offline. They add recall for docs; code retrieval leans on the name-weighted
  keyword index and the graph. A trained model can be plugged in by
  implementing `EmbeddingProvider`.
- **No type inference.** Call edges come from syntax plus naming; calls through
  attributes are best-effort and carry lower confidence than direct calls.
- **A team-scale profile** (`server_profile/`: Neo4j / Memgraph behind the same
  `GraphStore` port) exists but the embedded stores are the tested path.

## Development

```bash
git clone https://github.com/RoshanGamage01/Cortex.git && cd Cortex
git config core.hooksPath .githooks        # supply-chain scan on commit and push
python3 -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
python -m pytest tests/ -q
python scripts/security_scan.py --all-history
```

MIT licensed.
