mcp-kb 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,583 @@
1
+ """Integration layer that mirrors knowledge base updates into ChromaDB."""
2
+ from __future__ import annotations
3
+
4
+ import importlib
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Any, Dict, List, Mapping, Optional, Set, Tuple, Type, TYPE_CHECKING
8
+ from langchain_text_splitters import TokenTextSplitter
9
+
10
+ from mcp_kb.knowledge.events import (
11
+ FileDeleteEvent,
12
+ FileUpsertEvent,
13
+ KnowledgeBaseListener,
14
+ KnowledgeBaseReindexListener,
15
+ )
16
+ from mcp_kb.knowledge.search import SearchMatch
17
+
18
+ if TYPE_CHECKING: # pragma: no cover - type checking only imports
19
+ from chromadb.api import ClientAPI, GetResult
20
+ from chromadb.api.models.Collection import Collection
21
+ from mcp_kb.knowledge.store import KnowledgeBase
22
+
23
+ SUPPORTED_CLIENTS: Tuple[str, ...] = ("off", "ephemeral", "persistent", "http", "cloud")
24
+ """Recognised client types exposed to operators enabling Chroma ingestion."""
25
+
26
+ @dataclass(frozen=True)
27
+ class ChromaConfiguration:
28
+ """Runtime configuration controlling how Chroma ingestion behaves.
29
+
30
+ Each attribute corresponds to either a CLI flag or an environment variable
31
+ so that deployments can toggle Chroma synchronisation without changing the
32
+ application code. The configuration intentionally stores already-normalised
33
+ values (e.g., resolved paths and lowercase enums) so downstream components
34
+ can rely on consistent semantics regardless of where the data originated.
35
+ """
36
+
37
+ client_type: str
38
+ collection_name: str
39
+ embedding: str
40
+ data_directory: Optional[Path]
41
+ host: Optional[str]
42
+ port: Optional[int]
43
+ ssl: bool
44
+ tenant: Optional[str]
45
+ database: Optional[str]
46
+ api_key: Optional[str]
47
+ custom_auth_credentials: Optional[str]
48
+ id_prefix: str
49
+
50
+ @property
51
+ def enabled(self) -> bool:
52
+ """Return ``True`` when ingestion should be activated."""
53
+
54
+ return self.client_type != "off"
55
+
56
+ @classmethod
57
+ def from_options(
58
+ cls,
59
+ *,
60
+ root: Path,
61
+ client_type: str,
62
+ collection_name: str,
63
+ embedding: str,
64
+ data_directory: Optional[str],
65
+ host: Optional[str],
66
+ port: Optional[int],
67
+ ssl: bool,
68
+ tenant: Optional[str],
69
+ database: Optional[str],
70
+ api_key: Optional[str],
71
+ custom_auth_credentials: Optional[str],
72
+ id_prefix: Optional[str],
73
+ ) -> "ChromaConfiguration":
74
+ """Normalise CLI and environment inputs into a configuration object.
75
+
76
+ Parameters
77
+ ----------
78
+ root:
79
+ Absolute knowledge base root used to derive default directories.
80
+ client_type:
81
+ One of :data:`SUPPORTED_CLIENTS`. ``"off"`` disables ingestion.
82
+ collection_name:
83
+ Target Chroma collection that will store knowledge base documents.
84
+ embedding:
85
+ Name of the embedding function to instantiate. Values are matched
86
+ case-insensitively to the functions exported by Chroma.
87
+ data_directory:
88
+ Optional directory for the persistent client. When omitted and the
89
+ client type is ``"persistent"`` the function creates a ``chroma``
90
+ sub-directory next to the knowledge base.
91
+ host / port / ssl / tenant / database / api_key / custom_auth_credentials:
92
+ Transport-specific settings passed directly to the Chroma client
93
+ constructors.
94
+ id_prefix:
95
+ Optional prefix prepended to every document ID stored in Chroma.
96
+ Defaults to ``"kb::"`` for readability.
97
+ """
98
+
99
+ normalized_type = (client_type or "off").lower()
100
+ if normalized_type not in SUPPORTED_CLIENTS:
101
+ raise ValueError(f"Unsupported Chroma client type: {client_type}")
102
+
103
+ resolved_directory: Optional[Path]
104
+ if data_directory:
105
+ resolved_directory = Path(data_directory).expanduser().resolve()
106
+ elif normalized_type == "persistent":
107
+ resolved_directory = (root / "chroma").resolve()
108
+ else:
109
+ resolved_directory = None
110
+
111
+ if resolved_directory is not None:
112
+ resolved_directory.mkdir(parents=True, exist_ok=True)
113
+
114
+ prefix = id_prefix or "kb::"
115
+
116
+ normalized_embedding = (embedding or "default").lower()
117
+
118
+ config = cls(
119
+ client_type=normalized_type,
120
+ collection_name=collection_name,
121
+ embedding=normalized_embedding,
122
+ data_directory=resolved_directory,
123
+ host=host,
124
+ port=port,
125
+ ssl=ssl,
126
+ tenant=tenant,
127
+ database=database,
128
+ api_key=api_key,
129
+ custom_auth_credentials=custom_auth_credentials,
130
+ id_prefix=prefix,
131
+ )
132
+ config._validate()
133
+ return config
134
+
135
+ def _validate(self) -> None:
136
+ """Validate the configuration and raise descriptive errors when invalid."""
137
+
138
+ if not self.enabled:
139
+ return
140
+
141
+ if self.client_type == "persistent" and self.data_directory is None:
142
+ raise ValueError("Persistent Chroma client requires a data directory")
143
+
144
+ if self.client_type == "http" and not self.host:
145
+ raise ValueError("HTTP Chroma client requires --chroma-host or MCP_KB_CHROMA_HOST")
146
+
147
+ if self.client_type == "cloud":
148
+ missing = [
149
+ name
150
+ for name, value in (
151
+ ("tenant", self.tenant),
152
+ ("database", self.database),
153
+ ("api_key", self.api_key),
154
+ )
155
+ if not value
156
+ ]
157
+ if missing:
158
+ pretty = ", ".join(missing)
159
+ raise ValueError(f"Cloud Chroma client requires values for: {pretty}")
160
+
161
+ if not self.collection_name:
162
+ raise ValueError("Collection name must be provided")
163
+
164
+ if not self.embedding:
165
+ raise ValueError("Embedding function name must be provided")
166
+
167
+
168
+ @dataclass(frozen=True)
169
+ class _ChromaDependencies:
170
+ """Lazy import bundle containing the pieces needed to talk to ChromaDB."""
171
+
172
+ chroma_module: Any
173
+ settings_cls: Type[Any]
174
+ embedding_factories: Mapping[str, Type[Any]]
175
+
176
+
177
+ def _load_dependencies() -> _ChromaDependencies:
178
+ """Import ChromaDB lazily so the base server works without the dependency."""
179
+
180
+ try:
181
+ chroma_module = importlib.import_module("chromadb")
182
+ except ModuleNotFoundError as exc: # pragma: no cover - dependent on environment
183
+ raise RuntimeError(
184
+ "Chroma integration requested but the 'chromadb' package is not installed. "
185
+ "Install chromadb via 'uv add chromadb' or disable ingestion."
186
+ ) from exc
187
+
188
+ config_module = importlib.import_module("chromadb.config")
189
+ embedding_module = importlib.import_module("chromadb.utils.embedding_functions")
190
+
191
+ factories: Dict[str, Type[Any]] = {}
192
+ fallback_map = {
193
+ "default": "DefaultEmbeddingFunction",
194
+ "cohere": "CohereEmbeddingFunction",
195
+ "openai": "OpenAIEmbeddingFunction",
196
+ "jina": "JinaEmbeddingFunction",
197
+ "voyageai": "VoyageAIEmbeddingFunction",
198
+ "roboflow": "RoboflowEmbeddingFunction",
199
+ }
200
+ for alias, attr in fallback_map.items():
201
+ if hasattr(embedding_module, attr):
202
+ factories[alias] = getattr(embedding_module, attr)
203
+ if not factories:
204
+ raise RuntimeError("No embedding functions were found in chromadb.utils.embedding_functions")
205
+
206
+ return _ChromaDependencies(
207
+ chroma_module=chroma_module,
208
+ settings_cls=getattr(config_module, "Settings"),
209
+ embedding_factories=factories,
210
+ )
211
+
212
+
213
+ class ChromaIngestor(KnowledgeBaseListener, KnowledgeBaseReindexListener):
214
+ """Listener that mirrors knowledge base writes into a Chroma collection.
215
+
216
+ The listener adheres to the :class:`KnowledgeBaseListener` protocol so it
217
+ can be registered alongside other observers without coupling. Events are
218
+ written synchronously to guarantee that indexing stays consistent with the
219
+ underlying filesystem operations.
220
+ """
221
+
222
+ def __init__(self, configuration: ChromaConfiguration) -> None:
223
+ """Create an ingestor bound to ``configuration``.
224
+
225
+ Parameters
226
+ ----------
227
+ configuration:
228
+ Sanitised :class:`ChromaConfiguration` describing how to connect to
229
+ Chroma and which collection to mirror.
230
+ """
231
+
232
+ self.configuration = configuration
233
+ self._deps = _load_dependencies()
234
+ self._client = self._create_client()
235
+ self._collection = self._ensure_collection()
236
+ self.textsplitter = TokenTextSplitter(
237
+ chunk_size=200,
238
+ chunk_overlap=20,
239
+ add_start_index=True
240
+ )
241
+
242
+ def get_document_chunks(self, document_id: str, include: List[str] = ["metadatas", "documents"]) -> GetResult:
243
+ """Get a document from the Chroma index."""
244
+ return self._collection.get(where={"document_id": document_id},include=include)
245
+
246
+ def handle_upsert(self, event: FileUpsertEvent) -> None:
247
+ """Upsert ``event`` into the configured Chroma collection.
248
+
249
+ Every invocation removes any existing Chroma entry before inserting the
250
+ fresh payload so that the embedding engine recomputes vectors using the
251
+ latest markdown. The stored metadata keeps both absolute and relative
252
+ paths, enabling downstream semantic search tools to surface references
253
+ that point straight back into the knowledge base.
254
+ """
255
+
256
+ document_id = f"{self.configuration.id_prefix}{event.relative_path}"
257
+ metadata = {
258
+ "relative_path": event.relative_path,
259
+ }
260
+ self._reindex_document(document_id, event.content, metadata)
261
+
262
+ def delete_document(self, document_id: str) -> None:
263
+ """Delete a document from the Chroma index."""
264
+ self._collection.delete(ids=self.get_document_chunks(document_id,include=[])["ids"])
265
+
266
+ def handle_delete(self, event: FileDeleteEvent) -> None:
267
+ """Remove documents associated with ``event`` from the Chroma index.
268
+
269
+ Soft deletions translate to a straight removal because the PRD treats
270
+ files carrying the delete sentinel as hidden from client tooling.
271
+ """
272
+
273
+ document_id = f"{self.configuration.id_prefix}{event.relative_path}"
274
+ try:
275
+ self.delete_document(document_id)
276
+ except Exception: # pragma: no cover - depends on Chroma exceptions
277
+ # Chroma raises a custom error when the ID is missing. Deletion should
278
+ # be idempotent so we swallow those errors silently.
279
+ pass
280
+
281
+ @property
282
+ def collection(self) -> "Collection":
283
+ """Return the underlying Chroma collection for diagnostics and tests."""
284
+
285
+ return self._collection
286
+
287
+ def query(self, query: str, *, n_results: int = 5) -> List[Dict[str, Any]]:
288
+ """Return structured query results from the configured collection.
289
+
290
+ Parameters
291
+ ----------
292
+ query:
293
+ Natural language string used to compute the semantic embedding.
294
+ n_results:
295
+ Maximum number of results to return. Defaults to five to mirror the
296
+ behaviour surfaced through the MCP search tool.
297
+
298
+ Returns
299
+ -------
300
+ list[dict[str, Any]]
301
+ Each dictionary contains the ``document`` text, associated
302
+ ``metadata`` payload, and a floating-point ``distance`` score if
303
+ provided by Chroma.
304
+ """
305
+
306
+ payload = self._collection.query(
307
+ query_texts=[query],
308
+ n_results=n_results,
309
+ include=["metadatas", "documents", "distances"],
310
+ )
311
+
312
+ documents = payload.get("documents", [[]])
313
+ metadatas = payload.get("metadatas", [[]])
314
+ distances = payload.get("distances", [[]])
315
+
316
+ if not documents or not documents[0]:
317
+ return []
318
+
319
+ results: List[Dict[str, Any]] = []
320
+ for index, metadata in enumerate(metadatas[0]):
321
+ document = documents[0][index] if index < len(documents[0]) else ""
322
+ distance = distances[0][index] if distances and distances[0] else None
323
+ results.append(
324
+ {
325
+ "metadata": metadata or {},
326
+ "document": document,
327
+ "distance": distance,
328
+ }
329
+ )
330
+
331
+ return results
332
+
333
+ # Optional search extension -------------------------------------------------
334
+
335
+ def search(
336
+ self,
337
+ kb: "KnowledgeBase",
338
+ query: str,
339
+ *,
340
+ context_lines: int = 2,
341
+ limit: Optional[int] = None,
342
+ ) -> List[SearchMatch]:
343
+ """Translate semantic query results into :class:`SearchMatch` objects."""
344
+
345
+ max_results = limit or 5
346
+ records = self.query(query, n_results=max_results)
347
+ matches: List[SearchMatch] = []
348
+ seen_paths: Set[Path] = set()
349
+
350
+ for record in records:
351
+ metadata = record.get("metadata") or {}
352
+ candidate = self._resolve_candidate_path(
353
+ kb,
354
+ metadata.get("relative_path"),
355
+ )
356
+ if candidate is None or candidate in seen_paths:
357
+ continue
358
+
359
+ seen_paths.add(candidate)
360
+ try:
361
+ text = candidate.read_text(encoding="utf-8")
362
+ except FileNotFoundError:
363
+ continue
364
+
365
+ lines = text.splitlines()
366
+ file_matches = self._extract_matches_from_lines(candidate, lines, query, context_lines)
367
+ if file_matches:
368
+ matches.append(file_matches[0])
369
+ elif lines:
370
+ preview_limit = min(len(lines), context_lines * 2 + 1)
371
+ matches.append(
372
+ SearchMatch(
373
+ path=candidate,
374
+ line_number=1,
375
+ context=lines[:preview_limit],
376
+ )
377
+ )
378
+
379
+ if limit is not None and len(matches) >= limit:
380
+ break
381
+
382
+ return matches
383
+
384
+ # Internal helpers ----------------------------------------------------------
385
+
386
+ def _reindex_document(
387
+ self,
388
+ document_id: str,
389
+ content: str,
390
+ metadata: Mapping[str, Any],
391
+ ) -> None:
392
+ """Replace the stored document so embeddings are recomputed.
393
+
394
+ Reindexing involves removing any stale record before inserting the new
395
+ payload. Some Chroma backends keep historical data around when ``add``
396
+ is invoked with an existing ID, so the deletion step ensures the stored
397
+ embedding always reflects the latest markdown contents. ``metadata`` is
398
+ copied to break accidental references held by callers.
399
+ """
400
+
401
+ try:
402
+ # filter by document_id in metadata
403
+ self.delete_document(document_id)
404
+ except Exception: # pragma: no cover - depends on Chroma exception types
405
+ # Missing IDs are not an error; most clients raise when attempting to
406
+ # delete a non-existent record. We swallow those errors to keep the
407
+ # reindexing path idempotent.
408
+ pass
409
+
410
+ payload_metadata = dict(metadata)
411
+ payload_metadata['document_id'] = document_id
412
+
413
+ # splitting
414
+
415
+ split_docs = self.textsplitter.create_documents([content])
416
+
417
+ for i, d in enumerate(split_docs):
418
+ d.metadata.update(payload_metadata)
419
+ d.metadata['chunk_number'] = i
420
+ d.metadata['startline'] = len(content[:d.metadata['start_index']].splitlines())
421
+ d.metadata['endline'] = d.metadata['startline'] + len(d.page_content.splitlines())-1
422
+
423
+ self._collection.add(
424
+ documents=[d.page_content for d in split_docs],
425
+ metadatas=[d.metadata for d in split_docs],
426
+ ids=[f"{d.metadata['document_id']}-{d.metadata['chunk_number']}" for d in split_docs],
427
+ )
428
+
429
+ # Optional full reindex -----------------------------------------------------
430
+
431
+ def reindex(self, kb: "KnowledgeBase") -> int:
432
+ """Rebuild the Chroma index from the current knowledge base state.
433
+
434
+ The method iterates over all active markdown files visible to the
435
+ provided knowledge base instance, computing a deterministic document ID
436
+ for each path using the configured ``id_prefix``. Each file is read from
437
+ disk and upserted into the underlying Chroma collection by delegating to
438
+ :meth:`_reindex_document`, ensuring embeddings are recomputed.
439
+
440
+ Parameters
441
+ ----------
442
+ kb:
443
+ The :class:`~mcp_kb.knowledge.store.KnowledgeBase` providing access
444
+ to the validated filesystem and utility methods.
445
+
446
+ Returns
447
+ -------
448
+ int
449
+ The number of documents processed during the reindex run.
450
+ """
451
+
452
+ count = 0
453
+ root = kb.rules.root
454
+ for path in kb.iter_active_files(include_docs=False):
455
+ try:
456
+ content = path.read_text(encoding="utf-8")
457
+ except FileNotFoundError: # pragma: no cover - race with external edits
458
+ continue
459
+
460
+ relative = str(path.relative_to(root))
461
+ document_id = f"{self.configuration.id_prefix}{relative}"
462
+ metadata = {
463
+ "relative_path": relative,
464
+ }
465
+ self._reindex_document(document_id, content, metadata)
466
+ count += 1
467
+
468
+ return count
469
+
470
+ def _extract_matches_from_lines(
471
+ self,
472
+ path: Path,
473
+ lines: List[str],
474
+ query: str,
475
+ context_lines: int,
476
+ ) -> List[SearchMatch]:
477
+ """Return line-based matches for ``query`` within ``lines``."""
478
+
479
+ matches: List[SearchMatch] = []
480
+ for index, line in enumerate(lines, start=1):
481
+ if query in line:
482
+ start = max(0, index - context_lines - 1)
483
+ end = min(len(lines), index + context_lines)
484
+ matches.append(
485
+ SearchMatch(
486
+ path=path,
487
+ line_number=index,
488
+ context=lines[start:end],
489
+ )
490
+ )
491
+ return matches
492
+
493
+ def _resolve_candidate_path(
494
+ self,
495
+ kb: "KnowledgeBase",
496
+ relative: Optional[str],
497
+ ) -> Optional[Path]:
498
+ """Translate metadata hints into a validated path inside ``kb``."""
499
+
500
+ path: Optional[Path] = None
501
+ if relative:
502
+ candidate = (kb.rules.root / relative).resolve()
503
+ try:
504
+ candidate.relative_to(kb.rules.root)
505
+ except ValueError:
506
+ path = None
507
+ else:
508
+ if candidate.exists():
509
+ path = candidate
510
+
511
+ return path
512
+
513
+ def _create_client(self) -> "ClientAPI":
514
+ """Instantiate the proper Chroma client based on configuration.
515
+
516
+ The method supports all transport modes referenced in the user
517
+ requirements. It constructs the minimal set of keyword arguments for the
518
+ chosen backend and lets Chroma's client validate the final configuration.
519
+ """
520
+
521
+ chroma = self._deps.chroma_module
522
+ config = self.configuration
523
+
524
+ if not config.enabled:
525
+ raise RuntimeError("ChromaIngestor cannot be constructed when ingestion is disabled")
526
+
527
+ if config.client_type == "ephemeral":
528
+ return chroma.EphemeralClient()
529
+
530
+ if config.client_type == "persistent":
531
+ return chroma.PersistentClient(path=str(config.data_directory))
532
+
533
+ if config.client_type in {"http", "cloud"}:
534
+ kwargs: Dict[str, Any] = {
535
+ "ssl": config.ssl if config.client_type == "http" else True,
536
+ }
537
+ if config.client_type == "http":
538
+ kwargs["host"] = config.host
539
+ if config.port is not None:
540
+ kwargs["port"] = config.port
541
+ if config.custom_auth_credentials:
542
+ kwargs["settings"] = self._deps.settings_cls(
543
+ chroma_client_auth_provider="chromadb.auth.basic_authn.BasicAuthClientProvider",
544
+ chroma_client_auth_credentials=config.custom_auth_credentials,
545
+ )
546
+ else: # cloud
547
+ kwargs["host"] = config.host or "api.trychroma.com"
548
+ kwargs["tenant"] = config.tenant
549
+ kwargs["database"] = config.database
550
+ kwargs.setdefault("headers", {})
551
+ kwargs["headers"]["x-chroma-token"] = config.api_key
552
+
553
+ return chroma.HttpClient(**kwargs)
554
+
555
+ raise ValueError(f"Unsupported client type: {config.client_type}")
556
+
557
+ def _ensure_collection(self) -> "Collection":
558
+ """Create or return the configured Chroma collection."""
559
+
560
+ factory = self._deps.embedding_factories.get(self.configuration.embedding)
561
+ if factory is None:
562
+ available = ", ".join(sorted(self._deps.embedding_factories))
563
+ raise ValueError(
564
+ f"Unknown embedding function '{self.configuration.embedding}'. "
565
+ f"Available options: {available}"
566
+ )
567
+ embedding_function = factory()
568
+
569
+ metadata = {"source": "mcp-knowledge-base"}
570
+ client = self._client
571
+ try:
572
+ return client.get_or_create_collection(
573
+ name=self.configuration.collection_name,
574
+ metadata=metadata,
575
+ embedding_function=embedding_function,
576
+ )
577
+ except TypeError:
578
+ # Older Chroma versions expect CreateCollectionConfiguration. Fall back
579
+ # to create_collection for compatibility.
580
+ return client.get_or_create_collection(
581
+ name=self.configuration.collection_name,
582
+ embedding_function=embedding_function,
583
+ )
@@ -0,0 +1 @@
1
+ """Knowledge layer that encapsulates content storage and search helpers."""
@@ -0,0 +1,39 @@
1
+ """Bootstrap helpers executed during server startup."""
2
+ from __future__ import annotations
3
+
4
+ import importlib.resources as resources
5
+ from pathlib import Path
6
+
7
+ from mcp_kb.config import DOCS_FOLDER_NAME, DOC_FILENAME
8
+
9
+
10
+ def install_default_documentation(root: Path) -> Path:
11
+ """Ensure the default documentation file exists under ``root``.
12
+
13
+ The function creates the documentation directory if necessary and copies the
14
+ packaged ``KNOWLEDBASE_DOC.md`` file into place. Existing documentation is
15
+ preserved so that operators can customize the file without losing changes on
16
+ subsequent startups.
17
+
18
+ Parameters
19
+ ----------
20
+ root:
21
+ Absolute path representing the knowledge base root directory.
22
+
23
+ Returns
24
+ -------
25
+ Path
26
+ Path to the documentation file inside the knowledge base tree.
27
+ """
28
+
29
+ docs_dir = root / DOCS_FOLDER_NAME
30
+ doc_path = docs_dir / DOC_FILENAME
31
+ if doc_path.exists():
32
+ return doc_path
33
+
34
+ docs_dir.mkdir(parents=True, exist_ok=True)
35
+
36
+ with resources.files("mcp_kb.data").joinpath("KNOWLEDBASE_DOC.md").open("r", encoding="utf-8") as source:
37
+ doc_path.write_text(source.read(), encoding="utf-8")
38
+
39
+ return doc_path