ethicaldilkhush-code-context-mcp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. ethicaldilkhush_code_context_mcp-0.1.0/.cursor/mcp.json +8 -0
  2. ethicaldilkhush_code_context_mcp-0.1.0/.gitignore +9 -0
  3. ethicaldilkhush_code_context_mcp-0.1.0/LICENSE +21 -0
  4. ethicaldilkhush_code_context_mcp-0.1.0/PKG-INFO +329 -0
  5. ethicaldilkhush_code_context_mcp-0.1.0/README.md +283 -0
  6. ethicaldilkhush_code_context_mcp-0.1.0/examples/demo_client.py +146 -0
  7. ethicaldilkhush_code_context_mcp-0.1.0/pyproject.toml +76 -0
  8. ethicaldilkhush_code_context_mcp-0.1.0/src/code_context_mcp/__init__.py +8 -0
  9. ethicaldilkhush_code_context_mcp-0.1.0/src/code_context_mcp/__main__.py +5 -0
  10. ethicaldilkhush_code_context_mcp-0.1.0/src/code_context_mcp/chunker.py +993 -0
  11. ethicaldilkhush_code_context_mcp-0.1.0/src/code_context_mcp/cli.py +479 -0
  12. ethicaldilkhush_code_context_mcp-0.1.0/src/code_context_mcp/config.py +138 -0
  13. ethicaldilkhush_code_context_mcp-0.1.0/src/code_context_mcp/embeddings.py +245 -0
  14. ethicaldilkhush_code_context_mcp-0.1.0/src/code_context_mcp/errors.py +27 -0
  15. ethicaldilkhush_code_context_mcp-0.1.0/src/code_context_mcp/indexer.py +372 -0
  16. ethicaldilkhush_code_context_mcp-0.1.0/src/code_context_mcp/languages.py +377 -0
  17. ethicaldilkhush_code_context_mcp-0.1.0/src/code_context_mcp/models.py +63 -0
  18. ethicaldilkhush_code_context_mcp-0.1.0/src/code_context_mcp/relations.py +347 -0
  19. ethicaldilkhush_code_context_mcp-0.1.0/src/code_context_mcp/scanner.py +175 -0
  20. ethicaldilkhush_code_context_mcp-0.1.0/src/code_context_mcp/search.py +295 -0
  21. ethicaldilkhush_code_context_mcp-0.1.0/src/code_context_mcp/server.py +358 -0
  22. ethicaldilkhush_code_context_mcp-0.1.0/src/code_context_mcp/service.py +669 -0
  23. ethicaldilkhush_code_context_mcp-0.1.0/src/code_context_mcp/store.py +644 -0
  24. ethicaldilkhush_code_context_mcp-0.1.0/src/code_context_mcp/textutil.py +95 -0
  25. ethicaldilkhush_code_context_mcp-0.1.0/src/code_context_mcp/watcher.py +74 -0
  26. ethicaldilkhush_code_context_mcp-0.1.0/tests/__init__.py +0 -0
  27. ethicaldilkhush_code_context_mcp-0.1.0/tests/conftest.py +51 -0
  28. ethicaldilkhush_code_context_mcp-0.1.0/tests/fixtures/polyglot/Account.java +30 -0
  29. ethicaldilkhush_code_context_mcp-0.1.0/tests/fixtures/polyglot/Cart.kt +35 -0
  30. ethicaldilkhush_code_context_mcp-0.1.0/tests/fixtures/polyglot/GUIDE.md +18 -0
  31. ethicaldilkhush_code_context_mcp-0.1.0/tests/fixtures/polyglot/Mailer.php +27 -0
  32. ethicaldilkhush_code_context_mcp-0.1.0/tests/fixtures/polyglot/Orders.cs +33 -0
  33. ethicaldilkhush_code_context_mcp-0.1.0/tests/fixtures/polyglot/Profile.swift +32 -0
  34. ethicaldilkhush_code_context_mcp-0.1.0/tests/fixtures/polyglot/View.tsx +13 -0
  35. ethicaldilkhush_code_context_mcp-0.1.0/tests/fixtures/polyglot/api.ts +34 -0
  36. ethicaldilkhush_code_context_mcp-0.1.0/tests/fixtures/polyglot/billing.rb +23 -0
  37. ethicaldilkhush_code_context_mcp-0.1.0/tests/fixtures/polyglot/buffer.c +25 -0
  38. ethicaldilkhush_code_context_mcp-0.1.0/tests/fixtures/polyglot/deploy.sh +15 -0
  39. ethicaldilkhush_code_context_mcp-0.1.0/tests/fixtures/polyglot/lib.rs +36 -0
  40. ethicaldilkhush_code_context_mcp-0.1.0/tests/fixtures/polyglot/schema.sql +7 -0
  41. ethicaldilkhush_code_context_mcp-0.1.0/tests/fixtures/polyglot/server.go +30 -0
  42. ethicaldilkhush_code_context_mcp-0.1.0/tests/fixtures/polyglot/shapes.py +35 -0
  43. ethicaldilkhush_code_context_mcp-0.1.0/tests/fixtures/polyglot/store.js +51 -0
  44. ethicaldilkhush_code_context_mcp-0.1.0/tests/fixtures/polyglot/widget.hpp +25 -0
  45. ethicaldilkhush_code_context_mcp-0.1.0/tests/test_chunker.py +108 -0
  46. ethicaldilkhush_code_context_mcp-0.1.0/tests/test_indexer.py +188 -0
  47. ethicaldilkhush_code_context_mcp-0.1.0/tests/test_notes.py +66 -0
  48. ethicaldilkhush_code_context_mcp-0.1.0/tests/test_relations.py +87 -0
  49. ethicaldilkhush_code_context_mcp-0.1.0/tests/test_search.py +88 -0
  50. ethicaldilkhush_code_context_mcp-0.1.0/tests/test_server.py +140 -0
