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.
mcp_kb/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Top-level package for the MCP knowledge base server implementation."""
mcp_kb/cli/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """CLI subpackage exposing entry points for running the server."""
mcp_kb/cli/args.py ADDED
@@ -0,0 +1,153 @@
1
+ """Shared CLI argument wiring for knowledge base utilities.
2
+
3
+ This module centralizes the definition of common command-line options and
4
+ helpers so that multiple entry points (e.g., server and reindex commands) can
5
+ remain small and focused while sharing consistent behavior.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from argparse import ArgumentParser, Namespace
11
+ from pathlib import Path
12
+ from typing import Optional
13
+
14
+ from mcp_kb.ingest.chroma import SUPPORTED_CLIENTS, ChromaConfiguration, ChromaIngestor
15
+
16
+
17
+ def parse_bool(value: str | bool | None) -> bool:
18
+ """Return ``True`` when ``value`` represents an affirmative boolean string.
19
+
20
+ The function accepts case-insensitive variants such as "true", "t",
21
+ "yes", and "1". ``None`` yields ``False``.
22
+ """
23
+
24
+ if isinstance(value, bool):
25
+ return value
26
+ if value is None:
27
+ return False
28
+ return value.lower() in {"1", "true", "t", "yes", "y"}
29
+
30
+
31
+ def add_chroma_arguments(parser: ArgumentParser) -> None:
32
+ """Register Chroma ingestion arguments on ``parser``.
33
+
34
+ Environment variables are used as defaults where available so that
35
+ deployments can configure ingestion without repeating flags.
36
+ """
37
+
38
+ default_chroma_client = os.getenv("MCP_KB_CHROMA_CLIENT", "persistent").lower()
39
+ default_collection = os.getenv("MCP_KB_CHROMA_COLLECTION", "knowledge-base")
40
+ default_embedding = os.getenv("MCP_KB_CHROMA_EMBEDDING", "default")
41
+ default_data_dir = os.getenv("MCP_KB_CHROMA_DATA_DIR")
42
+ default_host = os.getenv("MCP_KB_CHROMA_HOST")
43
+ default_port_env = os.getenv("MCP_KB_CHROMA_PORT")
44
+ default_port = int(default_port_env) if default_port_env else None
45
+ default_ssl = parse_bool(os.getenv("MCP_KB_CHROMA_SSL", "true"))
46
+ default_tenant = os.getenv("MCP_KB_CHROMA_TENANT")
47
+ default_database = os.getenv("MCP_KB_CHROMA_DATABASE")
48
+ default_api_key = os.getenv("MCP_KB_CHROMA_API_KEY")
49
+ default_custom_auth = os.getenv("MCP_KB_CHROMA_CUSTOM_AUTH")
50
+ default_id_prefix = os.getenv("MCP_KB_CHROMA_ID_PREFIX")
51
+
52
+ parser.add_argument(
53
+ "--chroma-client",
54
+ dest="chroma_client",
55
+ choices=SUPPORTED_CLIENTS,
56
+ default=default_chroma_client,
57
+ help="Client implementation for mirroring data to ChromaDB (default: persistent).",
58
+ )
59
+ parser.add_argument(
60
+ "--chroma-collection",
61
+ dest="chroma_collection",
62
+ default=default_collection,
63
+ help="Chroma collection name used to store documents.",
64
+ )
65
+ parser.add_argument(
66
+ "--chroma-embedding",
67
+ dest="chroma_embedding",
68
+ default=default_embedding,
69
+ help="Embedding function name registered with chromadb.utils.embedding_functions.",
70
+ )
71
+ parser.add_argument(
72
+ "--chroma-data-dir",
73
+ dest="chroma_data_dir",
74
+ default=default_data_dir,
75
+ help="Storage directory for the persistent Chroma client.",
76
+ )
77
+ parser.add_argument(
78
+ "--chroma-host",
79
+ dest="chroma_host",
80
+ default=default_host,
81
+ help="Target host for HTTP or cloud Chroma clients.",
82
+ )
83
+ parser.add_argument(
84
+ "--chroma-port",
85
+ dest="chroma_port",
86
+ type=int,
87
+ default=default_port,
88
+ help="Port for the HTTP Chroma client.",
89
+ )
90
+ parser.add_argument(
91
+ "--chroma-ssl",
92
+ dest="chroma_ssl",
93
+ type=parse_bool,
94
+ default=default_ssl,
95
+ help="Toggle SSL for the HTTP Chroma client (default: true).",
96
+ )
97
+ parser.add_argument(
98
+ "--chroma-tenant",
99
+ dest="chroma_tenant",
100
+ default=default_tenant,
101
+ help="Tenant identifier for Chroma Cloud deployments.",
102
+ )
103
+ parser.add_argument(
104
+ "--chroma-database",
105
+ dest="chroma_database",
106
+ default=default_database,
107
+ help="Database name for Chroma Cloud deployments.",
108
+ )
109
+ parser.add_argument(
110
+ "--chroma-api-key",
111
+ dest="chroma_api_key",
112
+ default=default_api_key,
113
+ help="API key used to authenticate against Chroma Cloud.",
114
+ )
115
+ parser.add_argument(
116
+ "--chroma-custom-auth",
117
+ dest="chroma_custom_auth",
118
+ default=default_custom_auth,
119
+ help="Optional custom auth credentials for self-hosted HTTP deployments.",
120
+ )
121
+ parser.add_argument(
122
+ "--chroma-id-prefix",
123
+ dest="chroma_id_prefix",
124
+ default=default_id_prefix,
125
+ help="Prefix applied to document IDs stored in Chroma (default: kb::).",
126
+ )
127
+
128
+
129
+ def build_chroma_listener(options: Namespace, root: Path) -> Optional[ChromaIngestor]:
130
+ """Construct a Chroma listener from parsed CLI options when enabled.
131
+
132
+ Returns ``None`` when the configured client type is ``off``.
133
+ """
134
+
135
+ configuration = ChromaConfiguration.from_options(
136
+ root=root,
137
+ client_type=options.chroma_client,
138
+ collection_name=options.chroma_collection,
139
+ embedding=options.chroma_embedding,
140
+ data_directory=options.chroma_data_dir,
141
+ host=options.chroma_host,
142
+ port=options.chroma_port,
143
+ ssl=options.chroma_ssl,
144
+ tenant=options.chroma_tenant,
145
+ database=options.chroma_database,
146
+ api_key=options.chroma_api_key,
147
+ custom_auth_credentials=options.chroma_custom_auth,
148
+ id_prefix=options.chroma_id_prefix,
149
+ )
150
+ if not configuration.enabled:
151
+ return None
152
+ return ChromaIngestor(configuration)
153
+
mcp_kb/cli/main.py ADDED
@@ -0,0 +1,116 @@
1
+ """Command line interface for running the MCP knowledge base server."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import asyncio
6
+ import logging
7
+ import os
8
+ from pathlib import Path
9
+ from typing import Iterable, List, Optional
10
+
11
+ from mcp_kb.config import DOCS_FOLDER_NAME, resolve_knowledge_base_root
12
+ from mcp_kb.cli.args import add_chroma_arguments, build_chroma_listener, parse_bool
13
+ from mcp_kb.ingest.chroma import ChromaIngestor
14
+ from mcp_kb.knowledge.bootstrap import install_default_documentation
15
+ from mcp_kb.security.path_validation import PathRules
16
+ from mcp_kb.server.app import create_fastmcp_app
17
+ from mcp.server.fastmcp import FastMCP
18
+
19
+ logging.basicConfig(level=logging.INFO)
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ def _build_argument_parser() -> argparse.ArgumentParser:
25
+ """Create and return the argument parser used by ``main``."""
26
+
27
+ parser = argparse.ArgumentParser(description="Run the MCP knowledge base server")
28
+ parser.add_argument(
29
+ "--root",
30
+ dest="root",
31
+ default=None,
32
+ help="Optional path to the knowledge base root (defaults to environment configuration)",
33
+ )
34
+ parser.add_argument(
35
+ "--transport",
36
+ dest="transports",
37
+ action="append",
38
+ choices=["stdio", "sse", "http"],
39
+ help="Transport protocol to enable (repeatable). Defaults to stdio only.",
40
+ )
41
+ parser.add_argument(
42
+ "--host",
43
+ dest="host",
44
+ default=None,
45
+ help="Host interface for HTTP/SSE transports (default 127.0.0.1).",
46
+ )
47
+ parser.add_argument(
48
+ "--port",
49
+ dest="port",
50
+ type=int,
51
+ default=None,
52
+ help="Port for HTTP/SSE transports (default 8000).",
53
+ )
54
+
55
+ add_chroma_arguments(parser)
56
+ return parser
57
+
58
+
59
+ async def _run_transports(server: FastMCP, transports: List[str]) -> None:
60
+ """Run all selected transport protocols concurrently."""
61
+
62
+ coroutines = []
63
+ for name in transports:
64
+ if name == "stdio":
65
+ coroutines.append(server.run_stdio_async())
66
+ elif name == "sse":
67
+ coroutines.append(server.run_sse_async())
68
+ elif name == "http":
69
+ coroutines.append(server.run_streamable_http_async())
70
+ else: # pragma: no cover - argparse restricts values
71
+ raise ValueError(f"Unsupported transport: {name}")
72
+
73
+ await asyncio.gather(*coroutines)
74
+
75
+
76
+ def run_server(arguments: Iterable[str] | None = None) -> None:
77
+ """Entry point used by both CLI invocations and unit tests."""
78
+
79
+ parser = _build_argument_parser()
80
+ options = parser.parse_args(arguments)
81
+ root_path = resolve_knowledge_base_root(options.root)
82
+ rules = PathRules(root=root_path, protected_folders=(DOCS_FOLDER_NAME,))
83
+ install_default_documentation(root_path)
84
+ listeners: List[ChromaIngestor] = []
85
+ try:
86
+ listener = build_chroma_listener(options, root_path)
87
+ except Exception as exc: # pragma: no cover - configuration errors
88
+ raise SystemExit(f"Failed to configure Chroma ingestion: {exc}") from exc
89
+ if listener is not None:
90
+ listeners.append(listener)
91
+ logger.info(
92
+ "Chroma ingestion enabled (client=%s, collection=%s)",
93
+ options.chroma_client,
94
+ options.chroma_collection,
95
+ )
96
+ server = create_fastmcp_app(
97
+ rules,
98
+ host=options.host,
99
+ port=options.port,
100
+ listeners=listeners,
101
+ )
102
+ transports = options.transports or ["stdio"]
103
+ logger.info(f"Running server on {options.host}:{options.port} with transports {transports}")
104
+ logger.info(f"Data root is {root_path}")
105
+ print("--------------------------------",root_path,"--------------------------------")
106
+ asyncio.run(_run_transports(server, transports))
107
+
108
+
109
+ def main() -> None:
110
+ """CLI hook that executes :func:`run_server`."""
111
+
112
+ run_server()
113
+
114
+
115
+ if __name__ == "__main__":
116
+ main()
mcp_kb/cli/reindex.py ADDED
@@ -0,0 +1,90 @@
1
+ """CLI command to reindex the knowledge base into configured ingestors.
2
+
3
+ This command does not expose an MCP tool. Instead, it builds the configured
4
+ ingestors and calls their ``reindex`` method when available, allowing operators
5
+ to trigger a full rebuild of external indexes (e.g., Chroma) from the current
6
+ filesystem state.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import logging
12
+ from typing import Iterable, List
13
+
14
+ from mcp_kb.cli.args import add_chroma_arguments, build_chroma_listener
15
+ from mcp_kb.config import DOCS_FOLDER_NAME, resolve_knowledge_base_root
16
+ from mcp_kb.knowledge.events import KnowledgeBaseReindexListener
17
+ from mcp_kb.knowledge.store import KnowledgeBase
18
+ from mcp_kb.security.path_validation import PathRules
19
+
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ def _build_argument_parser() -> argparse.ArgumentParser:
25
+ """Return the argument parser for the reindex command."""
26
+
27
+ parser = argparse.ArgumentParser(description="Reindex the knowledge base into configured backends")
28
+ parser.add_argument(
29
+ "--root",
30
+ dest="root",
31
+ default=None,
32
+ help="Optional path to the knowledge base root (defaults to environment configuration)",
33
+ )
34
+ add_chroma_arguments(parser)
35
+ return parser
36
+
37
+
38
+ def run_reindex(arguments: Iterable[str] | None = None) -> int:
39
+ """Execute a reindex run across all registered ingestors.
40
+
41
+ The function constructs a :class:`~mcp_kb.knowledge.store.KnowledgeBase`
42
+ using the same root resolution logic as the server, builds any enabled
43
+ ingestion listeners from CLI options, and invokes ``reindex`` on those that
44
+ implement the optional protocol.
45
+
46
+ Parameters
47
+ ----------
48
+ arguments:
49
+ Optional iterable of command-line arguments, primarily used by tests.
50
+
51
+ Returns
52
+ -------
53
+ int
54
+ The total number of documents processed across all reindex-capable
55
+ listeners.
56
+ """
57
+
58
+ parser = _build_argument_parser()
59
+ options = parser.parse_args(arguments)
60
+ root_path = resolve_knowledge_base_root(options.root)
61
+ rules = PathRules(root=root_path, protected_folders=(DOCS_FOLDER_NAME,))
62
+ kb = KnowledgeBase(rules)
63
+
64
+ listeners: List[KnowledgeBaseReindexListener] = []
65
+ try:
66
+ chroma = build_chroma_listener(options, root_path)
67
+ except Exception as exc: # pragma: no cover - configuration errors
68
+ raise SystemExit(f"Failed to configure Chroma ingestion: {exc}") from exc
69
+ if chroma is not None and isinstance(chroma, KnowledgeBaseReindexListener):
70
+ listeners.append(chroma)
71
+
72
+ total = 0
73
+ for listener in listeners:
74
+ count = listener.reindex(kb)
75
+ logger.info("Reindexed %d documents via %s", count, listener.__class__.__name__)
76
+ total += count
77
+
78
+ return total
79
+
80
+
81
+ def main() -> None:
82
+ """CLI hook that executes :func:`run_reindex` and prints a summary."""
83
+
84
+ total = run_reindex()
85
+ print(f"Reindexed {total} documents")
86
+
87
+
88
+ if __name__ == "__main__":
89
+ main()
90
+
mcp_kb/config.py ADDED
@@ -0,0 +1,69 @@
1
+ """Configuration helpers for the MCP Knowledge Base server.
2
+
3
+ This module centralizes configuration lookups so that the rest of the codebase
4
+ only interacts with well-defined helper functions rather than environment
5
+ variables or default literals. Keeping configuration isolated makes the server
6
+ logic more reusable across different deployment environments because callers can
7
+ swap configurations programmatically or via environment variables without
8
+ modifying the core modules.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ from pathlib import Path
13
+ import os
14
+
15
+
16
+ DEFAULT_KNOWLEDGE_BASE_DIR = ".knowledgebase"
17
+ """str: Default relative directory for persisting knowledge base documents."""
18
+
19
+ DOCS_FOLDER_NAME = ".docs"
20
+ """str: Name of the documentation folder inside the knowledge base tree."""
21
+
22
+ DOC_FILENAME = "KNOWLEDBASE_DOC.md"
23
+ """str: Name of the canonical documentation file advertised in the PRD."""
24
+
25
+ DELETE_SENTINEL = "_DELETE_"
26
+ """str: Marker appended to filenames to implement soft deletion semantics."""
27
+
28
+ ENV_ROOT_KEY = "MCP_KB_ROOT"
29
+ """str: Environment variable that overrides the knowledge base root path."""
30
+
31
+
32
+ def resolve_knowledge_base_root(provided_path: str | None = None) -> Path:
33
+ """Return the absolute knowledge base root directory for the server.
34
+
35
+ The function applies the following precedence order when choosing a
36
+ directory:
37
+
38
+ 1. An explicit ``provided_path`` argument, if supplied by the caller.
39
+ 2. The ``MCP_KB_ROOT`` environment variable supplied by the host process.
40
+ 3. The default relative ``.knowledgebase`` directory.
41
+
42
+ The returned path is always absolute and resolved, which makes subsequent
43
+ filesystem operations robust against relative path confusion. The function
44
+ also ensures that the directory exists by calling ``mkdir`` with
45
+ ``parents=True`` and ``exist_ok=True`` so that repeated initializations are
46
+ idempotent.
47
+
48
+ Parameters
49
+ ----------
50
+ provided_path:
51
+ A string path explicitly supplied by the caller. ``None`` indicates
52
+ that the caller prefers environment or default resolution.
53
+
54
+ Returns
55
+ -------
56
+ Path
57
+ The resolved absolute path that should be used as the knowledge base
58
+ root directory.
59
+ """
60
+
61
+
62
+ candidate = provided_path or os.getenv(ENV_ROOT_KEY) or Path(
63
+ os.getenv('WORKSPACE_FOLDER_PATHS') or Path.cwd()
64
+ )/DEFAULT_KNOWLEDGE_BASE_DIR
65
+ root_path = Path(candidate).expanduser().resolve()
66
+ root_path.mkdir(parents=True, exist_ok=True)
67
+
68
+
69
+ return root_path
@@ -0,0 +1,36 @@
1
+ # Knowledge Base Usage Guide
2
+
3
+ Welcome to the MCP-managed knowledge base. This document is automatically
4
+ installed the first time the server starts to ensure every deployment ships with
5
+ baseline documentation. Customize it to describe project-specific conventions or
6
+ operational practices.
7
+
8
+ ## Structure
9
+
10
+ - All knowledge content lives beneath the `.knowledgebase/` root.
11
+ - Documentation resides under `.docs/` and is read-only from the MCP tools.
12
+ - Soft-deleted files are suffixed with `_DELETE_` and ignored by search/overview.
13
+
14
+ ## Recommended Practices
15
+
16
+ 1. Organize content into topic-based folders (e.g., `architecture/`, `ops/`).
17
+ 2. Keep document titles within the first heading so search results show context.
18
+ 3. Use relative markdown links to connect related documents inside the knowledge
19
+ base.
20
+ 4. Periodically review `_DELETE_` files and clean up as necessary via direct
21
+ filesystem operations.
22
+
23
+ ## Default Tools
24
+
25
+ | Tool | Purpose |
26
+ | --------------- | ----------------------------------------- |
27
+ | `create_file` | Create or overwrite markdown documents |
28
+ | `read_file` | Read entire files or specific line ranges |
29
+ | `append_file` | Append additional content to a file |
30
+ | `regex_replace` | Run regex-based replacements |
31
+ | `search` | Search text across active documents |
32
+ | `overview` | Display a tree overview of the knowledge |
33
+ | `documentation` | Read this documentation file |
34
+ | `delete` | Soft-delete files safely |
35
+
36
+ Update this document to reflect your team's workflows after deployment.
@@ -0,0 +1 @@
1
+ """Embedded data files shipped with the MCP knowledge base server."""
@@ -0,0 +1 @@
1
+ """Pluggable ingestion adapters for synchronizing knowledge base content."""