coremind-knowledge-mcp 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,3 @@
1
+ """带版本与读者权限的本地知识服务。"""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,174 @@
1
+ """按稳定文档 ID 与版本管理知识块,支持幂等导入、撤回和旧引文解析。"""
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+
8
+
9
+ class KnowledgeVersionConflict(ValueError):
10
+ """同一文档版本出现了不同内容。"""
11
+
12
+
13
+ def fingerprint(record):
14
+ content = {key: value for key, value in record.items() if key != "withdrawn"}
15
+ canonical = json.dumps(content, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
16
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
17
+
18
+
19
+ def table_context(record, chunk):
20
+ header = record.get("tableHeaders", {}).get(str(chunk.get("line")))
21
+ return {"tableHeader": [header]} if header is not None else {}
22
+
23
+
24
+ class KnowledgeCatalog:
25
+ def __init__(self, index, state_path=None):
26
+ self.index = index
27
+ self.state_path = Path(state_path) if state_path is not None else None
28
+ self.documents = {}
29
+ if self.state_path is not None and self.state_path.exists():
30
+ state = json.loads(self.state_path.read_text(encoding="utf-8"))
31
+ if state.get("schemaVersion") != 1:
32
+ raise ValueError("知识状态版本不受支持")
33
+ for record in state["documents"]:
34
+ self.documents[(record["docId"], record["version"])] = record
35
+ self.index.replace(self._active_chunks(self.documents))
36
+
37
+ def import_document(self, record):
38
+ result = self.import_documents([record])
39
+ return "imported" if result["imported"] else "unchanged"
40
+
41
+ def import_documents(self, records, *, withdrawals=()):
42
+ documents = dict(self.documents)
43
+ imported = 0
44
+ unchanged = 0
45
+ for record in records:
46
+ self._validate(record)
47
+ key = (record["docId"], record["version"])
48
+ existing = documents.get(key)
49
+ if existing is not None:
50
+ if "tableHeaders" not in existing and "tableHeaders" in record:
51
+ # 旧状态未保存表格结构。先补派生字段,再对照同版本的原文、位置和范围。
52
+ existing = {**existing, "tableHeaders": record["tableHeaders"]}
53
+ if fingerprint(existing) == fingerprint(record):
54
+ documents[key] = existing
55
+ unchanged += 1
56
+ continue
57
+ raise KnowledgeVersionConflict(
58
+ f"文档 {record['docId']} 版本 {record['version']} 内容已变化;请提升版本号"
59
+ )
60
+ documents[key] = record
61
+ imported += 1
62
+ for key in withdrawals:
63
+ if key not in documents:
64
+ raise ValueError("未知的文档版本")
65
+ documents[key] = {**documents[key], "withdrawn": True}
66
+ if documents != self.documents:
67
+ self._commit(documents)
68
+ return {"imported": imported, "unchanged": unchanged}
69
+
70
+ def withdraw(self, doc_id, version):
71
+ self.import_documents([], withdrawals=[(doc_id, version)])
72
+ return "withdrawn"
73
+
74
+ def search(self, query, *, scope, as_of, limit=5, mode="sparse"):
75
+ return self.index.search(
76
+ query, scope=scope, as_of=as_of, limit=limit, mode=mode
77
+ )
78
+
79
+ def resolve(self, doc_id, version, file, line=None, locator=None, *, scope, as_of):
80
+ record = self.documents.get((doc_id, version))
81
+ if (
82
+ record is None
83
+ or record["access"] not in {"public", scope}
84
+ or as_of < record["validFrom"]
85
+ or (record["validUntil"] is not None and as_of >= record["validUntil"])
86
+ ):
87
+ return {"status": "unknown", "docId": doc_id, "version": version}
88
+ if record.get("withdrawn"):
89
+ return {"status": "withdrawn", "docId": doc_id, "version": version}
90
+ for chunk in record["chunks"]:
91
+ if chunk.get("file", record["file"]) != file:
92
+ continue
93
+ if line is not None and chunk.get("line") != line:
94
+ continue
95
+ if locator is not None and chunk.get("locator") != locator:
96
+ continue
97
+ return {
98
+ "status": "available",
99
+ "docId": doc_id,
100
+ "version": version,
101
+ "file": file,
102
+ "line": chunk.get("line"),
103
+ "locator": chunk.get("locator"),
104
+ "text": chunk["text"],
105
+ **table_context(record, chunk),
106
+ }
107
+ return {
108
+ "status": "missing",
109
+ "docId": doc_id,
110
+ "version": version,
111
+ "file": file,
112
+ }
113
+
114
+ @staticmethod
115
+ def _active_chunks(documents):
116
+ chunks = []
117
+ for record in documents.values():
118
+ if record.get("withdrawn"):
119
+ continue
120
+ for chunk in record["chunks"]:
121
+ chunks.append(
122
+ {
123
+ **chunk,
124
+ **table_context(record, chunk),
125
+ "docId": record["docId"],
126
+ "version": record["version"],
127
+ "file": record["file"],
128
+ "access": record["access"],
129
+ "validFrom": record["validFrom"],
130
+ "validUntil": record["validUntil"],
131
+ }
132
+ )
133
+ return chunks
134
+
135
+ def _commit(self, documents):
136
+ chunks = self._active_chunks(documents)
137
+ if self.state_path is None:
138
+ self.index.replace(chunks)
139
+ else:
140
+ self.index.replace(chunks, before_publish=lambda: self._save(documents))
141
+ self.documents = documents
142
+
143
+ def _save(self, documents):
144
+ self.state_path.parent.mkdir(parents=True, exist_ok=True)
145
+ state = {
146
+ "schemaVersion": 1,
147
+ "documents": list(documents.values()),
148
+ }
149
+ temporary = self.state_path.with_suffix(self.state_path.suffix + ".tmp")
150
+ try:
151
+ temporary.write_text(
152
+ json.dumps(state, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
153
+ )
154
+ os.replace(temporary, self.state_path)
155
+ finally:
156
+ temporary.unlink(missing_ok=True)
157
+
158
+ @staticmethod
159
+ def _validate(record):
160
+ for field in ("docId", "file", "access", "validFrom"):
161
+ value = record.get(field)
162
+ if not isinstance(value, str) or not value.strip():
163
+ raise ValueError(f"缺少有效字段:{field}")
164
+ version = record.get("version")
165
+ if isinstance(version, bool) or not isinstance(version, int) or version < 1:
166
+ raise ValueError("文档版本必须是正整数")
167
+ chunks = record.get("chunks")
168
+ if not isinstance(chunks, list) or not chunks:
169
+ raise ValueError("文档至少需要一个知识块")
170
+ for chunk in chunks:
171
+ if not isinstance(chunk.get("text"), str) or not chunk["text"].strip():
172
+ raise ValueError("知识块正文不能为空")
173
+ if chunk.get("line") is None and not chunk.get("locator"):
174
+ raise ValueError("知识块缺少来源位置")
@@ -0,0 +1,62 @@
1
+ """将本地的中文 PDF、DOCX 或 Markdown 转为带来源定位的 UTF-8 JSON。"""
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from docling.datamodel.accelerator_options import AcceleratorOptions
9
+ from docling.datamodel.base_models import ConversionStatus, InputFormat
10
+ from docling.datamodel.pipeline_options import PdfPipelineOptions, RapidOcrOptions
11
+ from docling.document_converter import DocumentConverter, PdfFormatOption
12
+ from docling_core.types.doc import DocItemLabel, TableItem, TextItem
13
+
14
+ # Docling 按格式延迟加载流水线;长驻宿主复用同一转换器可避免重复加载模型。
15
+ _converter = DocumentConverter(
16
+ allowed_formats=[InputFormat.PDF, InputFormat.DOCX, InputFormat.MD],
17
+ format_options={
18
+ InputFormat.PDF: PdfFormatOption(pipeline_options=PdfPipelineOptions(
19
+ accelerator_options=AcceleratorOptions(device="cpu"),
20
+ ocr_options=RapidOcrOptions(lang=["ch"]),
21
+ )),
22
+ },
23
+ )
24
+
25
+
26
+ def parse_document(path):
27
+ path = Path(path)
28
+ if not path.is_file():
29
+ raise ValueError(f"找不到本地文件:{path}")
30
+ result = _converter.convert(path)
31
+ if result.status != ConversionStatus.SUCCESS:
32
+ raise ValueError(f"文档未完整解析:{result.status.value}")
33
+
34
+ chunks = []
35
+ heading = None
36
+ for item, _ in result.document.iterate_items():
37
+ if isinstance(item, TableItem):
38
+ text = item.export_to_markdown(doc=result.document)
39
+ elif isinstance(item, TextItem):
40
+ text = item.text
41
+ else:
42
+ continue
43
+ if not text.strip():
44
+ continue
45
+ if item.label in (DocItemLabel.TITLE, DocItemLabel.SECTION_HEADER):
46
+ heading = text.strip()
47
+ pages = sorted({p.page_no for p in item.prov})
48
+ if pages and result.input.format == InputFormat.PDF:
49
+ locator = "page:" + ",".join(map(str, pages))
50
+ else:
51
+ locator = f"section:{heading or item.self_ref}"
52
+ chunks.append({"text": text.strip(), "locator": locator})
53
+ if not chunks:
54
+ raise ValueError("文档没有可定位的文本或表格")
55
+ return chunks
56
+
57
+
58
+ def main():
59
+ parser = argparse.ArgumentParser(description=__doc__)
60
+ parser.add_argument("file", type=Path)
61
+ args = parser.parse_args()
62
+ sys.stdout.buffer.write((json.dumps(parse_document(args.file), ensure_ascii=False) + "\n").encode("utf-8"))
@@ -0,0 +1,199 @@
1
+ """在本机用 BGE-M3 和 Qdrant 检索有来源、权限和生效日期的知识块。"""
2
+
3
+ import hashlib
4
+ import threading
5
+ from datetime import date
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import onnxruntime as ort
10
+ from qdrant_client import QdrantClient, models
11
+ from tokenizers import Tokenizer
12
+
13
+ MODEL_REPO = "gpahal/bge-m3-onnx-int8"
14
+ MODEL_REVISION = "2b34e84df040034d4b9eabb62383a87c18955822"
15
+ MODEL_FILES = {
16
+ "model_quantized.onnx": "16de7ea1146ca427e14938ec3e9abfdcaff0e6ac76434cd693ac35d761250bcb",
17
+ "tokenizer.json": "249df0778f236f6ece390de0de746838ef25b9d6954b68c2ee71249e0a9d8fd4",
18
+ }
19
+
20
+
21
+ def verify_model(directory):
22
+ for name, expected in MODEL_FILES.items():
23
+ with (Path(directory) / name).open("rb") as file:
24
+ if hashlib.file_digest(file, "sha256").hexdigest() != expected:
25
+ raise ValueError(f"模型文件摘要不符:{name}")
26
+
27
+
28
+ def ordinal(value):
29
+ if not isinstance(value, str) or len(value) != 10:
30
+ raise ValueError("日期必须使用 YYYY-MM-DD")
31
+ parsed = date.fromisoformat(value)
32
+ if parsed.isoformat() != value:
33
+ raise ValueError("日期必须使用 YYYY-MM-DD")
34
+ return parsed.toordinal()
35
+
36
+
37
+ class KnowledgeIndex:
38
+ def __init__(self, model_dir):
39
+ verify_model(model_dir)
40
+ self.tokenizer = Tokenizer.from_file(str(Path(model_dir) / "tokenizer.json"))
41
+ self.tokenizer.enable_padding(
42
+ pad_id=self.tokenizer.token_to_id("<pad>"), pad_token="<pad>"
43
+ )
44
+ self.special = {
45
+ self.tokenizer.token_to_id(t) for t in ("<s>", "</s>", "<pad>", "<unk>")
46
+ }
47
+ options = ort.SessionOptions()
48
+ options.intra_op_num_threads = 4
49
+ self.model = ort.InferenceSession(
50
+ str(Path(model_dir) / "model_quantized.onnx"),
51
+ options,
52
+ providers=["CPUExecutionProvider"],
53
+ )
54
+ self.db = QdrantClient(":memory:")
55
+ self.lock = threading.RLock()
56
+
57
+ def close(self):
58
+ with self.lock:
59
+ self.db.close()
60
+
61
+ def _encode(self, texts):
62
+ encodings = self.tokenizer.encode_batch(texts)
63
+ ids = np.asarray([item.ids for item in encodings], dtype=np.int64)
64
+ if ids.shape[1] > 512:
65
+ raise ValueError("单个知识块或问题超过 512 个 token,请先按来源位置拆分")
66
+ mask = np.asarray([item.attention_mask for item in encodings], dtype=np.int64)
67
+ dense, weights = self.model.run(
68
+ ["dense_vecs", "sparse_vecs"], {"input_ids": ids, "attention_mask": mask}
69
+ )
70
+ for vector, token_weights, item in zip(dense, weights, encodings, strict=True):
71
+ # BGE-M3 的词项权重取同一词项在各位置的最大正权重。
72
+ sparse = {}
73
+ for token, weight in zip(item.ids, token_weights.reshape(-1), strict=True):
74
+ if token not in self.special and weight > 0:
75
+ sparse[token] = max(sparse.get(token, 0.0), float(weight))
76
+ yield (
77
+ vector.tolist(),
78
+ models.SparseVector(indices=list(sparse), values=list(sparse.values())),
79
+ )
80
+
81
+ def replace(self, chunks, *, before_publish=None):
82
+ payloads = []
83
+ for chunk in chunks:
84
+ for field in ("docId", "file", "text", "access"):
85
+ if not isinstance(chunk.get(field), str) or not chunk[field].strip():
86
+ raise ValueError(f"缺少有效字段:{field}")
87
+ version = chunk.get("version")
88
+ if (
89
+ isinstance(version, bool)
90
+ or not isinstance(version, (str, int))
91
+ or not str(version).strip()
92
+ ):
93
+ raise ValueError("缺少文档版本")
94
+ line = chunk.get("line")
95
+ locator = chunk.get("locator")
96
+ if line is not None and (type(line) is not int or line < 1):
97
+ raise ValueError("无效的来源行号")
98
+ if line is None and not (isinstance(locator, str) and locator.strip()):
99
+ raise ValueError("知识块缺少来源位置")
100
+ start = ordinal(chunk["validFrom"])
101
+ end = (
102
+ ordinal(chunk["validUntil"])
103
+ if chunk["validUntil"] is not None
104
+ else date.max.toordinal() + 1
105
+ )
106
+ if start >= end:
107
+ raise ValueError("无效的来源生效区间")
108
+ payloads.append({**chunk, "_start": start, "_end": end})
109
+ with self.lock:
110
+ staged = QdrantClient(":memory:")
111
+ staged.create_collection(
112
+ "knowledge",
113
+ vectors_config={
114
+ "dense": models.VectorParams(
115
+ size=1024, distance=models.Distance.COSINE
116
+ )
117
+ },
118
+ sparse_vectors_config={"sparse": models.SparseVectorParams()},
119
+ )
120
+ try:
121
+ for offset in range(0, len(payloads), 8):
122
+ batch = payloads[offset : offset + 8]
123
+ vectors = self._encode([p["text"] for p in batch])
124
+ staged.upsert(
125
+ "knowledge",
126
+ points=[
127
+ models.PointStruct(
128
+ id=offset + i,
129
+ payload=payload,
130
+ vector={"dense": dense, "sparse": sparse},
131
+ )
132
+ for i, (payload, (dense, sparse)) in enumerate(
133
+ zip(batch, vectors, strict=True)
134
+ )
135
+ ],
136
+ )
137
+ # 新索引构建和目录落盘均成功后,读请求才可见新版本。
138
+ if before_publish is not None:
139
+ before_publish()
140
+ except Exception:
141
+ staged.close()
142
+ raise
143
+ previous, self.db = self.db, staged
144
+ previous.close()
145
+
146
+ def search(self, question, *, scope, as_of, limit=5, mode="hybrid"):
147
+ if not isinstance(question, str) or not question.strip():
148
+ raise ValueError("问题不能为空")
149
+ if not isinstance(scope, str) or not scope.strip():
150
+ raise ValueError("需要宿主提供读者权限")
151
+ if (
152
+ type(limit) is not int
153
+ or not 1 <= limit <= 20
154
+ or mode not in {"dense", "sparse", "hybrid"}
155
+ ):
156
+ raise ValueError("无效的检索模式或候选数")
157
+ day = ordinal(as_of)
158
+ visible = models.Filter(
159
+ must=[
160
+ models.FieldCondition(
161
+ key="access",
162
+ match=models.MatchAny(any=list(dict.fromkeys(["public", scope]))),
163
+ ),
164
+ models.FieldCondition(key="_start", range=models.Range(lte=day)),
165
+ models.FieldCondition(key="_end", range=models.Range(gt=day)),
166
+ ]
167
+ )
168
+ with self.lock:
169
+ dense, sparse = next(self._encode([question]))
170
+ if mode != "dense" and not sparse.indices:
171
+ return []
172
+ if mode != "sparse" and not any(dense):
173
+ return []
174
+ if mode == "hybrid":
175
+ options = {
176
+ "query": models.FusionQuery(fusion=models.Fusion.RRF),
177
+ "prefetch": [
178
+ models.Prefetch(
179
+ query=vector,
180
+ using=key,
181
+ filter=visible,
182
+ limit=max(20, limit),
183
+ )
184
+ for key, vector in (("dense", dense), ("sparse", sparse))
185
+ ],
186
+ }
187
+ else:
188
+ options = {"query": dense if mode == "dense" else sparse, "using": mode}
189
+ points = self.db.query_points(
190
+ "knowledge",
191
+ **options,
192
+ query_filter=visible,
193
+ limit=limit,
194
+ with_payload=True,
195
+ ).points
196
+ return [
197
+ {k: v for k, v in point.payload.items() if k not in {"_start", "_end"}}
198
+ for point in points
199
+ ]
@@ -0,0 +1,197 @@
1
+ """从本地资料建索引,向获准的 CoreMind 运行提供只读知识查询。"""
2
+
3
+ import argparse
4
+ import hmac
5
+ import json
6
+ import os
7
+ from datetime import date
8
+ from pathlib import Path
9
+ from typing import Annotated
10
+
11
+ import uvicorn
12
+ from markdown_it import MarkdownIt
13
+ from mcp.server.fastmcp import FastMCP
14
+ from pydantic import Field
15
+ from starlette.requests import Request
16
+ from starlette.responses import JSONResponse
17
+
18
+ from . import __version__
19
+ from .catalog import KnowledgeCatalog
20
+ from .text import terms
21
+
22
+
23
+ def load_corpus(manifest_path):
24
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
25
+ as_of = date.fromisoformat(manifest["asOf"]).isoformat()
26
+ directory = (manifest_path.parent / "sources").resolve(strict=True)
27
+ records = []
28
+ seen = set()
29
+ for source in manifest["documents"]:
30
+ file = source["file"]
31
+ if not file or Path(file).name != file or ":" in file or "/" in file or "\\" in file:
32
+ raise ValueError("来源文件必须是 sources 目录下的文件名")
33
+ path = (directory / file).resolve(strict=True)
34
+ if path.parent != directory or not path.is_file():
35
+ raise ValueError(f"来源文件超出资料目录:{file}")
36
+ start = date.fromisoformat(source["validFrom"]).isoformat()
37
+ until = source["validUntil"]
38
+ if until is not None:
39
+ until = date.fromisoformat(until).isoformat()
40
+ if start >= until:
41
+ raise ValueError(f"来源有效期无效:{file}")
42
+ version = source["version"]
43
+ doc_id = source["id"]
44
+ if not isinstance(doc_id, str) or not doc_id.strip() or type(version) is not int or version < 1:
45
+ raise ValueError(f"来源 ID 或版本无效:{file}")
46
+ if (doc_id, version) in seen:
47
+ raise ValueError(f"来源 ID 与版本重复:{file}")
48
+ seen.add((doc_id, version))
49
+ access = source["access"]
50
+ if not isinstance(access, str) or not access.strip() or access != access.strip():
51
+ raise ValueError(f"来源范围无效:{file}")
52
+ metadata = {}
53
+ if path.suffix.lower() == ".md":
54
+ lines = path.read_text(encoding="utf-8").splitlines()
55
+ items = [
56
+ {"text": content.strip(), "line": line}
57
+ for line, content in enumerate(lines, 1)
58
+ if next(terms(content), None) is not None
59
+ ]
60
+ headers = {}
61
+ for token in MarkdownIt("commonmark").enable("table").parse("\n".join(lines)):
62
+ if token.type == "table_open":
63
+ header_index, table_end = token.map
64
+ # 第一个数据行在表头和分隔行之后;保留原始行号与原文。
65
+ header = {"line": header_index + 1, "text": lines[header_index]}
66
+ for number in range(header_index + 3, table_end + 1):
67
+ headers[str(number)] = header
68
+ metadata["tableHeaders"] = headers
69
+ elif path.suffix.lower() in {".pdf", ".docx"}:
70
+ try:
71
+ from .docling_bridge import parse_document
72
+ except ModuleNotFoundError as exc:
73
+ if exc.name != "docling":
74
+ raise
75
+ raise ValueError("处理 PDF 或 DOCX 需要安装知识组件的 documents 扩展") from exc
76
+
77
+ items = parse_document(path)
78
+ else:
79
+ raise ValueError(f"不支持的资料格式:{file}")
80
+ if not items:
81
+ raise ValueError(f"资料未提取出正文:{file}")
82
+ records.append(
83
+ {
84
+ "docId": doc_id,
85
+ "version": version,
86
+ "file": file,
87
+ "access": access,
88
+ "validFrom": start,
89
+ "validUntil": until,
90
+ "chunks": items,
91
+ **metadata,
92
+ }
93
+ )
94
+ return as_of, records
95
+
96
+
97
+ def make_app(catalog, scope, as_of, token):
98
+ mcp = FastMCP("CoreMind Knowledge", stateless_http=True, json_response=True)
99
+
100
+ @mcp.tool(structured_output=False)
101
+ def search_knowledge(query: Annotated[str, Field(min_length=1, max_length=500)]) -> str:
102
+ """查找可参考的资料片段并附版本与来源位置。相似片段只是候选证据。表格行按 tableHeader 解释列值,引用数据行。"""
103
+ if not query.strip():
104
+ raise ValueError("查询不能为空")
105
+ matches = catalog.search(query.strip(), scope=scope, as_of=as_of, limit=5, mode="sparse")
106
+ fields = {"docId", "version", "file", "line", "locator", "text", "tableHeader"}
107
+ citations = [{key: value for key, value in row.items() if key in fields} for row in matches]
108
+ return json.dumps({"citations": citations}, ensure_ascii=False)
109
+
110
+ @mcp.tool(structured_output=False)
111
+ def resolve_citation(
112
+ docId: Annotated[str, Field(min_length=1, max_length=200)],
113
+ version: Annotated[int, Field(ge=1)],
114
+ file: Annotated[str, Field(min_length=1, max_length=200)],
115
+ line: Annotated[int | None, Field(ge=1)] = None,
116
+ locator: Annotated[str | None, Field(max_length=200)] = None,
117
+ ) -> str:
118
+ """解析旧运行留下的引文;返回可用原文、已撤回或未知状态。"""
119
+ return json.dumps(
120
+ catalog.resolve(
121
+ docId.strip(), version, file, line=line, locator=locator, scope=scope, as_of=as_of
122
+ ),
123
+ ensure_ascii=False,
124
+ )
125
+
126
+ @mcp.custom_route("/health", methods=["GET"])
127
+ async def health(_request):
128
+ return JSONResponse({"status": "ready"})
129
+
130
+ app = mcp.streamable_http_app()
131
+
132
+ async def authorized(asgi_scope, receive, send):
133
+ if asgi_scope["type"] == "http":
134
+ request = Request(asgi_scope, receive)
135
+ actual = request.headers.get("authorization", "").encode("utf-8")
136
+ if not hmac.compare_digest(actual, token):
137
+ await JSONResponse({"error": "unauthorized"}, status_code=401)(
138
+ asgi_scope, receive, send
139
+ )
140
+ return
141
+ await app(asgi_scope, receive, send)
142
+
143
+ return authorized
144
+
145
+
146
+ def main(*, legacy_manifest=None):
147
+ parser = argparse.ArgumentParser(description=__doc__)
148
+ parser.add_argument("--version", action="version", version=__version__)
149
+ parser.add_argument("--manifest", type=Path, default=legacy_manifest, required=legacy_manifest is None)
150
+ parser.add_argument("--model-dir", type=Path, required=True)
151
+ parser.add_argument("--scope", default="public", required=legacy_manifest is None)
152
+ parser.add_argument("--port", type=int, default=8767)
153
+ parser.add_argument("--state", type=Path, required=legacy_manifest is None)
154
+ parser.add_argument(
155
+ "--withdraw",
156
+ action="append",
157
+ default=[],
158
+ metavar="DOC:VERSION",
159
+ help="启动时撤回指定文档版本,可重复",
160
+ )
161
+ args = parser.parse_args()
162
+ if not args.scope.strip() or args.scope != args.scope.strip():
163
+ parser.error("--scope 需要非空的阅读范围")
164
+ authorization = os.environ.get("COREMIND_KNOWLEDGE_AUTHORIZATION", "")
165
+ if not authorization.startswith("Bearer ") or len(authorization.removeprefix("Bearer ").strip()) < 24:
166
+ parser.error("请通过 COREMIND_KNOWLEDGE_AUTHORIZATION 提供独立的本地 Bearer 令牌")
167
+ if args.state is not None:
168
+ sources = (args.manifest.parent / "sources").resolve()
169
+ for output in (args.state, args.state.with_suffix(args.state.suffix + ".tmp")):
170
+ target = output.resolve()
171
+ if target == args.manifest.resolve() or target.is_relative_to(sources) or target.is_relative_to(args.model_dir.resolve()):
172
+ parser.error("--state 必须与清单、来源目录和模型目录分开")
173
+ withdrawals = []
174
+ for item in args.withdraw:
175
+ doc_id, separator, version = item.rpartition(":")
176
+ if not separator or not doc_id.strip() or not version.isascii() or not version.isdigit() or int(version) < 1:
177
+ parser.error("--withdraw 需要 DOC:VERSION,版本必须为正整数")
178
+ withdrawals.append((doc_id.strip(), int(version)))
179
+ from .retrieval import KnowledgeIndex
180
+
181
+ as_of, records = load_corpus(args.manifest)
182
+ index = KnowledgeIndex(args.model_dir)
183
+ try:
184
+ catalog = KnowledgeCatalog(index, args.state)
185
+ catalog.import_documents(records, withdrawals=withdrawals)
186
+ uvicorn.run(
187
+ make_app(catalog, args.scope, as_of, authorization.encode("utf-8")),
188
+ host="127.0.0.1",
189
+ port=args.port,
190
+ access_log=False,
191
+ )
192
+ finally:
193
+ index.close()
194
+
195
+
196
+ if __name__ == "__main__":
197
+ main()
@@ -0,0 +1,13 @@
1
+ """识别中文及字母数字知识行。"""
2
+
3
+ import re
4
+ import unicodedata
5
+
6
+
7
+ def terms(text):
8
+ normalized = unicodedata.normalize("NFKC", text).lower()
9
+ for token in re.findall(r"[\u3400-\u9fff]+|[a-z0-9]+", normalized):
10
+ if len(token) > 1 and "\u3400" <= token[0] <= "\u9fff":
11
+ yield from (token[i:i + 2] for i in range(len(token) - 1))
12
+ else:
13
+ yield token
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.4
2
+ Name: coremind-knowledge-mcp
3
+ Version: 0.1.0
4
+ Summary: Local, versioned document retrieval and citations over Streamable HTTP MCP
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.12
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: markdown-it-py==4.3.0
10
+ Requires-Dist: mcp==1.30.0
11
+ Requires-Dist: numpy==2.3.4
12
+ Requires-Dist: onnxruntime==1.23.2
13
+ Requires-Dist: pydantic<3,>=2
14
+ Requires-Dist: qdrant-client==1.15.1
15
+ Requires-Dist: starlette<2
16
+ Requires-Dist: tokenizers==0.22.1
17
+ Requires-Dist: uvicorn==0.54.0
18
+ Provides-Extra: documents
19
+ Requires-Dist: docling[rapidocr]==2.151.1; extra == "documents"
20
+ Dynamic: license-file
21
+
22
+ # CoreMind Knowledge MCP
23
+
24
+ `coremind-knowledge-mcp` 0.1.0 可独立安装,面向任何支持 Streamable HTTP 的 MCP 客户端。服务使用固定的 BGE-M3 ONNX 模型与内存 Qdrant 检索,目录和撤回记录持久化在业务方指定的状态文件。
25
+
26
+ ## 安装与首次查询
27
+
28
+ 在专用 Python 3.12 环境中从 PyPI 安装组件,下载[示例目录](https://github.com/Eclipseic1848/CoreMind/tree/main/components/knowledge/example)中的清单、`sources/` 与 `query.py`。模型目录应包含 `model_quantized.onnx` 和 `tokenizer.json`,来源为 `gpahal/bge-m3-onnx-int8` 的 `2b34e84df040034d4b9eabb62383a87c18955822` 修订。服务启动时校验两者的 SHA-256。
29
+
30
+ 将示例文件放入空业务目录,激活专用 Python 环境并在该目录执行以下命令。令牌由服务所有者生成,两个终端的 `COREMIND_KNOWLEDGE_AUTHORIZATION` 都应为同一完整的 `Bearer <随机令牌>`,令牌至少 24 个字符。将 `/path/to/model` 换为本地模型目录。
31
+
32
+ ```sh
33
+ python -m pip install coremind-knowledge-mcp==0.1.0
34
+ coremind-knowledge-mcp --version
35
+ coremind-knowledge-mcp --manifest ./manifest.json --model-dir /path/to/model --scope records --state ./state/catalog.json
36
+ ```
37
+
38
+ 在另一个终端运行 `python -X utf8 query.py 松纹卡`。示例回查 `desk.md` 第 3 行的“松纹卡 | 银杏台”,并携带第 1 行表头。服务监听 `127.0.0.1:8767/mcp`,`--port` 可改端口,客户端可用 `KNOWLEDGE_MCP_URL` 指定地址。按 Ctrl+C 停止服务。每个读者范围使用专用服务进程和凭据。
39
+
40
+ Markdown 使用基础安装。PDF/DOCX 使用可选扩展 `python -m pip install "coremind-knowledge-mcp[documents]==0.1.0"`。扫描 PDF 使用 Docling 与 RapidOCR 的本地模型,离线部署前需预置解析模型。
41
+
42
+ 从源码交付时,在组件目录运行 `python -m pip wheel --no-deps . -w dist`。在服务环境中用 `python -m pip install /path/to/coremind_knowledge_mcp-0.1.0-py3-none-any.whl` 安装该文件。
43
+
44
+ ## 版本与状态
45
+
46
+ 来源内容变化时提升清单中的文档版本。用有效期切换现行版本,或在下次启动附加 `--withdraw desk:1`。历史回查只向获准读者返回当前可见的原文或撤回标记。来源、清单、模型和状态文件分别管理,每份可写状态只由一个进程负责。更新或卸载组件前停止服务并保留状态和原文。升级先用状态副本核对当前和已撤回引文,失败时用原环境和备份恢复。卸载命令是 `python -m pip uninstall coremind-knowledge-mcp`。
47
+
48
+ ## English quick start
49
+
50
+ Install version 0.1.0 from PyPI in a dedicated Python 3.12 environment, or build and install the wheel as shown above for a source deployment. Start the service with your project manifest, BGE-M3 model directory, reader scope, and writable catalog path. Use the same `Authorization` header in your client and server environment. Run `python -X utf8 query.py` from the example directory to search and resolve an original citation. Markdown works with the base wheel. Install the `documents` extra for Docling/RapidOCR PDF or DOCX support and provision parser assets for offline use. Stop the server with Ctrl+C. Before changing versions, back up the project manifest, originals and catalog with withdrawal history, then test the replacement on a copy. Uninstall the component from its dedicated environment after removing the client binding.
@@ -0,0 +1,12 @@
1
+ coremind_knowledge_mcp/__init__.py,sha256=qipea6oD8FkTGbpHH9JKLadUfZpTX5rNSINQ6toYVlY,78
2
+ coremind_knowledge_mcp/catalog.py,sha256=d9pCxG6I-niuSLStwWOpH5MeOHa8MRBKxC03sSLkbkQ,7129
3
+ coremind_knowledge_mcp/docling_bridge.py,sha256=H-696IZ0Jad8A3Do6-HLFaoKoMZ_syBaNHxR7HvzvVA,2409
4
+ coremind_knowledge_mcp/retrieval.py,sha256=KJyrnSIelfNN_uxYYejjczcX6T_3ZdNQ5DHwrK-C6sk,8247
5
+ coremind_knowledge_mcp/server.py,sha256=CkwYGqLyskEiVDIXCimSSFczWaBFSvwo9-tGofgqFHM,8719
6
+ coremind_knowledge_mcp/text.py,sha256=v2UjOTFHh_4FBLYS97-EPvTEHkTDoX-Q9CsvhGTSm6s,401
7
+ coremind_knowledge_mcp-0.1.0.dist-info/licenses/LICENSE,sha256=KXXZrpPu9JjGxQX1EbhIre6gO48Zu_QosI7izMUDKTM,1070
8
+ coremind_knowledge_mcp-0.1.0.dist-info/METADATA,sha256=pmMYD7U9vX6DYZ0Pgrdao3lDDOt-20Fs1XCc4H2HdTY,4086
9
+ coremind_knowledge_mcp-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
10
+ coremind_knowledge_mcp-0.1.0.dist-info/entry_points.txt,sha256=cp_K643ccSJz1IoMMKRgFJ9EOUDCfAO6JZQdUaQ00aY,78
11
+ coremind_knowledge_mcp-0.1.0.dist-info/top_level.txt,sha256=AQ_9yuy0gdPhldML5r79k-RaJU-QRCrCeh9npH0xrnw,23
12
+ coremind_knowledge_mcp-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ coremind-knowledge-mcp = coremind_knowledge_mcp.server:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Eclipseic1848
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 @@
1
+ coremind_knowledge_mcp