@@ -0,0 +1,8 @@
1
+ {
2
+ "mcpServers": {
3
+ "code-context": {
4
+ "command": "${workspaceFolder}/.venv/bin/code-context",
5
+ "args": ["serve", "${workspaceFolder}"]
6
+ }
7
+ }
8
+ }
@@ -0,0 +1,9 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .pytest_cache/
8
+ .code-context/
9
+ .DS_Store
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ethicaldilkhush
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,329 @@
1
+ Metadata-Version: 2.5
2
+ Name: ethicaldilkhush-code-context-mcp
3
+ Version: 0.1.0
4
+ Summary: A Code Context MCP server: structural indexing, hybrid semantic/keyword code search, relationship exploration and persistent codebase notes for AI coding assistants.
5
+ Project-URL: Homepage, https://github.com/ethicaldilkhush/code_context_mcp
6
+ Project-URL: Repository, https://github.com/ethicaldilkhush/code_context_mcp
7
+ Project-URL: Issues, https://github.com/ethicaldilkhush/code_context_mcp/issues
8
+ Author: ethicaldilkhush
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: ai,code-search,coding-assistant,embeddings,mcp,model-context-protocol,semantic-search
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development
20
+ Classifier: Topic :: Software Development :: Libraries
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.11
23
+ Requires-Dist: fastembed>=0.5
24
+ Requires-Dist: mcp<3,>=2.0
25
+ Requires-Dist: numpy>=1.26
26
+ Requires-Dist: pathspec>=0.12
27
+ Requires-Dist: tree-sitter-bash>=0.23
28
+ Requires-Dist: tree-sitter-c-sharp>=0.23
29
+ Requires-Dist: tree-sitter-c>=0.23
30
+ Requires-Dist: tree-sitter-cpp>=0.23
31
+ Requires-Dist: tree-sitter-go>=0.23
32
+ Requires-Dist: tree-sitter-java>=0.23
33
+ Requires-Dist: tree-sitter-javascript>=0.23
34
+ Requires-Dist: tree-sitter-kotlin>=1.0
35
+ Requires-Dist: tree-sitter-php>=0.23
36
+ Requires-Dist: tree-sitter-python>=0.23
37
+ Requires-Dist: tree-sitter-ruby>=0.23
38
+ Requires-Dist: tree-sitter-rust>=0.23
39
+ Requires-Dist: tree-sitter-swift>=0.7
40
+ Requires-Dist: tree-sitter-typescript>=0.23
41
+ Requires-Dist: tree-sitter>=0.23
42
+ Requires-Dist: watchfiles>=0.21
43
+ Provides-Extra: dev
44
+ Requires-Dist: pytest>=8; extra == 'dev'
45
+ Description-Content-Type: text/markdown
46
+
47
+ # Code Context MCP
48
+
49
+ A Model Context Protocol server that gives AI coding assistants a persistent,
50
+ searchable understanding of a codebase. It indexes a repository at structural
51
+ boundaries (functions, methods, classes, ...), embeds every chunk, stores it
52
+ all in SQLite, and exposes hybrid semantic + keyword search, relationship
53
+ exploration and a knowledge-note memory through MCP tools. The index stays in
54
+ sync with the working tree, so assistants stop rediscovering the project each
55
+ session.
56
+
57
+ ```
58
+ repository ──scan──► changed files ──tree-sitter──► chunks + metadata ──embed──► SQLite
59
+ (.gitignore aware) (size/mtime/hash) (15 grammars) (calls, bases, imports) (fastembed) (FTS5 + vectors + notes)
60
+ │
61
+ AI assistant ◄──── MCP (stdio / HTTP) ◄──── hybrid search · relationships · notes ◄──────────┘
62
+ ```
63
+
64
+ ## Install
65
+
66
+ Requires Python 3.11+.
67
+
68
+ ```bash
69
+ # recommended: isolated CLI install
70
+ pipx install ethicaldilkhush-code-context-mcp
71
+
72
+ # or with uv
73
+ uv tool install ethicaldilkhush-code-context-mcp
74
+
75
+ # or into a virtualenv
76
+ pip install ethicaldilkhush-code-context-mcp
77
+ ```
78
+
79
+ The first semantic index downloads the local embedding model (~70 MB, once).
80
+ After that the default setup runs offline. Use `--embedder hash` to skip the
81
+ model for a fast lexical-only mode.
82
+
83
+ ```bash
84
+ code-context index /path/to/repo
85
+ code-context search -r /path/to/repo "where are retries handled"
86
+ code-context serve /path/to/repo # MCP server on stdio
87
+ ```
88
+
89
+ Every CLI command takes `-r/--repo` (default: `$CODE_CONTEXT_REPO` or the
90
+ current directory) and `--json`. Commands: `index [--full] [--watch]`,
91
+ `status`, `search`, `context`, `show <chunk_id>`, `related <chunk_id | -s symbol>`,
92
+ `outline <file>`, `symbol <name>`, `overview`, `notes add|list|search|delete`, `serve`.
93
+
94
+ ### Develop from this repository
95
+
96
+ ```bash
97
+ python3 -m venv .venv && .venv/bin/pip install -e ".[dev]"
98
+ .venv/bin/code-context --version
99
+ .venv/bin/python -m pytest
100
+ ```
101
+
102
+ ## Connecting an AI assistant
103
+
104
+ The server speaks MCP over stdio by default (`--transport http` serves
105
+ streamable HTTP on `127.0.0.1:8765/mcp`). On startup it indexes in the
106
+ background and then watches the repository for changes.
107
+
108
+ **Cursor** (`.cursor/mcp.json` or `~/.cursor/mcp.json`):
109
+
110
+ ```json
111
+ {
112
+ "mcpServers": {
113
+ "code-context": {
114
+ "command": "uvx",
115
+ "args": ["ethicaldilkhush-code-context-mcp", "serve", "${workspaceFolder}"]
116
+ }
117
+ }
118
+ }
119
+ ```
120
+
121
+ If you installed with `pipx`, use the installed binary instead:
122
+
123
+ ```json
124
+ {
125
+ "mcpServers": {
126
+ "code-context": {
127
+ "command": "code-context",
128
+ "args": ["serve", "${workspaceFolder}"]
129
+ }
130
+ }
131
+ }
132
+ ```
133
+
134
+ This repository also ships a local `.cursor/mcp.json` that points at the
135
+ editable `.venv` install for development.
136
+
137
+ **Claude Code**:
138
+
139
+ ```bash
140
+ claude mcp add code-context -- uvx ethicaldilkhush-code-context-mcp serve /path/to/repo
141
+ ```
142
+
143
+ **Claude Desktop** (`claude_desktop_config.json`): same `command`/`args`
144
+ shape as above with an absolute repository path.
145
+
146
+ **MCP Inspector** (interactive testing):
147
+
148
+ ```bash
149
+ npx @modelcontextprotocol/inspector uvx ethicaldilkhush-code-context-mcp serve /path/to/repo
150
+ npx @modelcontextprotocol/inspector --cli uvx ethicaldilkhush-code-context-mcp serve /path/to/repo \
151
+ --method tools/call --tool-name search_code --tool-arg query="parse config file"
152
+ ```
153
+
154
+ The server can also start with no repository; the assistant then calls
155
+ `index_repository(path=...)` to choose one, and can switch repositories the same way.
156
+
157
+ ## MCP interface
158
+
159
+ | Tool | Purpose |
160
+ | --- | --- |
161
+ | `index_repository` | Index or update incrementally (`full_rebuild`, or `path` to switch repos). Waits up to `wait_seconds`, then keeps going in the background. |
162
+ | `index_status` | State, progress, per-language counts, embedding coverage, files with issues, recent runs, on-disk freshness. |
163
+ | `search_code` | Hybrid / semantic / keyword search with `language`, `kind` and `path` filters. |
164
+ | `get_context` | One call for a task: top results with full source, their calls and callers, more locations, relevant notes. |
165
+ | `find_symbol` | Definitions by name or qualified name (`Server.Start`, `billing::Invoice`). |
166
+ | `get_code` | Complete source of a result, plus parent, members, file notes and optional live surrounding lines. |
167
+ | `read_file` | Read a file or line range from disk, confined to the repository. |
168
+ | `get_file_outline` | Symbols of a file with line ranges and signatures, its imports and its importers. |
169
+ | `get_related` | Calls, callers, base types, subclasses, members and file dependencies, each with a confidence level. |
170
+ | `get_call_graph` | Multi-level call graph (`out` = callees, `in` = callers). |
171
+ | `repository_overview` | Languages, layout, entry points, most referenced symbols, largest types, README intro, notes. |
172
+ | `save_note` / `update_note` / `delete_note` | Persistent knowledge, optionally linked to a path and/or symbol. |
173
+ | `search_notes` / `list_notes` | Retrieve knowledge by meaning, tag or path. |
174
+
175
+ Resources: `codecontext://overview`, `codecontext://status`, `codecontext://notes`.
176
+ Prompt: `explore_codebase(task)` walks an assistant through orient → gather context → follow relationships → record notes.
177
+
178
+ All results are structured JSON. Every chunk carries `chunk_id`, `path`,
179
+ `start_line`/`end_line`, `location`, `language`, `kind`, `name`,
180
+ `qualified_name`, `signature`, `docstring`, `calls` and `bases`. Search
181
+ results add `score`, `matched_by` (`semantic`, `keyword`, `exact_name`, ...)
182
+ and a preview.
183
+
184
+ ## How it works
185
+
186
+ **Scanning** (`scanner.py`): uses `git ls-files` when available, so
187
+ `.gitignore` is honoured exactly; otherwise it walks the tree with the root
188
+ `.gitignore`. Dependency and build directories, minified and generated files,
189
+ empty files and files over `max_file_kb` are skipped, and the skips are
190
+ counted by reason in the index report.
191
+
192
+ **Parsing and chunking** (`chunker.py`, `languages.py`): tree-sitter grammars
193
+ for Python, JavaScript, TypeScript, TSX, Go, Rust, Java, C, C++, C#, Ruby,
194
+ PHP, Swift, Kotlin and Bash. Each function, method, constructor, class,
195
+ interface, struct, enum, trait, impl, protocol, extension or type alias
196
+ becomes a chunk. The chunk includes its decorators and leading doc comments
197
+ and records:
198
+
199
+ - the qualified name (`ns.Class.method`; Go receivers and out-of-line C++ methods are attached to their type);
200
+ - the signature and docstring;
201
+ - the parent chunk;
202
+ - base types;
203
+ - called names;
204
+ - the file's imports.
205
+
206
+ Classes are embedded as a skeleton with member bodies elided, so they don't
207
+ drown out their methods. Code between definitions becomes `module` chunks.
208
+ Markdown is split by heading and other text by blank-line-aware windows.
209
+ Syntax errors don't stop parsing: the file is flagged and still chunked.
210
+
211
+ **Embeddings** (`embeddings.py`): the default is local `fastembed`
212
+ (`BAAI/bge-small-en-v1.5`, ONNX, CPU, no API key). `openai` uses any
213
+ OpenAI-compatible `/embeddings` endpoint. `hash` is a deterministic
214
+ feature-hashing embedder that needs no model. With the default `auto`
215
+ setting, the server falls back to `hash` when the model can't load, and
216
+ reports this in the status output.
217
+
218
+ **Storage** (`store.py`): one SQLite database per repository, by default under
219
+ `~/.code-context/indexes/`, in WAL mode so the CLI and a running server can
220
+ share it. It holds:
221
+
222
+ - files (hash, mtime, status, issues);
223
+ - chunks (metadata, source, float32 embedding);
224
+ - an FTS5 table;
225
+ - call and inheritance references;
226
+ - imports;
227
+ - notes, with their own FTS5 table and embeddings;
228
+ - the history of indexing runs.
229
+
230
+ **Search** (`search.py`):
231
+
232
+ - Semantic search is cosine similarity against an in-memory matrix that reloads when the index changes.
233
+ - Keyword search is FTS5 BM25. It weights names over signatures, docstrings and code, and indexes the sub-words of camelCase and snake_case identifiers, so `user name` finds `getUserName`.
234
+ - Hybrid search fuses both rankings with Reciprocal Rank Fusion (k = 60). It adds a bonus when the query names a symbol (exact or all its sub-words) and slightly discounts module and glue chunks.
235
+
236
+ **Relationships** (`relations.py`): imports are resolved to repository files
237
+ per language: Python modules and relative imports, relative JS/TS paths with
238
+ extension and index lookup, C includes, Go packages, Rust `mod`/`use`,
239
+ Java/Kotlin packages, PHP namespaces, Ruby `require_relative` and Bash
240
+ `source`. Calls and inheritance are matched by name within the same language
241
+ family. Each edge's confidence is `high` when the two pieces of code share a
242
+ file or one imports the other, `medium` for the same directory, and `low`
243
+ otherwise.
244
+
245
+ **Knowledge that improves over time**: notes are stored in the same database,
246
+ embedded, and returned by `search_notes`. They are also attached to code
247
+ search results on the same topic or file. A note linked to a symbol or file
248
+ records a hash of that code. When the code changes, the note is flagged
249
+ `stale` with a reason, and `update_note` re-verifies it. Notes survive
250
+ re-indexing and schema rebuilds.
251
+
252
+ **Staying in sync without re-analysing unchanged code** (`indexer.py`, `watcher.py`):
253
+
254
+ - Files whose size and mtime are unchanged are not read again. A touched file with an unchanged content hash is not re-parsed.
255
+ - Changed files are re-chunked in one transaction each. Deleted files are removed.
256
+ - Embeddings are reused for any chunk whose text was already embedded, even in another file, so renames and moves cost nothing.
257
+ - Chunks are re-embedded only when their text or the embedding model changes. Changing the chunking code re-parses everything automatically.
258
+ - While serving, a file watcher triggers an incremental run about 1.5 s after changes. `index_status` reports whether anything on disk is newer than the index.
259
+
260
+ ## Errors and visibility
261
+
262
+ - Every anticipated failure is a `CodeContextError` whose message is shown verbatim, as a CLI error or an MCP tool error with `isError: true`. Examples: no repository configured, path outside the repository, unknown chunk id, nothing indexed yet, empty query.
263
+ - Unexpected exceptions become a one-line internal error. The indexer never takes the server down.
264
+ - Unreadable, binary, non-UTF-8 or syntactically broken files are recorded with their issue and listed in `index_status`. The rest of the repository still indexes.
265
+ - Database failures (locked, corrupt, unwritable) raise `StoreError` naming the database file and suggesting `index --full`.
266
+ - If embedding fails, the run finishes as `partial`: keyword search keeps working, the error is reported, and the next run embeds the remaining chunks. In hybrid mode, search falls back to keyword results with a warning.
267
+
268
+ ## Configuration
269
+
270
+ | Setting | Environment variable | `.codecontext.toml` key | Default |
271
+ | --- | --- | --- | --- |
272
+ | Repository | `CODE_CONTEXT_REPO` | - | CLI argument / cwd |
273
+ | Data directory | `CODE_CONTEXT_HOME` | - | `~/.code-context` |
274
+ | Database file | `CODE_CONTEXT_DB` | - | `<home>/indexes/<repo>-<hash>.db` |
275
+ | Embedder | `CODE_CONTEXT_EMBEDDER` | `embedder` | `auto` (`fastembed`, `openai`, `hash`) |
276
+ | Embedding model | `CODE_CONTEXT_EMBEDDING_MODEL` | `embedding_model` | `BAAI/bge-small-en-v1.5` / `text-embedding-3-small` |
277
+ | Max file size | `CODE_CONTEXT_MAX_FILE_KB` | `max_file_kb` | `1024` |
278
+ | Extra excludes | - | `exclude = ["docs/generated/**"]` | - |
279
+ | OpenAI-compatible endpoint | `CODE_CONTEXT_OPENAI_BASE_URL`, `CODE_CONTEXT_OPENAI_API_KEY` / `OPENAI_API_KEY` | `openai_base_url` | `https://api.openai.com/v1` |
280
+
281
+ `.codecontext.toml` lives in the repository root. API keys are read only
282
+ from the environment and are never stored or logged.
283
+
284
+ ## Demo
285
+
286
+ From a checkout of this repository:
287
+
288
+ ```bash
289
+ .venv/bin/python examples/demo_client.py # this repository, neural embeddings
290
+ .venv/bin/python examples/demo_client.py /path/to/repo --embedder hash
291
+ ```
292
+
293
+ The demo launches the server over stdio, like a real client, and runs two
294
+ sessions. In session 1 the assistant indexes the repository, reads the
295
+ overview, searches "how does hybrid search combine semantic and keyword
296
+ results", fetches the full source of the top hit, follows its calls and
297
+ callers, and saves a note about what it learned. Session 2 is a new server
298
+ process (a new chat): it checks the index status, finds the note with
299
+ `search_notes`, and gets the note back attached to `get_context` for a
300
+ related task.
301
+
302
+ ## Tests
303
+
304
+ ```bash
305
+ .venv/bin/python -m pytest
306
+ ```
307
+
308
+ The suite covers:
309
+
310
+ - chunking for every language;
311
+ - incremental indexing (unchanged, touched, changed, deleted and renamed files, embedding reuse);
312
+ - invalid input (binary, non-UTF-8, syntax errors, unsupported, ignored and empty files);
313
+ - embedding outage and recovery;
314
+ - embedder changes;
315
+ - the file watcher;
316
+ - the search modes and filters;
317
+ - path confinement;
318
+ - import resolution across languages;
319
+ - calls, callers, inheritance and call graphs;
320
+ - notes (persistence, staleness, validation);
321
+ - corrupt databases;
322
+ - the full MCP tool workflow through an MCP client.
323
+
324
+ ## Limitations
325
+
326
+ - Relationships are name based, without type inference. A method call such as `x.save()` links to every same-language `save`, ranked by confidence and flagged when ambiguous.
327
+ - Vector search is brute force over an in-memory matrix. That is fast up to roughly 100k chunks; beyond that, an ANN index would be the next step.
328
+ - The `hash` fallback embedder is lexical, not semantic. Status output and search warnings say when it is active.
329
+ - The first `fastembed` run downloads the model and needs network access. After that everything runs offline.
@@ -0,0 +1,283 @@
1
+ # Code Context MCP
2
+
3
+ A Model Context Protocol server that gives AI coding assistants a persistent,
4
+ searchable understanding of a codebase. It indexes a repository at structural
5
+ boundaries (functions, methods, classes, ...), embeds every chunk, stores it
6
+ all in SQLite, and exposes hybrid semantic + keyword search, relationship
7
+ exploration and a knowledge-note memory through MCP tools. The index stays in
8
+ sync with the working tree, so assistants stop rediscovering the project each
9
+ session.
10
+
11
+ ```
12
+ repository ──scan──► changed files ──tree-sitter──► chunks + metadata ──embed──► SQLite
13
+ (.gitignore aware) (size/mtime/hash) (15 grammars) (calls, bases, imports) (fastembed) (FTS5 + vectors + notes)
14
+ │
15
+ AI assistant ◄──── MCP (stdio / HTTP) ◄──── hybrid search · relationships · notes ◄──────────┘
16
+ ```
17
+
18
+ ## Install
19
+
20
+ Requires Python 3.11+.
21
+
22
+ ```bash
23
+ # recommended: isolated CLI install
24
+ pipx install ethicaldilkhush-code-context-mcp
25
+
26
+ # or with uv
27
+ uv tool install ethicaldilkhush-code-context-mcp
28
+
29
+ # or into a virtualenv
30
+ pip install ethicaldilkhush-code-context-mcp
31
+ ```
32
+
33
+ The first semantic index downloads the local embedding model (~70 MB, once).
34
+ After that the default setup runs offline. Use `--embedder hash` to skip the
35
+ model for a fast lexical-only mode.
36
+
37
+ ```bash
38
+ code-context index /path/to/repo
39
+ code-context search -r /path/to/repo "where are retries handled"
40
+ code-context serve /path/to/repo # MCP server on stdio
41
+ ```
42
+
43
+ Every CLI command takes `-r/--repo` (default: `$CODE_CONTEXT_REPO` or the
44
+ current directory) and `--json`. Commands: `index [--full] [--watch]`,
45
+ `status`, `search`, `context`, `show <chunk_id>`, `related <chunk_id | -s symbol>`,
46
+ `outline <file>`, `symbol <name>`, `overview`, `notes add|list|search|delete`, `serve`.
47
+
48
+ ### Develop from this repository
49
+
50
+ ```bash
51
+ python3 -m venv .venv && .venv/bin/pip install -e ".[dev]"
52
+ .venv/bin/code-context --version
53
+ .venv/bin/python -m pytest
54
+ ```
55
+
56
+ ## Connecting an AI assistant
57
+
58
+ The server speaks MCP over stdio by default (`--transport http` serves
59
+ streamable HTTP on `127.0.0.1:8765/mcp`). On startup it indexes in the
60
+ background and then watches the repository for changes.
61
+
62
+ **Cursor** (`.cursor/mcp.json` or `~/.cursor/mcp.json`):
63
+
64
+ ```json
65
+ {
66
+ "mcpServers": {
67
+ "code-context": {
68
+ "command": "uvx",
69
+ "args": ["ethicaldilkhush-code-context-mcp", "serve", "${workspaceFolder}"]
70
+ }
71
+ }
72
+ }
73
+ ```
74
+
75
+ If you installed with `pipx`, use the installed binary instead:
76
+
77
+ ```json
78
+ {
79
+ "mcpServers": {
80
+ "code-context": {
81
+ "command": "code-context",
82
+ "args": ["serve", "${workspaceFolder}"]
83
+ }
84
+ }
85
+ }
86
+ ```
87
+
88
+ This repository also ships a local `.cursor/mcp.json` that points at the
89
+ editable `.venv` install for development.
90
+
91
+ **Claude Code**:
92
+
93
+ ```bash
94
+ claude mcp add code-context -- uvx ethicaldilkhush-code-context-mcp serve /path/to/repo
95
+ ```
96
+
97
+ **Claude Desktop** (`claude_desktop_config.json`): same `command`/`args`
98
+ shape as above with an absolute repository path.
99
+
100
+ **MCP Inspector** (interactive testing):
101
+
102
+ ```bash
103
+ npx @modelcontextprotocol/inspector uvx ethicaldilkhush-code-context-mcp serve /path/to/repo
104
+ npx @modelcontextprotocol/inspector --cli uvx ethicaldilkhush-code-context-mcp serve /path/to/repo \
105
+ --method tools/call --tool-name search_code --tool-arg query="parse config file"
106
+ ```
107
+
108
+ The server can also start with no repository; the assistant then calls
109
+ `index_repository(path=...)` to choose one, and can switch repositories the same way.
110
+
111
+ ## MCP interface
112
+
113
+ | Tool | Purpose |
114
+ | --- | --- |
115
+ | `index_repository` | Index or update incrementally (`full_rebuild`, or `path` to switch repos). Waits up to `wait_seconds`, then keeps going in the background. |
116
+ | `index_status` | State, progress, per-language counts, embedding coverage, files with issues, recent runs, on-disk freshness. |
117
+ | `search_code` | Hybrid / semantic / keyword search with `language`, `kind` and `path` filters. |
118
+ | `get_context` | One call for a task: top results with full source, their calls and callers, more locations, relevant notes. |
119
+ | `find_symbol` | Definitions by name or qualified name (`Server.Start`, `billing::Invoice`). |
120
+ | `get_code` | Complete source of a result, plus parent, members, file notes and optional live surrounding lines. |
121
+ | `read_file` | Read a file or line range from disk, confined to the repository. |
122
+ | `get_file_outline` | Symbols of a file with line ranges and signatures, its imports and its importers. |
123
+ | `get_related` | Calls, callers, base types, subclasses, members and file dependencies, each with a confidence level. |
124
+ | `get_call_graph` | Multi-level call graph (`out` = callees, `in` = callers). |
125
+ | `repository_overview` | Languages, layout, entry points, most referenced symbols, largest types, README intro, notes. |
126
+ | `save_note` / `update_note` / `delete_note` | Persistent knowledge, optionally linked to a path and/or symbol. |
127
+ | `search_notes` / `list_notes` | Retrieve knowledge by meaning, tag or path. |
128
+
129
+ Resources: `codecontext://overview`, `codecontext://status`, `codecontext://notes`.
130
+ Prompt: `explore_codebase(task)` walks an assistant through orient → gather context → follow relationships → record notes.
131
+
132
+ All results are structured JSON. Every chunk carries `chunk_id`, `path`,
133
+ `start_line`/`end_line`, `location`, `language`, `kind`, `name`,
134
+ `qualified_name`, `signature`, `docstring`, `calls` and `bases`. Search
135
+ results add `score`, `matched_by` (`semantic`, `keyword`, `exact_name`, ...)
136
+ and a preview.
137
+
138
+ ## How it works
139
+
140
+ **Scanning** (`scanner.py`): uses `git ls-files` when available, so
141
+ `.gitignore` is honoured exactly; otherwise it walks the tree with the root
142
+ `.gitignore`. Dependency and build directories, minified and generated files,
143
+ empty files and files over `max_file_kb` are skipped, and the skips are
144
+ counted by reason in the index report.
145
+
146
+ **Parsing and chunking** (`chunker.py`, `languages.py`): tree-sitter grammars
147
+ for Python, JavaScript, TypeScript, TSX, Go, Rust, Java, C, C++, C#, Ruby,
148
+ PHP, Swift, Kotlin and Bash. Each function, method, constructor, class,
149
+ interface, struct, enum, trait, impl, protocol, extension or type alias
150
+ becomes a chunk. The chunk includes its decorators and leading doc comments
151
+ and records:
152
+
153
+ - the qualified name (`ns.Class.method`; Go receivers and out-of-line C++ methods are attached to their type);
154
+ - the signature and docstring;
155
+ - the parent chunk;
156
+ - base types;
157
+ - called names;
158
+ - the file's imports.
159
+
160
+ Classes are embedded as a skeleton with member bodies elided, so they don't
161
+ drown out their methods. Code between definitions becomes `module` chunks.
162
+ Markdown is split by heading and other text by blank-line-aware windows.
163
+ Syntax errors don't stop parsing: the file is flagged and still chunked.
164
+
165
+ **Embeddings** (`embeddings.py`): the default is local `fastembed`
166
+ (`BAAI/bge-small-en-v1.5`, ONNX, CPU, no API key). `openai` uses any
167
+ OpenAI-compatible `/embeddings` endpoint. `hash` is a deterministic
168
+ feature-hashing embedder that needs no model. With the default `auto`
169
+ setting, the server falls back to `hash` when the model can't load, and
170
+ reports this in the status output.
171
+
172
+ **Storage** (`store.py`): one SQLite database per repository, by default under
173
+ `~/.code-context/indexes/`, in WAL mode so the CLI and a running server can
174
+ share it. It holds:
175
+
176
+ - files (hash, mtime, status, issues);
177
+ - chunks (metadata, source, float32 embedding);
178
+ - an FTS5 table;
179
+ - call and inheritance references;
180
+ - imports;
181
+ - notes, with their own FTS5 table and embeddings;
182
+ - the history of indexing runs.
183
+
184
+ **Search** (`search.py`):
185
+
186
+ - Semantic search is cosine similarity against an in-memory matrix that reloads when the index changes.
187
+ - Keyword search is FTS5 BM25. It weights names over signatures, docstrings and code, and indexes the sub-words of camelCase and snake_case identifiers, so `user name` finds `getUserName`.
188
+ - Hybrid search fuses both rankings with Reciprocal Rank Fusion (k = 60). It adds a bonus when the query names a symbol (exact or all its sub-words) and slightly discounts module and glue chunks.
189
+
190
+ **Relationships** (`relations.py`): imports are resolved to repository files
191
+ per language: Python modules and relative imports, relative JS/TS paths with
192
+ extension and index lookup, C includes, Go packages, Rust `mod`/`use`,
193
+ Java/Kotlin packages, PHP namespaces, Ruby `require_relative` and Bash
194
+ `source`. Calls and inheritance are matched by name within the same language
195
+ family. Each edge's confidence is `high` when the two pieces of code share a
196
+ file or one imports the other, `medium` for the same directory, and `low`
197
+ otherwise.
198
+
199
+ **Knowledge that improves over time**: notes are stored in the same database,
200
+ embedded, and returned by `search_notes`. They are also attached to code
201
+ search results on the same topic or file. A note linked to a symbol or file
202
+ records a hash of that code. When the code changes, the note is flagged
203
+ `stale` with a reason, and `update_note` re-verifies it. Notes survive
204
+ re-indexing and schema rebuilds.
205
+
206
+ **Staying in sync without re-analysing unchanged code** (`indexer.py`, `watcher.py`):
207
+
208
+ - Files whose size and mtime are unchanged are not read again. A touched file with an unchanged content hash is not re-parsed.
209
+ - Changed files are re-chunked in one transaction each. Deleted files are removed.
210
+ - Embeddings are reused for any chunk whose text was already embedded, even in another file, so renames and moves cost nothing.
211
+ - Chunks are re-embedded only when their text or the embedding model changes. Changing the chunking code re-parses everything automatically.
212
+ - While serving, a file watcher triggers an incremental run about 1.5 s after changes. `index_status` reports whether anything on disk is newer than the index.
213
+
214
+ ## Errors and visibility
215
+
216
+ - Every anticipated failure is a `CodeContextError` whose message is shown verbatim, as a CLI error or an MCP tool error with `isError: true`. Examples: no repository configured, path outside the repository, unknown chunk id, nothing indexed yet, empty query.
217
+ - Unexpected exceptions become a one-line internal error. The indexer never takes the server down.
218
+ - Unreadable, binary, non-UTF-8 or syntactically broken files are recorded with their issue and listed in `index_status`. The rest of the repository still indexes.
219
+ - Database failures (locked, corrupt, unwritable) raise `StoreError` naming the database file and suggesting `index --full`.
220
+ - If embedding fails, the run finishes as `partial`: keyword search keeps working, the error is reported, and the next run embeds the remaining chunks. In hybrid mode, search falls back to keyword results with a warning.
221
+
222
+ ## Configuration
223
+
224
+ | Setting | Environment variable | `.codecontext.toml` key | Default |
225
+ | --- | --- | --- | --- |
226
+ | Repository | `CODE_CONTEXT_REPO` | - | CLI argument / cwd |
227
+ | Data directory | `CODE_CONTEXT_HOME` | - | `~/.code-context` |
228
+ | Database file | `CODE_CONTEXT_DB` | - | `<home>/indexes/<repo>-<hash>.db` |
229
+ | Embedder | `CODE_CONTEXT_EMBEDDER` | `embedder` | `auto` (`fastembed`, `openai`, `hash`) |
230
+ | Embedding model | `CODE_CONTEXT_EMBEDDING_MODEL` | `embedding_model` | `BAAI/bge-small-en-v1.5` / `text-embedding-3-small` |
231
+ | Max file size | `CODE_CONTEXT_MAX_FILE_KB` | `max_file_kb` | `1024` |
232
+ | Extra excludes | - | `exclude = ["docs/generated/**"]` | - |
233
+ | OpenAI-compatible endpoint | `CODE_CONTEXT_OPENAI_BASE_URL`, `CODE_CONTEXT_OPENAI_API_KEY` / `OPENAI_API_KEY` | `openai_base_url` | `https://api.openai.com/v1` |
234
+
235
+ `.codecontext.toml` lives in the repository root. API keys are read only
236
+ from the environment and are never stored or logged.
237
+
238
+ ## Demo
239
+
240
+ From a checkout of this repository:
241
+
242
+ ```bash
243
+ .venv/bin/python examples/demo_client.py # this repository, neural embeddings
244
+ .venv/bin/python examples/demo_client.py /path/to/repo --embedder hash
245
+ ```
246
+
247
+ The demo launches the server over stdio, like a real client, and runs two
248
+ sessions. In session 1 the assistant indexes the repository, reads the
249
+ overview, searches "how does hybrid search combine semantic and keyword
250
+ results", fetches the full source of the top hit, follows its calls and
251
+ callers, and saves a note about what it learned. Session 2 is a new server
252
+ process (a new chat): it checks the index status, finds the note with
253
+ `search_notes`, and gets the note back attached to `get_context` for a
254
+ related task.
255
+
256
+ ## Tests
257
+
258
+ ```bash
259
+ .venv/bin/python -m pytest
260
+ ```
261
+
262
+ The suite covers:
263
+
264
+ - chunking for every language;
265
+ - incremental indexing (unchanged, touched, changed, deleted and renamed files, embedding reuse);
266
+ - invalid input (binary, non-UTF-8, syntax errors, unsupported, ignored and empty files);
267
+ - embedding outage and recovery;
268
+ - embedder changes;
269
+ - the file watcher;
270
+ - the search modes and filters;
271
+ - path confinement;
272
+ - import resolution across languages;
273
+ - calls, callers, inheritance and call graphs;
274
+ - notes (persistence, staleness, validation);
275
+ - corrupt databases;
276
+ - the full MCP tool workflow through an MCP client.
277
+
278
+ ## Limitations
279
+
280
+ - Relationships are name based, without type inference. A method call such as `x.save()` links to every same-language `save`, ranked by confidence and flagged when ambiguous.
281
+ - Vector search is brute force over an in-memory matrix. That is fast up to roughly 100k chunks; beyond that, an ANN index would be the next step.
282
+ - The `hash` fallback embedder is lexical, not semantic. Status output and search warnings say when it is active.
283
+ - The first `fastembed` run downloads the model and needs network access. After that everything runs offline.