mcp-kb 0.3.1__py3-none-any.whl → 0.3.2__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/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,168 @@
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. The helpers are
6
+ careful to avoid embedding environment defaults directly into the argparse
7
+ objects so that downstream consumers can layer persisted runtime configuration
8
+ in between CLI flags and built-in defaults.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ from argparse import ArgumentParser, Namespace
15
+ from pathlib import Path
16
+ from typing import Optional
17
+
18
+ from mcp_kb.ingest.chroma import SUPPORTED_CLIENTS, ChromaConfiguration, ChromaIngestor
19
+
20
+
21
+ def parse_bool(value: str | bool | None) -> bool:
22
+ """Return ``True`` when ``value`` represents an affirmative boolean string.
23
+
24
+ The function accepts case-insensitive variants such as "true", "t",
25
+ "yes", and "1". ``None`` yields ``False``.
26
+ """
27
+
28
+ if isinstance(value, bool):
29
+ return value
30
+ if value is None:
31
+ return False
32
+ return value.lower() in {"1", "true", "t", "yes", "y"}
33
+
34
+
35
+ def add_chroma_arguments(parser: ArgumentParser) -> None:
36
+ """Register Chroma ingestion arguments on ``parser``.
37
+
38
+ The parser intentionally suppresses defaults for all options so that the
39
+ calling code can merge CLI flags, environment variables, and persisted
40
+ runtime configuration explicitly. This keeps precedence handling in a
41
+ single location rather than scattering logic across the argument
42
+ registrations themselves.
43
+ """
44
+
45
+ parser.add_argument(
46
+ "--chroma-client",
47
+ dest="chroma_client",
48
+ choices=SUPPORTED_CLIENTS,
49
+ default=argparse.SUPPRESS,
50
+ help="Client implementation for mirroring data to ChromaDB (default: persistent).",
51
+ )
52
+ parser.add_argument(
53
+ "--chroma-collection",
54
+ dest="chroma_collection",
55
+ default=argparse.SUPPRESS,
56
+ help="Chroma collection name used to store documents.",
57
+ )
58
+ parser.add_argument(
59
+ "--chroma-embedding",
60
+ dest="chroma_embedding",
61
+ default=argparse.SUPPRESS,
62
+ help="Embedding function name registered with chromadb.utils.embedding_functions.",
63
+ )
64
+ parser.add_argument(
65
+ "--chroma-data-dir",
66
+ dest="chroma_data_dir",
67
+ default=argparse.SUPPRESS,
68
+ help="Storage directory for the persistent Chroma client.",
69
+ )
70
+ parser.add_argument(
71
+ "--chroma-host",
72
+ dest="chroma_host",
73
+ default=argparse.SUPPRESS,
74
+ help="Target host for HTTP or cloud Chroma clients.",
75
+ )
76
+ parser.add_argument(
77
+ "--chroma-port",
78
+ dest="chroma_port",
79
+ type=int,
80
+ default=argparse.SUPPRESS,
81
+ help="Port for the HTTP Chroma client.",
82
+ )
83
+ parser.add_argument(
84
+ "--chroma-ssl",
85
+ dest="chroma_ssl",
86
+ type=parse_bool,
87
+ default=argparse.SUPPRESS,
88
+ help="Toggle SSL for the HTTP Chroma client (default: true).",
89
+ )
90
+ parser.add_argument(
91
+ "--chroma-tenant",
92
+ dest="chroma_tenant",
93
+ default=argparse.SUPPRESS,
94
+ help="Tenant identifier for Chroma Cloud deployments.",
95
+ )
96
+ parser.add_argument(
97
+ "--chroma-database",
98
+ dest="chroma_database",
99
+ default=argparse.SUPPRESS,
100
+ help="Database name for Chroma Cloud deployments.",
101
+ )
102
+ parser.add_argument(
103
+ "--chroma-api-key",
104
+ dest="chroma_api_key",
105
+ default=argparse.SUPPRESS,
106
+ help="API key used to authenticate against Chroma Cloud.",
107
+ )
108
+ parser.add_argument(
109
+ "--chroma-custom-auth",
110
+ dest="chroma_custom_auth",
111
+ default=argparse.SUPPRESS,
112
+ help="Optional custom auth credentials for self-hosted HTTP deployments.",
113
+ )
114
+ parser.add_argument(
115
+ "--chroma-id-prefix",
116
+ dest="chroma_id_prefix",
117
+ default=argparse.SUPPRESS,
118
+ help="Prefix applied to document IDs stored in Chroma (default: kb::).",
119
+ )
120
+ parser.add_argument(
121
+ "--chroma-sentence-transformer",
122
+ dest="chroma_sentence_transformer",
123
+ default=argparse.SUPPRESS,
124
+ help="Sentence transformer model name.",
125
+ )
126
+ parser.add_argument(
127
+ "--chroma-chunk-size",
128
+ dest="chroma_chunk_size",
129
+ type=int,
130
+ default=argparse.SUPPRESS,
131
+ help="Chunk size for the sentence transformer model.",
132
+ )
133
+ parser.add_argument(
134
+ "--chroma-chunk-overlap",
135
+ dest="chroma_chunk_overlap",
136
+ type=int,
137
+ default=argparse.SUPPRESS,
138
+ help="Chunk overlap for the sentence transformer model.",
139
+ )
140
+
141
+
142
+ def build_chroma_listener(options: Namespace, root: Path) -> Optional[ChromaIngestor]:
143
+ """Construct a Chroma listener from parsed CLI options when enabled.
144
+
145
+ Returns ``None`` when the configured client type is ``off``.
146
+ """
147
+
148
+ configuration = ChromaConfiguration.from_options(
149
+ root=root,
150
+ client_type=options.chroma_client,
151
+ collection_name=options.chroma_collection,
152
+ embedding=options.chroma_embedding,
153
+ data_directory=options.chroma_data_dir,
154
+ host=options.chroma_host,
155
+ port=options.chroma_port,
156
+ ssl=options.chroma_ssl,
157
+ tenant=options.chroma_tenant,
158
+ database=options.chroma_database,
159
+ api_key=options.chroma_api_key,
160
+ custom_auth_credentials=options.chroma_custom_auth,
161
+ id_prefix=options.chroma_id_prefix,
162
+ sentence_transformer=options.chroma_sentence_transformer,
163
+ chunk_size=options.chroma_chunk_size,
164
+ chunk_overlap=options.chroma_chunk_overlap,
165
+ )
166
+ if not configuration.enabled:
167
+ return None
168
+ return ChromaIngestor(configuration)
mcp_kb/cli/main.py ADDED
@@ -0,0 +1,175 @@
1
+ """Command line interface for running the MCP knowledge base server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import logging
8
+ from typing import Iterable, List
9
+
10
+ from mcp_kb.config import DATA_FOLDER_NAME, resolve_knowledge_base_root
11
+ from mcp_kb.cli.args import add_chroma_arguments, build_chroma_listener
12
+ from mcp_kb.cli.runtime_config import (
13
+ apply_cli_runtime_configuration,
14
+ load_runtime_configuration,
15
+ persist_runtime_configuration,
16
+ )
17
+ from mcp_kb.ingest.chroma import ChromaIngestor
18
+ from mcp_kb.knowledge.bootstrap import install_default_documentation
19
+ from mcp_kb.security.path_validation import PathRules
20
+ from mcp_kb.server.app import create_fastmcp_app
21
+ from mcp.server.fastmcp import FastMCP
22
+ from mcp_kb.ui import start_ui_server
23
+
24
+ logging.basicConfig(level=logging.INFO)
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ def _build_argument_parser() -> argparse.ArgumentParser:
30
+ """Create and return the argument parser used by ``main``."""
31
+
32
+ parser = argparse.ArgumentParser(
33
+ description="Run the MCP knowledge base server", allow_abbrev=False
34
+ )
35
+ parser.add_argument(
36
+ "--root",
37
+ dest="root",
38
+ default=argparse.SUPPRESS,
39
+ help="Optional path to the knowledge base root (defaults to environment configuration)",
40
+ )
41
+ parser.add_argument(
42
+ "--transport",
43
+ dest="transports",
44
+ action="append",
45
+ choices=["stdio", "sse", "http"],
46
+ default=argparse.SUPPRESS,
47
+ help="Transport protocol to enable (repeatable). Defaults to stdio only.",
48
+ )
49
+ parser.add_argument(
50
+ "--host",
51
+ dest="host",
52
+ default=argparse.SUPPRESS,
53
+ help="Host interface for HTTP/SSE transports (default 127.0.0.1).",
54
+ )
55
+ parser.add_argument(
56
+ "--port",
57
+ dest="port",
58
+ type=int,
59
+ default=argparse.SUPPRESS,
60
+ help="Port for HTTP/SSE transports (default 8000).",
61
+ )
62
+ parser.add_argument(
63
+ "--ui-port",
64
+ dest="ui_port",
65
+ type=int,
66
+ default=argparse.SUPPRESS,
67
+ help=(
68
+ "Starting port for the human UI (default 8765). If occupied, the UI "
69
+ "server increments the port by 1 until a free one is found."
70
+ ),
71
+ )
72
+ parser.add_argument(
73
+ "--no-ui",
74
+ dest="no_ui",
75
+ action="store_true",
76
+ help=(
77
+ "Disable the human UI entirely, even when HTTP/SSE transports are active."
78
+ ),
79
+ )
80
+
81
+ add_chroma_arguments(parser)
82
+ return parser
83
+
84
+
85
+ async def _run_transports(server: FastMCP, transports: List[str]) -> None:
86
+ """Run all selected transport protocols concurrently."""
87
+
88
+ coroutines = []
89
+ for name in transports:
90
+ if name == "stdio":
91
+ coroutines.append(server.run_stdio_async())
92
+ elif name == "sse":
93
+ coroutines.append(server.run_sse_async())
94
+ elif name == "http":
95
+ coroutines.append(server.run_streamable_http_async())
96
+ else: # pragma: no cover - argparse restricts values
97
+ raise ValueError(f"Unsupported transport: {name}")
98
+
99
+ await asyncio.gather(*coroutines)
100
+
101
+
102
+ def run_server(arguments: Iterable[str] | None = None) -> None:
103
+ """Entry point used by both CLI invocations and unit tests.
104
+
105
+ Besides orchestrating the server lifecycle, the function resolves
106
+ configuration values by layering command-line arguments over environment
107
+ variables and any persisted defaults stored in the knowledge base data
108
+ directory. The resolved mapping is written back to disk so that future runs
109
+ inherit the same defaults unless explicitly overridden.
110
+ """
111
+
112
+ parser = _build_argument_parser()
113
+ options = parser.parse_args(arguments)
114
+ root_path = resolve_knowledge_base_root(getattr(options, "root", None))
115
+
116
+ persisted_config = load_runtime_configuration(root_path)
117
+ resolved_config = apply_cli_runtime_configuration(
118
+ options,
119
+ root=root_path,
120
+ persisted=persisted_config,
121
+ )
122
+ rules = PathRules(root=root_path, protected_folders=(DATA_FOLDER_NAME,))
123
+ install_default_documentation(root_path)
124
+ listeners: List[ChromaIngestor] = []
125
+ try:
126
+ listener = build_chroma_listener(options, root_path)
127
+ except Exception as exc: # pragma: no cover - configuration errors
128
+ logger.exception(exc)
129
+ raise SystemExit(f"Failed to configure Chroma ingestion: {exc}") from exc
130
+ if listener is not None:
131
+ listeners.append(listener)
132
+ logger.info(
133
+ "Chroma ingestion enabled (client=%s, collection=%s)",
134
+ options.chroma_client,
135
+ options.chroma_collection,
136
+ )
137
+ server = create_fastmcp_app(
138
+ rules,
139
+ host=options.host,
140
+ port=options.port,
141
+ listeners=listeners,
142
+ )
143
+ transports = options.transports or ["stdio"]
144
+ options.transports = transports
145
+ resolved_config["transports"] = transports
146
+ logger.info(
147
+ f"Running server on {options.host}:{options.port} with transports {transports}"
148
+ )
149
+ logger.info(f"Data root is {root_path}")
150
+
151
+ #having only the README.md. Think about a question a user might have. then using only
152
+ # Start the human-accessible UI when an HTTP-capable transport is active.
153
+ if not options.no_ui and any(t in ("http", "sse") for t in transports):
154
+ kb = getattr(server, "kb", None)
155
+ if kb is not None:
156
+ ui = start_ui_server(
157
+ kb,
158
+ host=options.host or "127.0.0.1",
159
+ port=options.ui_port,
160
+ )
161
+ logger.info("UI available at http://%s:%d", ui.host, ui.port)
162
+
163
+ persist_runtime_configuration(root_path, resolved_config)
164
+
165
+ asyncio.run(_run_transports(server, transports))
166
+
167
+
168
+ def main() -> None:
169
+ """CLI hook that executes :func:`run_server`."""
170
+
171
+ run_server()
172
+
173
+
174
+ if __name__ == "__main__":
175
+ main()
mcp_kb/cli/reindex.py ADDED
@@ -0,0 +1,113 @@
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
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import logging
13
+ from typing import Iterable, List
14
+
15
+ from mcp_kb.cli.args import add_chroma_arguments, build_chroma_listener
16
+ from mcp_kb.cli.runtime_config import (
17
+ apply_cli_runtime_configuration,
18
+ load_runtime_configuration,
19
+ persist_runtime_configuration,
20
+ )
21
+ from mcp_kb.config import DATA_FOLDER_NAME, resolve_knowledge_base_root
22
+ from mcp_kb.knowledge.events import KnowledgeBaseReindexListener
23
+ from mcp_kb.knowledge.store import KnowledgeBase
24
+ from mcp_kb.security.path_validation import PathRules
25
+
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ def _build_argument_parser() -> argparse.ArgumentParser:
31
+ """Return the argument parser for the reindex command."""
32
+
33
+ parser = argparse.ArgumentParser(
34
+ description="Reindex the knowledge base into configured backends",
35
+ allow_abbrev=False,
36
+ )
37
+ parser.add_argument(
38
+ "--root",
39
+ dest="root",
40
+ default=argparse.SUPPRESS,
41
+ help="Optional path to the knowledge base root (defaults to environment configuration)",
42
+ )
43
+ add_chroma_arguments(parser)
44
+ return parser
45
+
46
+
47
+ def run_reindex(arguments: Iterable[str] | None = None) -> int:
48
+ """Execute a reindex run across all registered ingestors.
49
+
50
+ The function constructs a :class:`~mcp_kb.knowledge.store.KnowledgeBase`
51
+ using the same root resolution logic as the server, builds any enabled
52
+ ingestion listeners from CLI options, and invokes ``reindex`` on those that
53
+ implement the optional protocol. Configuration precedence mirrors the main
54
+ server: command-line arguments override environment variables, which in
55
+ turn override the last persisted configuration snapshot. The resolved
56
+ mapping is written back to disk so the next invocation inherits the same
57
+ defaults.
58
+
59
+ Parameters
60
+ ----------
61
+ arguments:
62
+ Optional iterable of command-line arguments, primarily used by tests.
63
+
64
+ Returns
65
+ -------
66
+ int
67
+ The total number of documents processed across all reindex-capable
68
+ listeners.
69
+ """
70
+
71
+ parser = _build_argument_parser()
72
+ options = parser.parse_args(arguments)
73
+ root_path = resolve_knowledge_base_root(getattr(options, "root", None))
74
+
75
+ persisted_config = load_runtime_configuration(root_path)
76
+ resolved_config = apply_cli_runtime_configuration(
77
+ options,
78
+ root=root_path,
79
+ persisted=persisted_config,
80
+ )
81
+ rules = PathRules(root=root_path, protected_folders=(DATA_FOLDER_NAME,))
82
+ kb = KnowledgeBase(rules)
83
+
84
+ listeners: List[KnowledgeBaseReindexListener] = []
85
+ try:
86
+ chroma = build_chroma_listener(options, root_path)
87
+ except Exception as exc: # pragma: no cover - configuration errors
88
+ logger.exception(exc)
89
+ raise SystemExit(f"Failed to configure Chroma ingestion: {exc}") from exc
90
+ if chroma is not None and isinstance(chroma, KnowledgeBaseReindexListener):
91
+ listeners.append(chroma)
92
+
93
+ total = 0
94
+ for listener in listeners:
95
+ logger.info("Reindexing via %s", listener.__class__.__name__)
96
+ count = listener.reindex(kb)
97
+ logger.info("Reindexed %d documents via %s", count, listener.__class__.__name__)
98
+ total += count
99
+
100
+ persist_runtime_configuration(root_path, resolved_config)
101
+
102
+ return total
103
+
104
+
105
+ def main() -> None:
106
+ """CLI hook that executes :func:`run_reindex` and prints a summary."""
107
+
108
+ total = run_reindex()
109
+ print(f"Reindexed {total} documents")
110
+
111
+
112
+ if __name__ == "__main__":
113
+ main()