bugx-cli 0.1.3 → 0.1.4
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.
- package/core/README.md +5 -3
- package/core/assets/bugx-wechat-group.png +0 -0
- package/core/bugx.md +2 -2
- package/core/bugx_paths.py +10 -2
- package/core/bundled_docs/OVERVIEW.md +310 -0
- package/core/bundled_docs/README.md +10 -0
- package/core/bundled_docs/README_EN.md +278 -0
- package/core/bundled_docs/ai/01_AI_REFERENCE.md +833 -0
- package/core/bundled_docs/ai/02_AI_USAGE.md +161 -0
- package/core/bundled_docs/ai/03_AI_COMMANDS.md +322 -0
- package/core/bundled_docs/guides/01_USER_GUIDE.md +887 -0
- package/core/bundled_docs/guides/02_COMMANDS.md +935 -0
- package/core/bundled_docs/guides/03_TROUBLESHOOTING.md +763 -0
- package/core/bundled_docs/guides/04_CLOUD_AUTH_AND_SYNC_COOKBOOK.md +48 -0
- package/core/bundled_docs/guides/05_HOST_MATRIX_AND_DISPATCH.md +23 -0
- package/core/bundled_docs/guides/06_PROBES_AND_POC_COOKBOOK.md +49 -0
- package/core/bundled_docs/guides/07_LIFECYCLE_AND_RECOVERY_STATES.md +46 -0
- package/core/bundled_docs/guides/08_LESSONS_AND_PRIVACY_BOUNDARY.md +35 -0
- package/core/bundled_docs/hosts/bugx-claude_SKILL.md +326 -0
- package/core/bundled_docs/hosts/bugx-dsh_SKILL.md +229 -0
- package/core/bundled_docs/hosts/bugx-opencode_SKILL.md +129 -0
- package/core/bundled_docs/hosts/bugx-zcode_SKILL.md +459 -0
- package/core/bundled_docs/hosts/bugx_SKILL.md +118 -0
- package/core/bundled_docs/hosts/cline_bugx_SKILL.md +69 -0
- package/core/bundled_docs/hosts/platform_bugx_SKILL.md +50 -0
- package/core/bundled_docs/manifest.json +140 -0
- package/core/bundled_docs/reference/01_ENVIRONMENT_VARIABLES.md +421 -0
- package/core/bundled_docs/reference/04_REPOSITORY_TOPOLOGY.md +180 -0
- package/core/cli-help.txt +7 -3
- package/core/cloud_sync/cloud_client.py +81 -2
- package/core/cloud_sync/endpoint_router.py +22 -9
- package/core/cloud_sync/issue_uploader.py +297 -0
- package/core/cloud_sync/sensitive_filter.py +77 -7
- package/core/contracts/AGENT_GUIDE.md +3 -9
- package/core/contracts/README.md +1 -1
- package/core/contracts/bugx-runtime-contract.md +10 -20
- package/core/contracts/bugx-worker.md +1 -1
- package/core/engine-integrity.json +209 -93
- package/core/host_acp/antigravity.py +153 -0
- package/core/host_runtime/adapters.py +5 -1
- package/core/host_runtime/antigravity.py +162 -0
- package/core/host_runtime/host_bootstrap.py +18 -7
- package/core/host_runtime/host_evaluators.py +4 -4
- package/core/host_runtime/host_registry.py +2 -1
- package/core/host_runtime/mcp_process_tracker.py +30 -3
- package/core/host_runtime/mcp_registry_gate.py +34 -11
- package/core/hosts/antigravity.py +115 -0
- package/core/hosts/codex.py +3 -0
- package/core/hosts/dsh.py +42 -23
- package/core/hosts/minimax.py +5 -4
- package/core/i18n.py +94 -5
- package/core/infra/README.md +1 -1
- package/core/infra/build_info.py +2 -2
- package/core/launch_phases/README.md +2 -2
- package/core/launch_phases/startup_version_gate.py +2 -2
- package/core/launch_phases/supervisor_bridge.py +2 -0
- package/core/launch_phases/supervisor_degraded.py +7 -5
- package/core/ledger/README.md +1 -1
- package/core/locales/en-US.json +3 -3
- package/core/locales/zh-CN.json +3 -3
- package/core/mcp_runtime_support/environment.py +6 -1
- package/core/metadata.txt +1 -1
- package/core/planning/README.md +1 -1
- package/core/planning/prompt_harness.py +2 -2
- package/core/probes/codebase_memory_probe.py +43 -24
- package/core/probes/probe_registry.py +10 -7
- package/core/prompts/command_routing_en.md +6 -5
- package/core/prompts/command_routing_zh.md +6 -5
- package/core/repair/rsi_rounds.py +3 -0
- package/core/repair/self_heal.py +160 -6
- package/core/retrieval/README.md +1 -1
- package/core/runtime/README.md +1 -1
- package/core/runtime/scenario_eval.py +5 -1
- package/core/runtime/tool_install_targets.py +12 -2
- package/core/skills/README.md +4 -2
- package/core/skills/bugx_docs_cloud_sync.py +658 -0
- package/core/skills/bugx_docs_mcp_server.py +966 -140
- package/core/supervisor/README.md +1 -1
- package/core/supervisor/worker_execution.py +16 -3
- package/core/webui/docs_session_service.py +40 -2
- package/core/webui/mcp_inspector.py +6 -6
- package/ecosystem/integrations/cline/skills/bugx/SKILL.md +46 -46
- package/ecosystem/integrations/dsh/agents/bugx.md +2 -1
- package/ecosystem/integrations/dsh/mcp/package.json +1 -1
- package/ecosystem/integrations/dsh/skills/bugx/SKILL.md +5 -5
- package/ecosystem/integrations/dsh/ui/package.json +1 -1
- package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +2 -2
- package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
- package/ecosystem/integrations/pi/skills/bugx/SKILL.md +5 -5
- package/ecosystem/integrations/qoder/CONNECTORS.md +11 -23
- package/ecosystem/integrations/qoder/connector-meta.json +1 -1
- package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
- package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +8 -7
- package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/agents/bugx-worker.md +14 -18
- package/ecosystem/plugins/bugx/agents/bugx.md +45 -49
- package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +7 -7
- package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +2 -2
- package/interfaces/cli/bugx_cli/__init__.py +1 -1
- package/interfaces/cli/bugx_cli/cli.py +138 -8
- package/interfaces/cli/bugx_cli/commands/agent.py +376 -69
- package/interfaces/cli/bugx_cli/commands/cloud.py +42 -1
- package/interfaces/cli/bugx_cli/commands/doctor.py +650 -223
- package/interfaces/cli/bugx_cli/commands/guide.py +143 -0
- package/interfaces/cli/bugx_cli/commands/issue.py +262 -0
- package/interfaces/cli/bugx_cli/commands/lifecycle.py +55 -25
- package/interfaces/cli/bugx_cli/commands/plugin.py +295 -54
- package/interfaces/cli/bugx_cli/commands/plugin_antigravity.py +350 -0
- package/interfaces/cli/bugx_cli/commands/plugin_claude.py +2 -2
- package/interfaces/cli/bugx_cli/commands/plugin_kimi.py +154 -62
- package/interfaces/cli/bugx_cli/commands/plugin_minimax.py +308 -108
- package/interfaces/cli/bugx_cli/commands/system.py +11 -1
- package/interfaces/cli/bugx_cli/common.py +39 -8
- package/interfaces/cli/bugx_cli/host_adapters.py +40 -3
- package/interfaces/cli/bugx_cli/hosts/registry.py +3 -2
- package/interfaces/cli/bugx_cli/hosts/template_engine.py +21 -2
- package/interfaces/cli/bugx_cli/infra/__init__.py +4 -0
- package/interfaces/cli/bugx_cli/infra/ai_advisor.py +14 -12
- package/interfaces/cli/bugx_cli/infra/engine_installer.py +76 -10
- package/interfaces/cli/bugx_cli/infra/host_sync.py +66 -1
- package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +240 -50
- package/package.json +3 -2
- package/pyproject.toml +22 -2
- package/scripts/sync-version.mjs +1 -1
- package/skills/README.md +1 -2
- package/skills/platform/bugx/SKILL.md +50 -0
- package/skills/platform/bugx-user/SKILL.md +0 -92
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
|
-
"""BugX
|
|
2
|
+
"""BugX 双作用域本地/云端协同文档 MCP(SQLite FTS5 trigram + 章节切分 + 不可变缓存)。"""
|
|
3
3
|
|
|
4
4
|
from __future__ import annotations
|
|
5
5
|
# --- 引擎导入根(直接执行脚本时自举 core.* 命名空间)---
|
|
@@ -29,14 +29,21 @@ from core.infra.build_info import BASE_VERSION
|
|
|
29
29
|
_CORE_DIR = Path(__file__).resolve().parent.parent if Path(__file__).resolve().parent.name == "skills" else Path(__file__).resolve().parent
|
|
30
30
|
if str(_CORE_DIR) not in sys.path:
|
|
31
31
|
sys.path.insert(0, str(_CORE_DIR))
|
|
32
|
+
if str(_CORE_DIR.parent) not in sys.path:
|
|
33
|
+
sys.path.insert(0, str(_CORE_DIR.parent))
|
|
34
|
+
|
|
35
|
+
from core.skills import bugx_docs_cloud_sync as _docs_sync # noqa: E402
|
|
32
36
|
|
|
33
37
|
JSONRPC_VERSION = "2.0"
|
|
34
38
|
MCP_PROTOCOL_VERSION = "2024-11-05"
|
|
35
39
|
SERVER_NAME = "bugx-docs"
|
|
36
40
|
SERVER_VERSION = BASE_VERSION
|
|
41
|
+
SCHEMA_VERSION = "v2-trigram-section-hybrid"
|
|
42
|
+
OFFICIAL_LIBRARY_ID = "bugx:official"
|
|
37
43
|
MAX_FILE_BYTES = 1_000_000
|
|
38
44
|
MAX_FILES = 500
|
|
39
45
|
MAX_RESULT_BYTES = 12_000
|
|
46
|
+
MAX_SECTION_CHARS = 6_000
|
|
40
47
|
|
|
41
48
|
|
|
42
49
|
class DocsMcpError(ValueError):
|
|
@@ -70,23 +77,18 @@ def _db_path(root: Path, value: str | Path) -> Path:
|
|
|
70
77
|
return path
|
|
71
78
|
|
|
72
79
|
|
|
73
|
-
def
|
|
74
|
-
"""只读取项目文档,避免把源码、运行态和凭据误纳入知识库。"""
|
|
75
|
-
candidates: list[Path] = []
|
|
76
|
-
for path in (root / "README.md",):
|
|
77
|
-
if path.is_file() and not path.is_symlink():
|
|
78
|
-
candidates.append(path)
|
|
79
|
-
for directory in (root / "docs", root / "core"):
|
|
80
|
-
if not directory.is_dir() or directory.is_symlink():
|
|
81
|
-
continue
|
|
82
|
-
candidates.extend(
|
|
83
|
-
path for path in sorted(directory.rglob("*.md"))
|
|
84
|
-
if path.is_file() and not path.is_symlink()
|
|
85
|
-
)
|
|
80
|
+
def _collect_md_files(candidates: list[Path], base: Path, *, strip_prefix: str = "") -> list[tuple[str, Path]]:
|
|
86
81
|
unique: list[tuple[str, Path]] = []
|
|
87
82
|
seen: set[str] = set()
|
|
88
83
|
for path in candidates:
|
|
89
|
-
|
|
84
|
+
if path.is_symlink() or not path.is_file():
|
|
85
|
+
continue
|
|
86
|
+
try:
|
|
87
|
+
relative = path.relative_to(base).as_posix()
|
|
88
|
+
except ValueError:
|
|
89
|
+
continue
|
|
90
|
+
if strip_prefix and relative.startswith(strip_prefix):
|
|
91
|
+
relative = relative[len(strip_prefix):]
|
|
90
92
|
if relative in seen:
|
|
91
93
|
continue
|
|
92
94
|
seen.add(relative)
|
|
@@ -98,11 +100,68 @@ def _source_files(root: Path) -> list[tuple[str, Path]]:
|
|
|
98
100
|
unique.append((relative, path))
|
|
99
101
|
if len(unique) >= MAX_FILES:
|
|
100
102
|
break
|
|
101
|
-
# ponytail: bounded recursive scan; add a signed manifest when repositories
|
|
102
|
-
# need more than 500 documentation files or remote libraries.
|
|
103
103
|
return unique
|
|
104
104
|
|
|
105
105
|
|
|
106
|
+
def _project_source_files(root: Path) -> list[tuple[str, Path]]:
|
|
107
|
+
"""仅读取当前项目可控文档(优先级保证核心 README/docs 不被海量内部产物挤出配额)。"""
|
|
108
|
+
candidates: list[Path] = []
|
|
109
|
+
for name in ("README.md", "README_EN.md", "AGENTS.md", "CLAUDE.md", "CONTRIBUTING.md", "CHANGELOG.md"):
|
|
110
|
+
candidates.append(root / name)
|
|
111
|
+
# 优先级队列:指南与设计 -> 技能目录 -> 内置核心(排除 bundled_docs 防双份重复)
|
|
112
|
+
docs_dir = root / "docs"
|
|
113
|
+
if docs_dir.is_dir() and not docs_dir.is_symlink():
|
|
114
|
+
# 先收 01_guides/03_ai/04_reference 等公开文档,最后才收 08_internal
|
|
115
|
+
public_mds: list[Path] = []
|
|
116
|
+
internal_mds: list[Path] = []
|
|
117
|
+
for path in sorted(docs_dir.rglob("*.md")):
|
|
118
|
+
if "08_internal" in path.parts:
|
|
119
|
+
internal_mds.append(path)
|
|
120
|
+
else:
|
|
121
|
+
public_mds.append(path)
|
|
122
|
+
candidates.extend(public_mds)
|
|
123
|
+
candidates.extend(internal_mds)
|
|
124
|
+
for directory in (root / "skills", root / ".agents" / "skills", root / "core"):
|
|
125
|
+
if not directory.is_dir() or directory.is_symlink():
|
|
126
|
+
continue
|
|
127
|
+
for path in sorted(directory.rglob("*.md")):
|
|
128
|
+
if "bundled_docs" in path.parts:
|
|
129
|
+
continue
|
|
130
|
+
candidates.append(path)
|
|
131
|
+
return _collect_md_files(candidates, root)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _official_source_files(core_root: Path | None = None) -> list[tuple[str, Path]]:
|
|
135
|
+
"""收集随包/全局引擎内自带的 BugX 官方文档资产。"""
|
|
136
|
+
croot = (core_root or _CORE_DIR).resolve()
|
|
137
|
+
candidates: list[Path] = []
|
|
138
|
+
bundled = croot / "bundled_docs"
|
|
139
|
+
if bundled.is_dir() and not bundled.is_symlink():
|
|
140
|
+
for path in sorted(bundled.rglob("*.md")):
|
|
141
|
+
if path.name == "README.md" and path.parent == bundled:
|
|
142
|
+
continue
|
|
143
|
+
candidates.append(path)
|
|
144
|
+
out = _collect_md_files(candidates, bundled if bundled.is_dir() else croot)
|
|
145
|
+
seen = {rel for rel, _ in out}
|
|
146
|
+
extra_candidates: list[Path] = []
|
|
147
|
+
if (croot / "bugx.md").is_file():
|
|
148
|
+
extra_candidates.append(croot / "bugx.md")
|
|
149
|
+
for sub in ("contracts", "prompts", "audit_packs"):
|
|
150
|
+
subdir = croot / sub
|
|
151
|
+
if subdir.is_dir() and not subdir.is_symlink():
|
|
152
|
+
extra_candidates.extend(sorted(subdir.rglob("*.md")))
|
|
153
|
+
for rel, path in _collect_md_files(extra_candidates, croot.parent if croot.name == "core" else croot):
|
|
154
|
+
if not rel.startswith("core/"):
|
|
155
|
+
rel = f"core/{rel}"
|
|
156
|
+
if rel not in seen and len(out) < MAX_FILES:
|
|
157
|
+
seen.add(rel)
|
|
158
|
+
out.append((rel, path))
|
|
159
|
+
return out
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
_source_files = _project_source_files
|
|
163
|
+
|
|
164
|
+
|
|
106
165
|
def _version(root: Path, supplied: str | None) -> str:
|
|
107
166
|
value = str(supplied or os.environ.get("BUGX_DOCS_VERSION") or "working-tree").strip()
|
|
108
167
|
if not value or len(value) > 128:
|
|
@@ -110,6 +169,106 @@ def _version(root: Path, supplied: str | None) -> str:
|
|
|
110
169
|
return value
|
|
111
170
|
|
|
112
171
|
|
|
172
|
+
def _doc_tier(source_path: str, library_id: str) -> float:
|
|
173
|
+
path = source_path.lstrip("/")
|
|
174
|
+
if path in ("README.md", "README_EN.md"):
|
|
175
|
+
return 3.5
|
|
176
|
+
if path.startswith("guides/04_") or path.startswith("guides/05_") or path.startswith("guides/06_") or path.startswith("guides/07_") or path.startswith("guides/08_"):
|
|
177
|
+
return 4.0
|
|
178
|
+
if path.startswith("docs/01_guides/04_") or path.startswith("docs/01_guides/05_") or path.startswith("docs/01_guides/06_") or path.startswith("docs/01_guides/07_") or path.startswith("docs/01_guides/08_"):
|
|
179
|
+
return 4.0
|
|
180
|
+
if path.startswith(("guides/", "docs/01_guides/", "ai/", "docs/03_ai/")):
|
|
181
|
+
return 3.0
|
|
182
|
+
if path in ("skills/platform/bugx/SKILL.md", "ai/SKILL.md"):
|
|
183
|
+
return 2.8
|
|
184
|
+
if path.startswith(("reference/", "docs/04_reference/", "hosts/", "core/contracts/", "core/prompts/")):
|
|
185
|
+
return 2.0
|
|
186
|
+
if path.startswith("docs/02_architecture/"):
|
|
187
|
+
return 1.5
|
|
188
|
+
if path.startswith("docs/08_internal/") or path.startswith("docs/05_release-notes/001_") or path.startswith("docs/05_release-notes/002_"):
|
|
189
|
+
return -1.5
|
|
190
|
+
if library_id == OFFICIAL_LIBRARY_ID:
|
|
191
|
+
return 1.2
|
|
192
|
+
return 1.0
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _split_markdown_sections(doc_id: str, library_id: str, content: str) -> list[tuple[Any, ...]]:
|
|
196
|
+
"""按 fenced-code-aware ATX 标题切片,避免 # 注释误切与大文件截断。"""
|
|
197
|
+
lines = content.splitlines(keepends=True)
|
|
198
|
+
headings: list[tuple[int, int, str]] = [] # (char_offset, level, title)
|
|
199
|
+
offset = 0
|
|
200
|
+
fence_marker: str | None = None
|
|
201
|
+
heading_re = re.compile(r"^(#{1,6})\s+(.+?)\s*#*\s*$")
|
|
202
|
+
|
|
203
|
+
for line in lines:
|
|
204
|
+
stripped = line.lstrip()
|
|
205
|
+
fence_match = re.match(r"^(`{3,}|~{3,})", stripped)
|
|
206
|
+
if fence_match:
|
|
207
|
+
marker = fence_match.group(1)
|
|
208
|
+
if fence_marker is None:
|
|
209
|
+
fence_marker = marker
|
|
210
|
+
elif stripped.startswith(fence_marker[0] * len(fence_marker)):
|
|
211
|
+
fence_marker = None
|
|
212
|
+
elif fence_marker is None:
|
|
213
|
+
m = heading_re.match(line.rstrip("\r\n"))
|
|
214
|
+
if m:
|
|
215
|
+
headings.append((offset, len(m.group(1)), m.group(2).strip()))
|
|
216
|
+
offset += len(line)
|
|
217
|
+
|
|
218
|
+
raw_sections: list[tuple[str, str, int, int, int, str]] = []
|
|
219
|
+
if not headings:
|
|
220
|
+
raw_sections.append(("(document)", "(document)", 1, 0, len(content), content))
|
|
221
|
+
else:
|
|
222
|
+
stack: list[tuple[int, str]] = []
|
|
223
|
+
if headings[0][0] > 0:
|
|
224
|
+
intro = content[:headings[0][0]].strip()
|
|
225
|
+
if intro:
|
|
226
|
+
raw_sections.append(("(preamble)", "(preamble)", 1, 0, headings[0][0], intro))
|
|
227
|
+
for idx, (h_start, level, title) in enumerate(headings):
|
|
228
|
+
while stack and stack[-1][0] >= level:
|
|
229
|
+
stack.pop()
|
|
230
|
+
stack.append((level, title))
|
|
231
|
+
h_path = " > ".join(t for _, t in stack)
|
|
232
|
+
# 找到同级或更高级别的下一个标题作为整章边界
|
|
233
|
+
end_pos = len(content)
|
|
234
|
+
for j in range(idx + 1, len(headings)):
|
|
235
|
+
if headings[j][1] <= level:
|
|
236
|
+
end_pos = headings[j][0]
|
|
237
|
+
break
|
|
238
|
+
# 紧邻切片边界仅取到下一个标题开始以保持去重,完整跨子章节读取由 fetch_doc(start, full_end) 负责
|
|
239
|
+
slice_end = headings[idx + 1][0] if idx + 1 < len(headings) else len(content)
|
|
240
|
+
sec_text = content[h_start:slice_end].strip()
|
|
241
|
+
if sec_text:
|
|
242
|
+
raw_sections.append((title, h_path, level, h_start, end_pos, sec_text))
|
|
243
|
+
|
|
244
|
+
rows: list[tuple[Any, ...]] = []
|
|
245
|
+
seq = 0
|
|
246
|
+
for title, h_path, level, c_start, c_end, sec_text in raw_sections:
|
|
247
|
+
if len(sec_text) <= MAX_SECTION_CHARS:
|
|
248
|
+
seq += 1
|
|
249
|
+
sec_id = f"{doc_id}#s{seq}"
|
|
250
|
+
rows.append((sec_id, doc_id, library_id, title, h_path, level, c_start, c_end, sec_text))
|
|
251
|
+
else:
|
|
252
|
+
# 按空行切分子片
|
|
253
|
+
pos = 0
|
|
254
|
+
part = 1
|
|
255
|
+
while pos < len(sec_text):
|
|
256
|
+
cut = min(len(sec_text), pos + MAX_SECTION_CHARS)
|
|
257
|
+
if cut < len(sec_text):
|
|
258
|
+
nl = sec_text.rfind("\n\n", pos + 1000, cut)
|
|
259
|
+
if nl > pos:
|
|
260
|
+
cut = nl + 2
|
|
261
|
+
chunk = sec_text[pos:cut].strip()
|
|
262
|
+
if chunk:
|
|
263
|
+
seq += 1
|
|
264
|
+
sec_id = f"{doc_id}#s{seq}"
|
|
265
|
+
part_title = title if part == 1 else f"{title} (part {part})"
|
|
266
|
+
rows.append((sec_id, doc_id, library_id, part_title, h_path, level, c_start, c_end, chunk))
|
|
267
|
+
part += 1
|
|
268
|
+
pos = cut if cut > pos else pos + MAX_SECTION_CHARS
|
|
269
|
+
return rows
|
|
270
|
+
|
|
271
|
+
|
|
113
272
|
def _citation(row: Mapping[str, Any]) -> dict[str, Any]:
|
|
114
273
|
return {
|
|
115
274
|
"document_id": row["doc_id"],
|
|
@@ -126,15 +285,22 @@ def _citation(row: Mapping[str, Any]) -> dict[str, Any]:
|
|
|
126
285
|
}
|
|
127
286
|
|
|
128
287
|
|
|
129
|
-
def
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
288
|
+
def _populate_database(
|
|
289
|
+
connection: sqlite3.Connection,
|
|
290
|
+
*,
|
|
291
|
+
sources: list[tuple[str, Path]],
|
|
292
|
+
library_id: str,
|
|
293
|
+
project_id: str,
|
|
294
|
+
library_name: str,
|
|
295
|
+
version: str,
|
|
296
|
+
source_label: str,
|
|
297
|
+
private_flag: int,
|
|
298
|
+
contract_version: str,
|
|
299
|
+
) -> int:
|
|
135
300
|
captured_at = datetime.now(timezone.utc).replace(microsecond=0).isoformat()
|
|
136
|
-
|
|
137
|
-
|
|
301
|
+
doc_rows: list[tuple[Any, ...]] = []
|
|
302
|
+
section_rows: list[tuple[Any, ...]] = []
|
|
303
|
+
for relative, path in sources:
|
|
138
304
|
try:
|
|
139
305
|
content = path.read_text(encoding="utf-8")
|
|
140
306
|
except (OSError, UnicodeError):
|
|
@@ -143,47 +309,122 @@ def index_documents(root: Path, db: Path, *, project_id: str, version: str) -> d
|
|
|
143
309
|
continue
|
|
144
310
|
digest = hashlib.sha256(content.encode("utf-8")).hexdigest()
|
|
145
311
|
doc_id = f"{library_id}:{version}:{relative}"
|
|
146
|
-
|
|
147
|
-
doc_id, library_id, project_id,
|
|
148
|
-
content, digest, captured_at,
|
|
312
|
+
doc_rows.append((
|
|
313
|
+
doc_id, library_id, project_id, library_name, version, relative,
|
|
314
|
+
content, digest, captured_at, source_label, private_flag,
|
|
149
315
|
))
|
|
316
|
+
section_rows.extend(_split_markdown_sections(doc_id, library_id, content))
|
|
317
|
+
|
|
318
|
+
connection.executescript(
|
|
319
|
+
"""
|
|
320
|
+
DROP TABLE IF EXISTS documents_meta;
|
|
321
|
+
DROP TABLE IF EXISTS documents;
|
|
322
|
+
DROP TABLE IF EXISTS document_sections;
|
|
323
|
+
DROP TABLE IF EXISTS documents_fts;
|
|
324
|
+
DROP TABLE IF EXISTS sections_fts;
|
|
325
|
+
CREATE TABLE documents_meta (
|
|
326
|
+
key TEXT PRIMARY KEY,
|
|
327
|
+
value TEXT NOT NULL
|
|
328
|
+
);
|
|
329
|
+
CREATE TABLE documents (
|
|
330
|
+
doc_id TEXT PRIMARY KEY,
|
|
331
|
+
library_id TEXT NOT NULL,
|
|
332
|
+
project_id TEXT NOT NULL,
|
|
333
|
+
library_name TEXT NOT NULL,
|
|
334
|
+
version TEXT NOT NULL,
|
|
335
|
+
source_path TEXT NOT NULL,
|
|
336
|
+
content TEXT NOT NULL,
|
|
337
|
+
content_sha256 TEXT NOT NULL,
|
|
338
|
+
captured_at TEXT NOT NULL,
|
|
339
|
+
source_label TEXT NOT NULL,
|
|
340
|
+
private INTEGER NOT NULL CHECK(private IN (0, 1))
|
|
341
|
+
);
|
|
342
|
+
CREATE TABLE document_sections (
|
|
343
|
+
section_id TEXT PRIMARY KEY,
|
|
344
|
+
doc_id TEXT NOT NULL,
|
|
345
|
+
library_id TEXT NOT NULL,
|
|
346
|
+
heading TEXT NOT NULL,
|
|
347
|
+
heading_path TEXT NOT NULL,
|
|
348
|
+
level INTEGER NOT NULL,
|
|
349
|
+
char_start INTEGER NOT NULL,
|
|
350
|
+
char_end INTEGER NOT NULL,
|
|
351
|
+
content TEXT NOT NULL
|
|
352
|
+
);
|
|
353
|
+
CREATE VIRTUAL TABLE documents_fts USING fts5(
|
|
354
|
+
doc_id UNINDEXED, title, content, tokenize='trigram'
|
|
355
|
+
);
|
|
356
|
+
CREATE VIRTUAL TABLE sections_fts USING fts5(
|
|
357
|
+
section_id UNINDEXED, doc_id UNINDEXED, title, heading_path, content, tokenize='trigram'
|
|
358
|
+
);
|
|
359
|
+
"""
|
|
360
|
+
)
|
|
361
|
+
connection.executemany(
|
|
362
|
+
"INSERT INTO documents_meta VALUES (?, ?)",
|
|
363
|
+
[
|
|
364
|
+
("schema_version", SCHEMA_VERSION),
|
|
365
|
+
("contract_version", contract_version),
|
|
366
|
+
("built_at", captured_at),
|
|
367
|
+
("library_id", library_id),
|
|
368
|
+
],
|
|
369
|
+
)
|
|
370
|
+
connection.executemany(
|
|
371
|
+
"INSERT INTO documents VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
372
|
+
doc_rows,
|
|
373
|
+
)
|
|
374
|
+
connection.executemany(
|
|
375
|
+
"INSERT INTO document_sections VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
376
|
+
section_rows,
|
|
377
|
+
)
|
|
378
|
+
connection.executemany(
|
|
379
|
+
"INSERT INTO documents_fts(doc_id, title, content) VALUES (?, ?, ?)",
|
|
380
|
+
((row[0], str(row[5]).rsplit("/", 1)[-1], row[6]) for row in doc_rows),
|
|
381
|
+
)
|
|
382
|
+
doc_title_map = {row[0]: str(row[5]).rsplit("/", 1)[-1] for row in doc_rows}
|
|
383
|
+
connection.executemany(
|
|
384
|
+
"INSERT INTO sections_fts(section_id, doc_id, title, heading_path, content) VALUES (?, ?, ?, ?, ?)",
|
|
385
|
+
((s[0], s[1], doc_title_map.get(s[1], ""), s[4], s[8]) for s in section_rows),
|
|
386
|
+
)
|
|
387
|
+
connection.commit()
|
|
388
|
+
return len(doc_rows)
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def index_documents(root: Path, db: Path, *, project_id: str, version: str) -> dict[str, Any]:
|
|
392
|
+
root = root.expanduser().resolve()
|
|
393
|
+
if not root.is_dir():
|
|
394
|
+
raise DocsMcpError(f"项目根目录不是目录: {root}")
|
|
395
|
+
db = _db_path(root, db)
|
|
396
|
+
library_id = f"project:{project_id}"
|
|
397
|
+
contract_ver = _docs_sync.contract_version_of(BASE_VERSION)
|
|
398
|
+
sources = _project_source_files(root)
|
|
150
399
|
try:
|
|
151
|
-
with sqlite3.connect(db) as connection:
|
|
400
|
+
with sqlite3.connect(db, timeout=5.0) as connection:
|
|
401
|
+
connection.execute("PRAGMA busy_timeout=5000")
|
|
152
402
|
connection.execute("PRAGMA journal_mode=WAL")
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
source_path TEXT NOT NULL,
|
|
164
|
-
content TEXT NOT NULL,
|
|
165
|
-
content_sha256 TEXT NOT NULL,
|
|
166
|
-
captured_at TEXT NOT NULL,
|
|
167
|
-
source_label TEXT NOT NULL,
|
|
168
|
-
private INTEGER NOT NULL CHECK(private IN (0, 1))
|
|
169
|
-
);
|
|
170
|
-
CREATE VIRTUAL TABLE documents_fts USING fts5(
|
|
171
|
-
doc_id UNINDEXED, title, content
|
|
172
|
-
);
|
|
173
|
-
"""
|
|
174
|
-
)
|
|
175
|
-
connection.executemany(
|
|
176
|
-
"INSERT INTO documents VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
177
|
-
rows,
|
|
178
|
-
)
|
|
179
|
-
connection.executemany(
|
|
180
|
-
"INSERT INTO documents_fts(doc_id, title, content) VALUES (?, ?, ?)",
|
|
181
|
-
((row[0], str(row[5]).rsplit("/", 1)[-1], row[6]) for row in rows),
|
|
403
|
+
count = _populate_database(
|
|
404
|
+
connection,
|
|
405
|
+
sources=sources,
|
|
406
|
+
library_id=library_id,
|
|
407
|
+
project_id=project_id,
|
|
408
|
+
library_name="project-docs",
|
|
409
|
+
version=version,
|
|
410
|
+
source_label="BugX project documentation",
|
|
411
|
+
private_flag=1,
|
|
412
|
+
contract_version=contract_ver,
|
|
182
413
|
)
|
|
183
|
-
connection.commit()
|
|
184
414
|
except sqlite3.Error as exc:
|
|
185
415
|
raise DocsMcpError(f"文档数据库不可用: {exc}") from exc
|
|
186
|
-
return {"indexed":
|
|
416
|
+
return {"indexed": count, "db": str(db), "library_id": library_id, "version": version, "schema": SCHEMA_VERSION}
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _official_baseline_fingerprint(sources: list[tuple[str, Path]]) -> str:
|
|
420
|
+
h = hashlib.sha256()
|
|
421
|
+
for rel, path in sources:
|
|
422
|
+
try:
|
|
423
|
+
st = path.stat()
|
|
424
|
+
h.update(f"{rel}:{st.st_size}:{st.st_mtime_ns}\n".encode("utf-8"))
|
|
425
|
+
except OSError:
|
|
426
|
+
continue
|
|
427
|
+
return h.hexdigest()[:16]
|
|
187
428
|
|
|
188
429
|
|
|
189
430
|
def _open_readonly(db: Path) -> sqlite3.Connection:
|
|
@@ -198,6 +439,87 @@ def _open_readonly(db: Path) -> sqlite3.Connection:
|
|
|
198
439
|
raise DocsMcpError(f"文档索引无法只读打开: {exc}") from exc
|
|
199
440
|
|
|
200
441
|
|
|
442
|
+
def _is_v2_db(connection: sqlite3.Connection) -> bool:
|
|
443
|
+
try:
|
|
444
|
+
row = connection.execute(
|
|
445
|
+
"SELECT value FROM documents_meta WHERE key = 'schema_version'"
|
|
446
|
+
).fetchone()
|
|
447
|
+
return bool(row and row[0] == SCHEMA_VERSION)
|
|
448
|
+
except sqlite3.Error:
|
|
449
|
+
return False
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _open_official_connection(
|
|
453
|
+
*,
|
|
454
|
+
contract_version: str | None = None,
|
|
455
|
+
sync_if_missing: bool = False,
|
|
456
|
+
offline: bool = False,
|
|
457
|
+
remote_url: str | None = None,
|
|
458
|
+
) -> sqlite3.Connection | None:
|
|
459
|
+
"""打开 BugX 官方只读文档连接:云端不可变缓存 → 本地基线磁盘快照 → 内存库兜底 (NEG-03)。"""
|
|
460
|
+
ver = _docs_sync.contract_version_of(contract_version)
|
|
461
|
+
if sync_if_missing and not offline and not _docs_sync.docs_offline_disabled():
|
|
462
|
+
try:
|
|
463
|
+
_docs_sync.sync_official_docs(contract_version=ver, offline=offline, remote_url=remote_url)
|
|
464
|
+
except Exception:
|
|
465
|
+
pass
|
|
466
|
+
cached = _docs_sync.current_cached_db(ver)
|
|
467
|
+
if cached is not None:
|
|
468
|
+
try:
|
|
469
|
+
return _open_readonly(cached)
|
|
470
|
+
except DocsMcpError:
|
|
471
|
+
pass
|
|
472
|
+
|
|
473
|
+
sources = _official_source_files()
|
|
474
|
+
if not sources:
|
|
475
|
+
return None
|
|
476
|
+
fp = _official_baseline_fingerprint(sources)
|
|
477
|
+
try:
|
|
478
|
+
cdir = _docs_sync.docs_cache_dir(ver)
|
|
479
|
+
baseline_db = cdir / f"baseline-{fp}.sqlite3"
|
|
480
|
+
if _docs_sync.verify_sqlite_snapshot(baseline_db, ver):
|
|
481
|
+
return _open_readonly(baseline_db)
|
|
482
|
+
cdir.mkdir(parents=True, mode=0o700, exist_ok=True)
|
|
483
|
+
tmp_db = cdir / f".tmp-baseline-{os.getpid()}.sqlite3"
|
|
484
|
+
with sqlite3.connect(tmp_db) as conn:
|
|
485
|
+
_populate_database(
|
|
486
|
+
conn,
|
|
487
|
+
sources=sources,
|
|
488
|
+
library_id=OFFICIAL_LIBRARY_ID,
|
|
489
|
+
project_id=OFFICIAL_LIBRARY_ID,
|
|
490
|
+
library_name="bugx-official-docs",
|
|
491
|
+
version=ver,
|
|
492
|
+
source_label="BugX official documentation (bundled baseline)",
|
|
493
|
+
private_flag=0,
|
|
494
|
+
contract_version=ver,
|
|
495
|
+
)
|
|
496
|
+
os.replace(tmp_db, baseline_db)
|
|
497
|
+
# 清理旧版本 baseline 文件
|
|
498
|
+
for old in cdir.glob("baseline-*.sqlite3"):
|
|
499
|
+
if old.name != baseline_db.name:
|
|
500
|
+
try:
|
|
501
|
+
old.unlink()
|
|
502
|
+
except OSError:
|
|
503
|
+
pass
|
|
504
|
+
return _open_readonly(baseline_db)
|
|
505
|
+
except (OSError, sqlite3.Error, _docs_sync.DocsSyncError):
|
|
506
|
+
# NEG-03:只读文件系统容器兜底回落纯内存库
|
|
507
|
+
conn = sqlite3.connect(":memory:")
|
|
508
|
+
conn.row_factory = sqlite3.Row
|
|
509
|
+
_populate_database(
|
|
510
|
+
conn,
|
|
511
|
+
sources=sources,
|
|
512
|
+
library_id=OFFICIAL_LIBRARY_ID,
|
|
513
|
+
project_id=OFFICIAL_LIBRARY_ID,
|
|
514
|
+
library_name="bugx-official-docs",
|
|
515
|
+
version=ver,
|
|
516
|
+
source_label="BugX official documentation (in-memory)",
|
|
517
|
+
private_flag=0,
|
|
518
|
+
contract_version=ver,
|
|
519
|
+
)
|
|
520
|
+
return conn
|
|
521
|
+
|
|
522
|
+
|
|
201
523
|
def _authorize(arguments: Mapping[str, Any], project_id: str, expected_token: str | None) -> None:
|
|
202
524
|
supplied_project = str(arguments.get("project_id") or "").strip()
|
|
203
525
|
if supplied_project != project_id:
|
|
@@ -207,14 +529,112 @@ def _authorize(arguments: Mapping[str, Any], project_id: str, expected_token: st
|
|
|
207
529
|
raise DocsMcpError("文档 MCP token 无效")
|
|
208
530
|
|
|
209
531
|
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
532
|
+
_STOP_WORDS_CN = {
|
|
533
|
+
"怎么", "如何", "怎样", "请问", "我想", "要", "请教", "帮我", "关于", "对于", "进行",
|
|
534
|
+
"排查", "查看", "一下", "一个", "我们", "你们", "什么", "为什么", "在哪里", "哪个",
|
|
535
|
+
"命令", "方法", "步骤", "规范", "操作", "手册", "指南", "指引", "说明"
|
|
536
|
+
}
|
|
537
|
+
_STOP_WORDS_EN_PATTERN = re.compile(
|
|
538
|
+
r"\b(how|to|what|is|the|a|an|in|on|for|with|about|can|i|do|does|did|please|help|me|my)\b",
|
|
539
|
+
re.IGNORECASE,
|
|
540
|
+
)
|
|
541
|
+
_CN_STOP_PATTERN = re.compile(
|
|
542
|
+
r"|".join(re.escape(w) for w in sorted(_STOP_WORDS_CN, key=len, reverse=True))
|
|
543
|
+
)
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def _extract_search_terms(query: str) -> tuple[list[str], list[str]]:
|
|
547
|
+
"""从自然语言查询中提取检索词:(fts_terms >=3 chars, sub_terms >=2 chars)。"""
|
|
548
|
+
text = str(query or "").strip()
|
|
549
|
+
if not text:
|
|
550
|
+
return [], []
|
|
551
|
+
cleaned = _STOP_WORDS_EN_PATTERN.sub(" ", text)
|
|
552
|
+
cleaned = _CN_STOP_PATTERN.sub(" ", cleaned)
|
|
553
|
+
chunks = re.findall(r"[\u4e00-\u9fff]+|[a-zA-Z0-9_.-]+", cleaned)
|
|
554
|
+
fts_terms: list[str] = []
|
|
555
|
+
sub_terms: list[str] = []
|
|
556
|
+
seen_sub: set[str] = set()
|
|
557
|
+
|
|
558
|
+
def _add_sub(term: str) -> None:
|
|
559
|
+
t = term.strip().lower()
|
|
560
|
+
if len(t) >= 2 and t not in seen_sub:
|
|
561
|
+
seen_sub.add(t)
|
|
562
|
+
sub_terms.append(t)
|
|
563
|
+
|
|
564
|
+
def _add_fts(term: str) -> None:
|
|
565
|
+
t = term.strip()
|
|
566
|
+
if len(t) >= 3 and t not in fts_terms:
|
|
567
|
+
fts_terms.append(t)
|
|
568
|
+
|
|
569
|
+
for chunk in chunks:
|
|
570
|
+
if re.match(r"^[\u4e00-\u9fff]+$", chunk):
|
|
571
|
+
if len(chunk) >= 3:
|
|
572
|
+
_add_fts(chunk)
|
|
573
|
+
if len(chunk) == 2:
|
|
574
|
+
_add_sub(chunk)
|
|
575
|
+
elif len(chunk) == 3:
|
|
576
|
+
_add_sub(chunk)
|
|
577
|
+
_add_sub(chunk[:2])
|
|
578
|
+
_add_sub(chunk[1:])
|
|
579
|
+
elif len(chunk) == 4:
|
|
580
|
+
_add_sub(chunk[:2])
|
|
581
|
+
_add_sub(chunk[2:])
|
|
582
|
+
else:
|
|
583
|
+
for i in range(0, len(chunk) - 1, 2):
|
|
584
|
+
_add_sub(chunk[i:i+2])
|
|
585
|
+
else:
|
|
586
|
+
_add_sub(chunk)
|
|
587
|
+
if len(chunk) >= 3:
|
|
588
|
+
_add_fts(chunk)
|
|
589
|
+
|
|
590
|
+
if not sub_terms:
|
|
591
|
+
raw_chunks = re.findall(r"[\w.-]+", text, flags=re.UNICODE)
|
|
592
|
+
for rc in raw_chunks:
|
|
593
|
+
_add_sub(rc)
|
|
594
|
+
if len(rc) >= 3:
|
|
595
|
+
_add_fts(rc)
|
|
596
|
+
|
|
597
|
+
return fts_terms, sub_terms
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
def _extract_snippet(content: str, terms: list[str], max_chars: int = 1200) -> str:
|
|
601
|
+
"""提取关键词高频命中窗口,避免截取前缀导致丢失真正答案。"""
|
|
602
|
+
if not content:
|
|
603
|
+
return ""
|
|
604
|
+
if not terms or len(content) <= max_chars:
|
|
605
|
+
snippet = content[:max_chars].strip()
|
|
606
|
+
return snippet + " ..." if len(content) > max_chars else snippet
|
|
607
|
+
|
|
608
|
+
term_matches: list[int] = []
|
|
609
|
+
for term in terms:
|
|
610
|
+
for m in re.finditer(re.escape(term), content, re.IGNORECASE):
|
|
611
|
+
term_matches.append(m.start())
|
|
612
|
+
|
|
613
|
+
if not term_matches:
|
|
614
|
+
snippet = content[:max_chars].strip()
|
|
615
|
+
return snippet + " ..." if len(content) > max_chars else snippet
|
|
616
|
+
|
|
617
|
+
term_matches.sort()
|
|
618
|
+
best_start = 0
|
|
619
|
+
best_score = -1
|
|
620
|
+
for idx in term_matches:
|
|
621
|
+
w_start = max(0, idx - 150)
|
|
622
|
+
w_end = min(len(content), w_start + max_chars)
|
|
623
|
+
window = content[w_start:w_end]
|
|
624
|
+
cnt = sum(1 for t in terms if t.lower() in window.lower())
|
|
625
|
+
total_occ = sum(len(re.findall(re.escape(t), window, re.IGNORECASE)) for t in terms)
|
|
626
|
+
score = cnt * 10 + total_occ
|
|
627
|
+
if score > best_score:
|
|
628
|
+
best_score = score
|
|
629
|
+
best_start = w_start
|
|
630
|
+
|
|
631
|
+
end = min(len(content), best_start + max_chars)
|
|
632
|
+
snippet = content[best_start:end].strip()
|
|
633
|
+
if best_start > 0:
|
|
634
|
+
snippet = "... " + snippet
|
|
635
|
+
if end < len(content):
|
|
636
|
+
snippet = snippet + " ..."
|
|
637
|
+
return snippet
|
|
218
638
|
|
|
219
639
|
|
|
220
640
|
def _bounded(text: str, limit: int = MAX_RESULT_BYTES) -> str:
|
|
@@ -222,72 +642,429 @@ def _bounded(text: str, limit: int = MAX_RESULT_BYTES) -> str:
|
|
|
222
642
|
return raw[:limit].decode("utf-8", errors="ignore")
|
|
223
643
|
|
|
224
644
|
|
|
225
|
-
def
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
645
|
+
def _search_single_connection(
|
|
646
|
+
connection: sqlite3.Connection,
|
|
647
|
+
*,
|
|
648
|
+
scope_project_id: str,
|
|
649
|
+
library_id: str,
|
|
650
|
+
version: str | None,
|
|
651
|
+
query_str: str,
|
|
652
|
+
fts_terms: list[str],
|
|
653
|
+
sub_terms: list[str],
|
|
654
|
+
limit: int,
|
|
655
|
+
) -> list[dict[str, Any]]:
|
|
656
|
+
if scope_project_id == OFFICIAL_LIBRARY_ID:
|
|
657
|
+
scope_clause = "d.library_id = ? AND d.private = 0"
|
|
658
|
+
base_params: list[Any] = [library_id]
|
|
659
|
+
else:
|
|
660
|
+
scope_clause = "d.project_id = ? AND d.library_id = ?"
|
|
661
|
+
base_params = [scope_project_id, library_id]
|
|
662
|
+
version_clause = " AND d.version = ?" if version is not None else ""
|
|
663
|
+
if version is not None:
|
|
664
|
+
base_params.append(str(version))
|
|
665
|
+
|
|
666
|
+
use_sections = _is_v2_db(connection)
|
|
667
|
+
candidates_by_key: dict[str, dict[str, Any]] = {}
|
|
668
|
+
|
|
669
|
+
if use_sections:
|
|
670
|
+
if fts_terms:
|
|
671
|
+
fts_exprs = [" AND ".join('"' + t.replace('"', '""') + '"' for t in fts_terms[:8])]
|
|
672
|
+
if len(fts_terms) > 1:
|
|
673
|
+
fts_exprs.append(" OR ".join('"' + t.replace('"', '""') + '"' for t in fts_terms[:8]))
|
|
674
|
+
for fts_expr in fts_exprs:
|
|
675
|
+
try:
|
|
676
|
+
res = connection.execute(
|
|
677
|
+
"SELECT d.*, s.section_id, s.heading, s.heading_path, s.content AS sec_content "
|
|
678
|
+
"FROM document_sections s "
|
|
679
|
+
"JOIN documents d ON d.doc_id = s.doc_id "
|
|
680
|
+
"JOIN sections_fts f ON f.section_id = s.section_id "
|
|
681
|
+
"WHERE " + scope_clause + version_clause +
|
|
682
|
+
" AND f.sections_fts MATCH ? ORDER BY f.rank ASC LIMIT 24",
|
|
683
|
+
list(base_params) + [fts_expr],
|
|
684
|
+
).fetchall()
|
|
685
|
+
for r in res:
|
|
686
|
+
candidates_by_key[r["section_id"]] = dict(r)
|
|
687
|
+
if len(candidates_by_key) >= limit * 2:
|
|
688
|
+
break
|
|
689
|
+
except sqlite3.OperationalError:
|
|
690
|
+
continue
|
|
691
|
+
|
|
692
|
+
if len(candidates_by_key) < limit * 2 and sub_terms:
|
|
693
|
+
and_clauses = ["(s.content LIKE ? OR s.heading_path LIKE ? OR d.source_path LIKE ?)" for _ in sub_terms[:5]]
|
|
694
|
+
and_params = list(base_params)
|
|
695
|
+
for t in sub_terms[:5]:
|
|
696
|
+
pat = f"%{t}%"
|
|
697
|
+
and_params.extend([pat, pat, pat])
|
|
698
|
+
res = connection.execute(
|
|
699
|
+
"SELECT d.*, s.section_id, s.heading, s.heading_path, s.content AS sec_content "
|
|
700
|
+
"FROM document_sections s JOIN documents d ON d.doc_id = s.doc_id "
|
|
701
|
+
"WHERE " + scope_clause + version_clause +
|
|
702
|
+
" AND " + " AND ".join(and_clauses) + " LIMIT 24",
|
|
703
|
+
and_params,
|
|
704
|
+
).fetchall()
|
|
705
|
+
for r in res:
|
|
706
|
+
candidates_by_key[r["section_id"]] = dict(r)
|
|
707
|
+
|
|
708
|
+
if not candidates_by_key and sub_terms:
|
|
709
|
+
or_clauses = ["(s.content LIKE ? OR s.heading_path LIKE ? OR d.source_path LIKE ?)" for _ in sub_terms[:5]]
|
|
710
|
+
or_params = list(base_params)
|
|
711
|
+
for t in sub_terms[:5]:
|
|
712
|
+
pat = f"%{t}%"
|
|
713
|
+
or_params.extend([pat, pat, pat])
|
|
714
|
+
res = connection.execute(
|
|
715
|
+
"SELECT d.*, s.section_id, s.heading, s.heading_path, s.content AS sec_content "
|
|
716
|
+
"FROM document_sections s JOIN documents d ON d.doc_id = s.doc_id "
|
|
717
|
+
"WHERE " + scope_clause + version_clause +
|
|
718
|
+
" AND (" + " OR ".join(or_clauses) + ") LIMIT 30",
|
|
719
|
+
or_params,
|
|
720
|
+
).fetchall()
|
|
721
|
+
for r in res:
|
|
722
|
+
candidates_by_key[r["section_id"]] = dict(r)
|
|
723
|
+
else:
|
|
724
|
+
# 兼容极早期无 document_sections 结构的旧索引读取
|
|
725
|
+
if sub_terms:
|
|
726
|
+
and_clauses = ["(d.content LIKE ? OR d.source_path LIKE ?)" for _ in sub_terms[:5]]
|
|
727
|
+
and_params = list(base_params)
|
|
728
|
+
for t in sub_terms[:5]:
|
|
729
|
+
pat = f"%{t}%"
|
|
730
|
+
and_params.extend([pat, pat])
|
|
731
|
+
res = connection.execute(
|
|
732
|
+
"SELECT d.* FROM documents d WHERE " + scope_clause +
|
|
733
|
+
version_clause + " AND " + " AND ".join(and_clauses) + " LIMIT 20",
|
|
734
|
+
and_params,
|
|
262
735
|
).fetchall()
|
|
736
|
+
for r in res:
|
|
737
|
+
row_d = dict(r)
|
|
738
|
+
row_d["section_id"] = row_d["doc_id"]
|
|
739
|
+
row_d["heading"] = ""
|
|
740
|
+
row_d["heading_path"] = ""
|
|
741
|
+
row_d["sec_content"] = row_d["content"]
|
|
742
|
+
candidates_by_key[row_d["doc_id"]] = row_d
|
|
743
|
+
|
|
744
|
+
results: list[dict[str, Any]] = []
|
|
745
|
+
for row in candidates_by_key.values():
|
|
746
|
+
path = str(row["source_path"])
|
|
747
|
+
title = path.rsplit("/", 1)[-1].lower()
|
|
748
|
+
hpath = str(row.get("heading_path") or "").lower()
|
|
749
|
+
sec_text = str(row.get("sec_content") or row["content"])
|
|
750
|
+
sec_lower = sec_text.lower()
|
|
751
|
+
|
|
752
|
+
hits = sum(1 for t in sub_terms if t in sec_lower or t in hpath or t in title)
|
|
753
|
+
if not hits and sub_terms:
|
|
754
|
+
continue
|
|
755
|
+
score = hits * 10.0
|
|
756
|
+
if hits == len(sub_terms) and len(sub_terms) > 1:
|
|
757
|
+
score += 25.0
|
|
758
|
+
if any(t in hpath for t in sub_terms):
|
|
759
|
+
score += 18.0
|
|
760
|
+
if any(t in title for t in sub_terms):
|
|
761
|
+
score += 12.0
|
|
762
|
+
score += _doc_tier(path, library_id) * 4.0
|
|
763
|
+
|
|
764
|
+
results.append({
|
|
765
|
+
**_citation(row),
|
|
766
|
+
"section": row.get("heading") or "",
|
|
767
|
+
"heading_path": row.get("heading_path") or "",
|
|
768
|
+
"snippet": _extract_snippet(sec_text, sub_terms, 1200),
|
|
769
|
+
"_score": score,
|
|
770
|
+
})
|
|
771
|
+
return results
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
def _normalize_heading_key(text: str) -> str:
|
|
775
|
+
stripped = re.sub(r"^[\d.]+\s*", "", text.strip())
|
|
776
|
+
return re.sub(r"\s+", " ", stripped).lower()
|
|
777
|
+
|
|
778
|
+
|
|
779
|
+
def call_tool(
|
|
780
|
+
db: Path,
|
|
781
|
+
name: str,
|
|
782
|
+
arguments: Mapping[str, Any],
|
|
783
|
+
*,
|
|
784
|
+
project_id: str,
|
|
785
|
+
expected_token: str | None,
|
|
786
|
+
mode: str = "hybrid",
|
|
787
|
+
remote_url: str | None = None,
|
|
788
|
+
) -> dict[str, Any]:
|
|
789
|
+
_authorize(arguments, project_id, expected_token)
|
|
790
|
+
contract_ver = _docs_sync.contract_version_of(BASE_VERSION)
|
|
791
|
+
|
|
792
|
+
if name == "resolve_library":
|
|
793
|
+
query = str(arguments.get("name") or "").strip()
|
|
794
|
+
if not query or len(query) > 128:
|
|
795
|
+
raise DocsMcpError("library name 无效")
|
|
796
|
+
q_low = query.lower()
|
|
797
|
+
if q_low in {OFFICIAL_LIBRARY_ID, "bugx", "official", "bugx-official-docs"}:
|
|
263
798
|
return {
|
|
264
|
-
"
|
|
265
|
-
"
|
|
799
|
+
"library_id": OFFICIAL_LIBRARY_ID,
|
|
800
|
+
"library_name": "bugx-official-docs",
|
|
801
|
+
"version": contract_ver,
|
|
802
|
+
"project_id": OFFICIAL_LIBRARY_ID,
|
|
266
803
|
}
|
|
267
|
-
if
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
804
|
+
if db.is_file() and not db.is_symlink():
|
|
805
|
+
with _open_readonly(db) as connection:
|
|
806
|
+
row = connection.execute(
|
|
807
|
+
"SELECT DISTINCT library_id, library_name, version, project_id "
|
|
808
|
+
"FROM documents WHERE project_id = ? AND (library_id = ? OR library_name LIKE ?) "
|
|
809
|
+
"ORDER BY version DESC LIMIT 1",
|
|
810
|
+
(project_id, query, f"%{query}%"),
|
|
811
|
+
).fetchone()
|
|
812
|
+
if row is not None:
|
|
813
|
+
return dict(row)
|
|
814
|
+
raise DocsMcpError("未找到受控文档库")
|
|
815
|
+
|
|
816
|
+
if name == "search_docs":
|
|
817
|
+
raw_lib = str(arguments.get("library_id") or "").strip()
|
|
818
|
+
library_id = raw_lib or "all"
|
|
819
|
+
version = arguments.get("version")
|
|
820
|
+
try:
|
|
821
|
+
limit = int(arguments.get("limit", 5))
|
|
822
|
+
except (TypeError, ValueError) as exc:
|
|
823
|
+
raise DocsMcpError("limit 必须是整数") from exc
|
|
824
|
+
if not 1 <= limit <= 20:
|
|
825
|
+
raise DocsMcpError("limit 必须在 1 到 20 之间")
|
|
826
|
+
query_str = str(arguments.get("query") or "").strip()
|
|
827
|
+
if not query_str or len(query_str) > 512:
|
|
828
|
+
raise DocsMcpError("query 不能为空且不得超过 512 字符")
|
|
829
|
+
|
|
830
|
+
fts_terms, sub_terms = _extract_search_terms(query_str)
|
|
831
|
+
all_hits: list[dict[str, Any]] = []
|
|
832
|
+
search_project = library_id.lower() in {"all", "*", f"project:{project_id}".lower()}
|
|
833
|
+
search_official = library_id.lower() in {"all", "*", OFFICIAL_LIBRARY_ID}
|
|
834
|
+
|
|
835
|
+
if search_project and db.is_file() and not db.is_symlink():
|
|
836
|
+
try:
|
|
837
|
+
with _open_readonly(db) as proj_conn:
|
|
838
|
+
all_hits.extend(_search_single_connection(
|
|
839
|
+
proj_conn,
|
|
840
|
+
scope_project_id=project_id,
|
|
841
|
+
library_id=f"project:{project_id}",
|
|
842
|
+
version=str(version) if version is not None else None,
|
|
843
|
+
query_str=query_str,
|
|
844
|
+
fts_terms=fts_terms,
|
|
845
|
+
sub_terms=sub_terms,
|
|
846
|
+
limit=limit,
|
|
847
|
+
))
|
|
848
|
+
except DocsMcpError:
|
|
849
|
+
pass
|
|
850
|
+
|
|
851
|
+
if search_official:
|
|
852
|
+
remote_done = False
|
|
853
|
+
if mode != "local-only" and not _docs_sync.docs_offline_disabled():
|
|
854
|
+
try:
|
|
855
|
+
remote_res = _docs_sync.remote_search_docs(
|
|
856
|
+
query_str, contract_version=contract_ver, limit=limit, remote_url=remote_url,
|
|
857
|
+
)
|
|
858
|
+
for idx, item in enumerate(remote_res.get("results") or []):
|
|
859
|
+
if isinstance(item, dict):
|
|
860
|
+
all_hits.append({**item, "_score": float(100 - idx)})
|
|
861
|
+
remote_done = True
|
|
862
|
+
except Exception:
|
|
863
|
+
if mode == "remote-only":
|
|
864
|
+
raise
|
|
865
|
+
remote_done = False
|
|
866
|
+
|
|
867
|
+
if not remote_done:
|
|
868
|
+
off_conn = _open_official_connection(
|
|
869
|
+
contract_version=contract_ver,
|
|
870
|
+
sync_if_missing=False,
|
|
871
|
+
offline=(mode == "local-only"),
|
|
872
|
+
remote_url=remote_url,
|
|
873
|
+
)
|
|
874
|
+
if off_conn is not None:
|
|
875
|
+
try:
|
|
876
|
+
all_hits.extend(_search_single_connection(
|
|
877
|
+
off_conn,
|
|
878
|
+
scope_project_id=OFFICIAL_LIBRARY_ID,
|
|
879
|
+
library_id=OFFICIAL_LIBRARY_ID,
|
|
880
|
+
version=None,
|
|
881
|
+
query_str=query_str,
|
|
882
|
+
fts_terms=fts_terms,
|
|
883
|
+
sub_terms=sub_terms,
|
|
884
|
+
limit=limit,
|
|
885
|
+
))
|
|
886
|
+
finally:
|
|
887
|
+
off_conn.close()
|
|
888
|
+
|
|
889
|
+
# 若 library_id 为自定义作用域且未命中以上两者,直接在 db 中尝试精确匹配
|
|
890
|
+
if not search_project and not search_official and db.is_file() and not db.is_symlink():
|
|
891
|
+
with _open_readonly(db) as custom_conn:
|
|
892
|
+
all_hits.extend(_search_single_connection(
|
|
893
|
+
custom_conn,
|
|
894
|
+
scope_project_id=project_id,
|
|
895
|
+
library_id=library_id,
|
|
896
|
+
version=str(version) if version is not None else None,
|
|
897
|
+
query_str=query_str,
|
|
898
|
+
fts_terms=fts_terms,
|
|
899
|
+
sub_terms=sub_terms,
|
|
900
|
+
limit=limit,
|
|
901
|
+
))
|
|
902
|
+
|
|
903
|
+
all_hits.sort(key=lambda item: float(item.get("_score", 0.0)), reverse=True)
|
|
904
|
+
# 按 (内容哈希 + 章节名称) 去重,避免官方文档与 dev 仓内同类文档重复占用名额
|
|
905
|
+
deduped: list[dict[str, Any]] = []
|
|
906
|
+
seen_sig: set[tuple[str, str]] = set()
|
|
907
|
+
for item in all_hits:
|
|
908
|
+
sig = (str(item.get("sha256") or ""), str(item.get("section") or ""))
|
|
909
|
+
if sig in seen_sig:
|
|
910
|
+
continue
|
|
911
|
+
seen_sig.add(sig)
|
|
912
|
+
clean = {k: v for k, v in item.items() if k != "_score"}
|
|
913
|
+
deduped.append(clean)
|
|
914
|
+
if len(deduped) >= limit:
|
|
915
|
+
break
|
|
916
|
+
|
|
917
|
+
return {"results": deduped, "count": len(deduped)}
|
|
918
|
+
|
|
919
|
+
if name == "list_sections":
|
|
920
|
+
document_id = str(arguments.get("document_id") or "").strip()
|
|
921
|
+
if not document_id:
|
|
922
|
+
raise DocsMcpError("document_id 不能为空")
|
|
923
|
+
row, sec_rows = _find_doc_and_sections(
|
|
924
|
+
db, document_id=document_id, project_id=project_id, contract_ver=contract_ver, mode=mode,
|
|
925
|
+
)
|
|
926
|
+
return {
|
|
927
|
+
**_citation(row),
|
|
928
|
+
"sections": [
|
|
929
|
+
{
|
|
930
|
+
"section": s["heading"],
|
|
931
|
+
"heading_path": s["heading_path"],
|
|
932
|
+
"level": s["level"],
|
|
933
|
+
"char_count": max(0, int(s["char_end"]) - int(s["char_start"])),
|
|
934
|
+
}
|
|
935
|
+
for s in sec_rows
|
|
936
|
+
],
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
if name == "fetch_doc":
|
|
940
|
+
document_id = str(arguments.get("document_id") or "").strip()
|
|
941
|
+
section = str(arguments.get("section") or "").strip()
|
|
942
|
+
if document_id.startswith(f"{OFFICIAL_LIBRARY_ID}:") and mode != "local-only" and not _docs_sync.docs_offline_disabled():
|
|
943
|
+
try:
|
|
944
|
+
return _docs_sync.remote_fetch_doc(
|
|
945
|
+
document_id, contract_version=contract_ver, section=section, remote_url=remote_url,
|
|
946
|
+
)
|
|
947
|
+
except Exception:
|
|
948
|
+
if mode == "remote-only":
|
|
949
|
+
raise
|
|
950
|
+
# 远程读取失败,无感降级到本地 SQLite 兜底
|
|
951
|
+
pass
|
|
952
|
+
row, sec_rows = _find_doc_and_sections(
|
|
953
|
+
db, document_id=document_id, project_id=project_id, contract_ver=contract_ver, mode=mode,
|
|
954
|
+
)
|
|
955
|
+
content = str(row["content"])
|
|
956
|
+
if section:
|
|
957
|
+
content = _extract_exact_section(content, sec_rows, section)
|
|
958
|
+
return {
|
|
959
|
+
**_citation(row),
|
|
960
|
+
"content": _bounded(content),
|
|
961
|
+
"available_sections": [s["heading"] for s in sec_rows[:25]],
|
|
962
|
+
}
|
|
963
|
+
|
|
284
964
|
raise DocsMcpError(f"未知文档工具: {name}")
|
|
285
965
|
|
|
286
966
|
|
|
967
|
+
def _find_doc_and_sections(
|
|
968
|
+
db: Path,
|
|
969
|
+
*,
|
|
970
|
+
document_id: str,
|
|
971
|
+
project_id: str,
|
|
972
|
+
contract_ver: str,
|
|
973
|
+
mode: str,
|
|
974
|
+
) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
|
975
|
+
def _query_one(conn: sqlite3.Connection, scope_pid: str) -> tuple[dict[str, Any], list[dict[str, Any]]] | None:
|
|
976
|
+
row = conn.execute(
|
|
977
|
+
"SELECT * FROM documents WHERE doc_id = ? AND project_id = ?",
|
|
978
|
+
(document_id, scope_pid),
|
|
979
|
+
).fetchone()
|
|
980
|
+
if row is None:
|
|
981
|
+
return None
|
|
982
|
+
secs: list[dict[str, Any]] = []
|
|
983
|
+
if _is_v2_db(conn):
|
|
984
|
+
secs = [
|
|
985
|
+
dict(s)
|
|
986
|
+
for s in conn.execute(
|
|
987
|
+
"SELECT * FROM document_sections WHERE doc_id = ? ORDER BY rowid ASC",
|
|
988
|
+
(document_id,),
|
|
989
|
+
).fetchall()
|
|
990
|
+
]
|
|
991
|
+
return dict(row), secs
|
|
992
|
+
|
|
993
|
+
if document_id.startswith(f"{OFFICIAL_LIBRARY_ID}:"):
|
|
994
|
+
off_conn = _open_official_connection(
|
|
995
|
+
contract_version=contract_ver, sync_if_missing=False, offline=(mode == "local-only"),
|
|
996
|
+
)
|
|
997
|
+
if off_conn is not None:
|
|
998
|
+
try:
|
|
999
|
+
found = _query_one(off_conn, OFFICIAL_LIBRARY_ID)
|
|
1000
|
+
if found is not None:
|
|
1001
|
+
return found
|
|
1002
|
+
finally:
|
|
1003
|
+
off_conn.close()
|
|
1004
|
+
|
|
1005
|
+
if db.is_file() and not db.is_symlink():
|
|
1006
|
+
with _open_readonly(db) as proj_conn:
|
|
1007
|
+
found = _query_one(proj_conn, project_id)
|
|
1008
|
+
if found is not None:
|
|
1009
|
+
return found
|
|
1010
|
+
|
|
1011
|
+
if not document_id.startswith(f"{OFFICIAL_LIBRARY_ID}:"):
|
|
1012
|
+
off_conn = _open_official_connection(
|
|
1013
|
+
contract_version=contract_ver, sync_if_missing=False, offline=(mode == "local-only"),
|
|
1014
|
+
)
|
|
1015
|
+
if off_conn is not None:
|
|
1016
|
+
try:
|
|
1017
|
+
found = _query_one(off_conn, OFFICIAL_LIBRARY_ID)
|
|
1018
|
+
if found is not None:
|
|
1019
|
+
return found
|
|
1020
|
+
finally:
|
|
1021
|
+
off_conn.close()
|
|
1022
|
+
|
|
1023
|
+
raise DocsMcpError("document_id 不存在或不属于当前项目")
|
|
1024
|
+
|
|
1025
|
+
|
|
1026
|
+
def _extract_exact_section(content: str, sec_rows: list[dict[str, Any]], section: str) -> str:
|
|
1027
|
+
"""精确或唯一子串匹配标题并切片到下一个同级或更高级标题;未命中或歧义时 fail-closed 返回可用目录。"""
|
|
1028
|
+
target_low = section.strip().lower()
|
|
1029
|
+
target_norm = _normalize_heading_key(section)
|
|
1030
|
+
usable = [s for s in sec_rows if s["heading"] not in {"(document)", "(preamble)"} and "(part " not in s["heading"]]
|
|
1031
|
+
|
|
1032
|
+
if usable:
|
|
1033
|
+
# 1. 精确匹配(忽略大小写)
|
|
1034
|
+
exact = [s for s in usable if s["heading"].strip().lower() == target_low]
|
|
1035
|
+
if len(exact) == 1:
|
|
1036
|
+
return content[int(exact[0]["char_start"]):int(exact[0]["char_end"])].strip()
|
|
1037
|
+
# 2. 去编号规范化精确匹配(如 '8.5 auth' vs 'auth')
|
|
1038
|
+
norm_hits = [s for s in usable if _normalize_heading_key(s["heading"]) == target_norm]
|
|
1039
|
+
if len(norm_hits) == 1:
|
|
1040
|
+
return content[int(norm_hits[0]["char_start"]):int(norm_hits[0]["char_end"])].strip()
|
|
1041
|
+
# 3. 唯一子串匹配
|
|
1042
|
+
sub_hits = [
|
|
1043
|
+
s for s in usable
|
|
1044
|
+
if target_low in s["heading"].lower() or (target_norm and target_norm in _normalize_heading_key(s["heading"]))
|
|
1045
|
+
]
|
|
1046
|
+
if len(sub_hits) == 1:
|
|
1047
|
+
return content[int(sub_hits[0]["char_start"]):int(sub_hits[0]["char_end"])].strip()
|
|
1048
|
+
if len(sub_hits) > 1:
|
|
1049
|
+
cands = ", ".join(s["heading"] for s in sub_hits[:10])
|
|
1050
|
+
raise DocsMcpError(f"section 匹配存在多处歧义 ({section!r}),请传入更精确标题,候选: [{cands}]")
|
|
1051
|
+
toc = ", ".join(s["heading"] for s in usable[:20])
|
|
1052
|
+
raise DocsMcpError(f"未找到章节 {section!r};可用章节列表: [{toc}]")
|
|
1053
|
+
|
|
1054
|
+
# 极旧单表无 section 索引时的回落边界修复(fenced-code-safe + 同级停止)
|
|
1055
|
+
match = re.search(rf"(?im)^(#+)\s*{re.escape(section)}\s*$", content)
|
|
1056
|
+
if not match:
|
|
1057
|
+
raise DocsMcpError(f"未找到章节 {section!r}")
|
|
1058
|
+
lvl = len(match.group(1))
|
|
1059
|
+
tail = content[match.end():]
|
|
1060
|
+
next_heading = re.search(rf"(?m)^#{{1,{lvl}}}\s+", tail)
|
|
1061
|
+
return (match.group(0) + (tail[:next_heading.start()] if next_heading else tail)).strip()
|
|
1062
|
+
|
|
1063
|
+
|
|
287
1064
|
TOOLS = [
|
|
288
1065
|
{
|
|
289
1066
|
"name": "resolve_library",
|
|
290
|
-
"description": "
|
|
1067
|
+
"description": "解析当前项目或 BugX 官方受控文档库 (`bugx:official` / `project:<id>`);结果只来自本地安全索引。",
|
|
291
1068
|
"inputSchema": {"type": "object", "required": ["name", "project_id"], "properties": {
|
|
292
1069
|
"name": {"type": "string", "maxLength": 128},
|
|
293
1070
|
"project_id": {"type": "string"}, "token": {"type": "string"},
|
|
@@ -295,7 +1072,7 @@ TOOLS = [
|
|
|
295
1072
|
},
|
|
296
1073
|
{
|
|
297
1074
|
"name": "search_docs",
|
|
298
|
-
"description": "
|
|
1075
|
+
"description": "在当前项目与 BugX 官方受控文档库的章节级索引中检索并返回可引用证据 (`library_id='all'|'bugx:official'|'project:<id>')。",
|
|
299
1076
|
"inputSchema": {"type": "object", "required": ["query", "project_id"], "properties": {
|
|
300
1077
|
"library_id": {"type": "string"}, "query": {"type": "string", "maxLength": 512},
|
|
301
1078
|
"version": {"type": "string"}, "limit": {"type": "integer", "minimum": 1, "maximum": 20},
|
|
@@ -304,12 +1081,20 @@ TOOLS = [
|
|
|
304
1081
|
},
|
|
305
1082
|
{
|
|
306
1083
|
"name": "fetch_doc",
|
|
307
|
-
"description": "
|
|
1084
|
+
"description": "读取一份受控文档或其中精确章节(支持去编号标题与子小节完整边界),并返回版本、哈希和来源引用。",
|
|
308
1085
|
"inputSchema": {"type": "object", "required": ["document_id", "project_id"], "properties": {
|
|
309
1086
|
"document_id": {"type": "string"}, "section": {"type": "string"},
|
|
310
1087
|
"project_id": {"type": "string"}, "token": {"type": "string"},
|
|
311
1088
|
}},
|
|
312
1089
|
},
|
|
1090
|
+
{
|
|
1091
|
+
"name": "list_sections",
|
|
1092
|
+
"description": "列出指定文档的完整 Markdown 标题结构目录 (TOC) 与字符预算,便于精准拉取章节。",
|
|
1093
|
+
"inputSchema": {"type": "object", "required": ["document_id", "project_id"], "properties": {
|
|
1094
|
+
"document_id": {"type": "string"},
|
|
1095
|
+
"project_id": {"type": "string"}, "token": {"type": "string"},
|
|
1096
|
+
}},
|
|
1097
|
+
},
|
|
313
1098
|
]
|
|
314
1099
|
|
|
315
1100
|
|
|
@@ -323,15 +1108,30 @@ def _error(request_id: Any, code: int, message: str) -> dict[str, Any]:
|
|
|
323
1108
|
"error": {"code": code, "message": message}}
|
|
324
1109
|
|
|
325
1110
|
|
|
326
|
-
def serve(
|
|
327
|
-
|
|
1111
|
+
def serve(
|
|
1112
|
+
root: Path,
|
|
1113
|
+
db: Path,
|
|
1114
|
+
*,
|
|
1115
|
+
project_id: str,
|
|
1116
|
+
version: str,
|
|
1117
|
+
token: str | None = None,
|
|
1118
|
+
auto_index: bool = True,
|
|
1119
|
+
mode: str = "hybrid",
|
|
1120
|
+
remote_url: str | None = None,
|
|
1121
|
+
) -> int:
|
|
328
1122
|
root = root.expanduser().resolve()
|
|
329
1123
|
db = _db_path(root, db)
|
|
330
1124
|
if auto_index:
|
|
331
1125
|
index_documents(root, db, project_id=project_id, version=version)
|
|
1126
|
+
if mode != "local-only" and not _docs_sync.docs_offline_disabled():
|
|
1127
|
+
try:
|
|
1128
|
+
_docs_sync.sync_official_docs(
|
|
1129
|
+
contract_version=_docs_sync.contract_version_of(BASE_VERSION),
|
|
1130
|
+
remote_url=remote_url,
|
|
1131
|
+
)
|
|
1132
|
+
except Exception:
|
|
1133
|
+
pass
|
|
332
1134
|
expected_token = token or os.environ.get("BUGX_DOCS_TOKEN")
|
|
333
|
-
# The stdio boundary is local; when a token is configured, every call must
|
|
334
|
-
# still prove both token and project scope. No token is ever logged/returned.
|
|
335
1135
|
for raw_line in sys.stdin.buffer:
|
|
336
1136
|
request_id = None
|
|
337
1137
|
has_id = False
|
|
@@ -351,10 +1151,12 @@ def serve(root: Path, db: Path, *, project_id: str, version: str,
|
|
|
351
1151
|
if method in {"notifications/initialized", "notifications/cancelled"}:
|
|
352
1152
|
continue
|
|
353
1153
|
if method == "initialize":
|
|
354
|
-
payload = {
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
1154
|
+
payload = {
|
|
1155
|
+
"protocolVersion": MCP_PROTOCOL_VERSION,
|
|
1156
|
+
"capabilities": {"tools": {"listChanged": False}},
|
|
1157
|
+
"serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},
|
|
1158
|
+
"instructions": "调用工具时必须提供当前 project_id;支持 library_id='all'|'bugx:official'|'project:<id>'。",
|
|
1159
|
+
}
|
|
358
1160
|
elif method == "ping":
|
|
359
1161
|
payload = {}
|
|
360
1162
|
elif method == "tools/list":
|
|
@@ -365,8 +1167,13 @@ def serve(root: Path, db: Path, *, project_id: str, version: str,
|
|
|
365
1167
|
args = params.get("arguments") or {}
|
|
366
1168
|
if not isinstance(args, dict):
|
|
367
1169
|
raise DocsMcpError("arguments 必须是对象")
|
|
368
|
-
payload = _result(call_tool(
|
|
369
|
-
|
|
1170
|
+
payload = _result(call_tool(
|
|
1171
|
+
db, params["name"], args,
|
|
1172
|
+
project_id=project_id,
|
|
1173
|
+
expected_token=expected_token,
|
|
1174
|
+
mode=mode,
|
|
1175
|
+
remote_url=remote_url,
|
|
1176
|
+
))
|
|
370
1177
|
else:
|
|
371
1178
|
raise DocsMcpError(f"不支持 MCP 方法: {method}")
|
|
372
1179
|
if "id" in request:
|
|
@@ -389,7 +1196,7 @@ def serve(root: Path, db: Path, *, project_id: str, version: str,
|
|
|
389
1196
|
def main(argv: Sequence[str] | None = None) -> int:
|
|
390
1197
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
391
1198
|
sub = parser.add_subparsers(dest="command", required=True)
|
|
392
|
-
for name in ("index", "serve"):
|
|
1199
|
+
for name in ("index", "serve", "sync"):
|
|
393
1200
|
command = sub.add_parser(name)
|
|
394
1201
|
command.add_argument("--root", type=Path, default=Path.cwd())
|
|
395
1202
|
command.add_argument("--db", type=Path, default=Path(".bugx/knowledge/docs.sqlite3"))
|
|
@@ -398,6 +1205,12 @@ def main(argv: Sequence[str] | None = None) -> int:
|
|
|
398
1205
|
command.add_argument("--token", default=None, help=argparse.SUPPRESS)
|
|
399
1206
|
if name == "serve":
|
|
400
1207
|
command.add_argument("--no-auto-index", action="store_true")
|
|
1208
|
+
command.add_argument("--mode", choices=("hybrid", "local-only", "remote-only"), default="hybrid")
|
|
1209
|
+
command.add_argument("--remote-url", default=None)
|
|
1210
|
+
if name == "sync":
|
|
1211
|
+
command.add_argument("--force", action="store_true")
|
|
1212
|
+
command.add_argument("--offline", action="store_true")
|
|
1213
|
+
command.add_argument("--remote-url", default=None)
|
|
401
1214
|
args = parser.parse_args(argv)
|
|
402
1215
|
try:
|
|
403
1216
|
root = args.root.expanduser().resolve()
|
|
@@ -407,8 +1220,21 @@ def main(argv: Sequence[str] | None = None) -> int:
|
|
|
407
1220
|
print(json.dumps(index_documents(root, args.db, project_id=project_id, version=version),
|
|
408
1221
|
ensure_ascii=False))
|
|
409
1222
|
return 0
|
|
410
|
-
|
|
411
|
-
|
|
1223
|
+
if args.command == "sync":
|
|
1224
|
+
proj_res = index_documents(root, args.db, project_id=project_id, version=version)
|
|
1225
|
+
cloud_res = _docs_sync.sync_official_docs(
|
|
1226
|
+
contract_version=_docs_sync.contract_version_of(BASE_VERSION),
|
|
1227
|
+
force=bool(args.force),
|
|
1228
|
+
offline=bool(args.offline),
|
|
1229
|
+
remote_url=args.remote_url,
|
|
1230
|
+
)
|
|
1231
|
+
print(json.dumps({"project": proj_res, "official": cloud_res}, ensure_ascii=False))
|
|
1232
|
+
return 0
|
|
1233
|
+
return serve(
|
|
1234
|
+
root, args.db, project_id=project_id, version=version,
|
|
1235
|
+
token=args.token, auto_index=not args.no_auto_index,
|
|
1236
|
+
mode=args.mode, remote_url=args.remote_url,
|
|
1237
|
+
)
|
|
412
1238
|
except DocsMcpError as exc:
|
|
413
1239
|
print(f"bugx-docs: {exc}", file=sys.stderr)
|
|
414
1240
|
return 2
|