lantern-harness 0.1.45 → 0.2.2

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.
Files changed (244) hide show
  1. package/CHANGELOG.md +215 -0
  2. package/README.md +25 -8
  3. package/builtin/session/lh-fs.mjs +93 -4
  4. package/builtin/session/lh-nav-groups.mjs +3 -0
  5. package/builtin/session/mcp-client.mjs +7 -3
  6. package/builtin/session/session-runs.mjs +5 -1
  7. package/builtin/session/skill-validation.mjs +72 -0
  8. package/builtin/session/space-skills.mjs +751 -0
  9. package/cli/data-root.mjs +21 -4
  10. package/cli/lantern.mjs +26 -1
  11. package/cli/mcp-server.mjs +2779 -0
  12. package/cli/server.mjs +8 -2
  13. package/config/app.defaults.json +4 -2
  14. package/dist/500.html +9 -6
  15. package/dist/_astro/Base.Du_-4L-4.css +1 -0
  16. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.XUV2H6ea.js +2 -0
  17. package/dist/_astro/BusinessMapBoard.mRxl2G3D.js +5 -0
  18. package/dist/_astro/CaseExecBoard.Cqkxuf5c.js +1 -0
  19. package/dist/_astro/CaseExecutionBoard.CjX4CoKd.js +5 -0
  20. package/dist/_astro/CaseGenerateApp.acgnxl79.js +10 -0
  21. package/dist/_astro/CasesLibrary.zmzOQwdn.js +21 -0
  22. package/dist/_astro/ChatApp.Ben9LFra.js +1 -0
  23. package/dist/_astro/ChatApp.DBi6q7Qv.js +262 -0
  24. package/dist/_astro/{ConfirmDialog.DrrPf1MB.js → ConfirmDialog.DQFd6g2r.js} +1 -1
  25. package/dist/_astro/DashboardBoard.CAJVE2G4.js +5 -0
  26. package/dist/_astro/{DatePicker.Bkl71M49.js → DatePicker.BRO_CjVQ.js} +1 -1
  27. package/dist/_astro/DefectSubmitEntry.BzKXJ-zq.js +2 -0
  28. package/dist/_astro/DocsFileBrowser.apKMbGVf.js +1 -0
  29. package/dist/_astro/{DocsPager.Duf4I68E.js → DocsPager.DMN9-Tjg.js} +1 -1
  30. package/dist/_astro/{DrawerField.BH3p4Q4D.js → DrawerField.CLdvmHc6.js} +1 -1
  31. package/dist/_astro/KnowledgeLibrary.BcoMQeUd.js +1 -0
  32. package/dist/_astro/LifeKrTasksBoard.DJU0-QI-.js +1 -0
  33. package/dist/_astro/LifeKrTodosBoard.GK7KRAO3.js +1 -0
  34. package/dist/_astro/LifeObjectivesBoard.DuKa6Q3k.js +1 -0
  35. package/dist/_astro/LifePlanTypeSelect.Cm2lUmnH.js +1 -0
  36. package/dist/_astro/{LifeReviewsBoard.BPXeVpg1.js → LifeReviewsBoard.BWOOVMtz.js} +3 -3
  37. package/dist/_astro/{LifeShared.tnT7aQON.js → LifeShared.bY2l01Ha.js} +2 -2
  38. package/dist/_astro/LifeStagesBoard.CIzxPOJB.js +1 -0
  39. package/dist/_astro/LifeYearCycleSelect.BlsyPmmI.js +1 -0
  40. package/dist/_astro/LifeYearPlansBoard.DaA9O08j.js +1 -0
  41. package/dist/_astro/MultiSelectDropdown.D-rbpivp.js +1 -0
  42. package/dist/_astro/{NamePromptDialog.Csfnh5eM.js → NamePromptDialog.KPCeXmri.js} +1 -1
  43. package/dist/_astro/NavLibraries.DVR5Ua-S.js +1 -0
  44. package/dist/_astro/PluginsPage.B063QIlQ.js +18 -0
  45. package/dist/_astro/PmBugsBoard.Cu-v0Gfd.js +1 -0
  46. package/dist/_astro/PmIterationsBoard.CgRzkP-j.js +1 -0
  47. package/dist/_astro/{PmProjectDetail.DneFVBpy.js → PmProjectDetail.DVCEh0Lm.js} +1 -1
  48. package/dist/_astro/PmProjectsBoard.z-bQa98r.js +1 -0
  49. package/dist/_astro/PmRequirementsBoard.B0W6bsW2.js +1 -0
  50. package/dist/_astro/PmRequirementsBoard.CyfBI0u_.js +1 -0
  51. package/dist/_astro/PmShared.BQVzwsiz.js +1 -0
  52. package/dist/_astro/ReportsPage.najSzJeT.js +1 -0
  53. package/dist/_astro/ReqAnalysisBoard.BQb8dHFD.js +39 -0
  54. package/dist/_astro/RequirementBreakdownLibrary.Cn6OV6xt.js +2 -0
  55. package/dist/_astro/RequirementsLibrary.CqKNFVsP.js +1 -0
  56. package/dist/_astro/SearchableSelect.DXclLMJI.js +1 -0
  57. package/dist/_astro/SelectDropdown.D7IeyHDI.js +1 -0
  58. package/dist/_astro/SettingsDialog.db3BpFw0.js +1 -0
  59. package/dist/_astro/SlideOverDrawer.BMg2tce6.js +1 -0
  60. package/dist/_astro/SpaceSwitcher.DSUVAPOi.js +7 -0
  61. package/dist/_astro/{TableFieldConfig.C7O-mL-p.js → TableFieldConfig.72AL-8p-.js} +1 -1
  62. package/dist/_astro/{TagSelect.UUXgkMqJ.js → TagSelect.B_r2p0fp.js} +1 -1
  63. package/dist/_astro/TasksBoard.CCDhCSR7.js +1 -0
  64. package/dist/_astro/TemplatesLibrary.peYzrHZ2.js +1 -0
  65. package/dist/_astro/TestReportsLibrary.fWiEyCRx.js +1 -0
  66. package/dist/_astro/TestStatsBoard.BSUBsWSu.js +1 -0
  67. package/dist/_astro/Toast.BydY-X7T.js +1 -0
  68. package/dist/_astro/TodosBoard.By5YdlUe.js +1 -0
  69. package/dist/_astro/UiAutoBoard.BGdlp5Sr.js +3 -0
  70. package/dist/_astro/UiAutoEnvPanel.BUASgPLB.js +10 -0
  71. package/dist/_astro/UiAutoGenerationDialog.D1PyCgrD.js +12 -0
  72. package/dist/_astro/UiAutoProjectsPage.B6A9NlVK.js +3 -0
  73. package/dist/_astro/app-config.Dvfzl5_N.js +1 -0
  74. package/dist/_astro/app-version.CNpnKIb9.js +1 -0
  75. package/dist/_astro/{bash-tools.D9HCzC_7.js → bash-tools.CS2w8LOb.js} +1 -1
  76. package/dist/_astro/business-map.BiJ85oxm.js +1 -0
  77. package/dist/_astro/business-map.DKwdW1VL.css +1 -0
  78. package/dist/_astro/case-gen-run.Cvvdv_kv.js +26 -0
  79. package/dist/_astro/case-prompt.CZ3vWUju.js +2 -0
  80. package/dist/_astro/{case-review.TdDs1WFM.js → case-review.DFWZkoR9.js} +1 -1
  81. package/dist/_astro/{case-template.Cd2xNbgy.js → case-template.Clb7HrDB.js} +1 -1
  82. package/dist/_astro/defect-submit.Dc49lFjm.css +1 -0
  83. package/dist/_astro/defect-workbench.CjTb4FDv.js +6 -0
  84. package/dist/_astro/dialog.XgRGNF_Q.js +1 -0
  85. package/dist/_astro/doc-roots.C-20VD0x.js +1 -0
  86. package/dist/_astro/{hydrate-cache.B15Nrpq0.js → hydrate-cache.O4CIma9y.js} +1 -1
  87. package/dist/_astro/i18n.Cp4so7KR.js +7 -0
  88. package/dist/_astro/{llm.DN5S1KBK.js → llm.BCYNgppW.js} +1 -1
  89. package/dist/_astro/mcp-tools.Kf-lupGn.js +7 -0
  90. package/dist/_astro/{open-docs-in-session.CRiZT022.js → open-docs-in-session.BpcAcBSI.js} +1 -1
  91. package/dist/_astro/plugins.Db9xoFZb.js +1 -0
  92. package/dist/_astro/project-docs.bB9lQ1Ki.js +1 -0
  93. package/dist/_astro/prompts-meta.VAjE4OET.js +2 -0
  94. package/dist/_astro/report-prompt.CwHuOcRN.js +1 -0
  95. package/dist/_astro/req-analysis.C_gARMrB.js +31 -0
  96. package/dist/_astro/requirement-breakdown-library.l0rPd7b3.js +1 -0
  97. package/dist/_astro/{settings.38J2uD5M.js → settings.D02wZj3w.js} +2 -2
  98. package/dist/_astro/space-skills.CPucW8zt.js +1 -0
  99. package/dist/_astro/{spaces-client.DV04tRyD.js → spaces-client.BAtG6PkW.js} +1 -1
  100. package/dist/_astro/story-review.DTN91Vl9.js +7 -0
  101. package/dist/_astro/test-points.C7ZgggQT.js +8 -0
  102. package/dist/_astro/test-reports.0gr6-c_0.js +19 -0
  103. package/dist/_astro/ui-auto-prompt.BmO3ja2m.js +8 -0
  104. package/dist/_astro/{view-prefs.DhdLZjGh.js → view-prefs.COAKEQtZ.js} +1 -1
  105. package/dist/business-map/index.html +983 -0
  106. package/dist/case-exec/index.html +10 -7
  107. package/dist/{prompts → case-execution}/index.html +12 -9
  108. package/dist/cases/generate/index.html +9 -6
  109. package/dist/cases/library/index.html +10 -7
  110. package/dist/dashboard/index.html +10 -7
  111. package/dist/defect-rules/index.html +690 -0
  112. package/dist/defect-submit/index.html +690 -0
  113. package/dist/defect-submit/templates/index.html +690 -0
  114. package/dist/docs/changelog/index.html +259 -52
  115. package/dist/docs/install/index.html +44 -12
  116. package/dist/docs/manual/index.html +212 -75
  117. package/dist/knowledge/index.html +10 -7
  118. package/dist/life/kr-tasks/index.html +10 -7
  119. package/dist/life/kr-todos/index.html +10 -7
  120. package/dist/life/objectives/index.html +10 -7
  121. package/dist/life/reviews/index.html +10 -7
  122. package/dist/life/stages/index.html +10 -7
  123. package/dist/life/year-plans/index.html +10 -7
  124. package/dist/plugins/index.html +10 -7
  125. package/dist/pm/bugs/index.html +10 -7
  126. package/dist/pm/iterations/index.html +10 -7
  127. package/dist/pm/projects/detail/index.html +10 -7
  128. package/dist/pm/projects/index.html +10 -7
  129. package/dist/pm/requirements/index.html +10 -7
  130. package/dist/reports/index.html +10 -7
  131. package/dist/requirement-analysis/index.html +10 -7
  132. package/dist/requirement-breakdowns/index.html +983 -0
  133. package/dist/requirements/index.html +10 -7
  134. package/dist/tasks/index.html +10 -7
  135. package/dist/templates/index.html +10 -7
  136. package/dist/test-automation/index.html +10 -7
  137. package/dist/test-automation/projects/index.html +10 -7
  138. package/dist/test-reports/index.html +10 -7
  139. package/dist/test-stats/index.html +10 -7
  140. package/dist/todos/index.html +10 -7
  141. package/dist/workbench/index.html +9 -6
  142. package/docs/Codex-MCP/351/233/206/346/210/220.md +296 -0
  143. package/docs//344/270/232/345/212/241/345/234/260/345/233/276/350/257/204/344/274/260.md +39 -0
  144. package/docs//344/270/232/345/212/241/345/234/260/345/233/276/350/257/206/345/210/253/351/207/215/346/236/204/346/226/271/346/241/210.md +88 -0
  145. package/docs//344/274/232/350/257/235/346/217/222/344/273/266.md +22 -3
  146. package/docs//345/205/250/345/261/200/346/217/222/344/273/266.md +41 -1
  147. package/docs//345/256/211/350/243/205/346/211/213/345/206/214.md +63 -17
  148. package/docs//346/217/222/344/273/266/344/273/223/345/272/223/344/270/216/346/212/200/350/203/275/346/225/264/345/220/210/346/226/271/346/241/210.md +187 -0
  149. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +207 -69
  150. package/lh-plugins/business-map/assistant.mjs +958 -0
  151. package/lh-plugins/business-map/auth-paths.mjs +61 -0
  152. package/lh-plugins/business-map/jobs.mjs +749 -0
  153. package/lh-plugins/business-map/login.mjs +295 -0
  154. package/lh-plugins/business-map/sources.mjs +1014 -0
  155. package/lh-plugins/case-execution/files.mjs +777 -0
  156. package/lh-plugins/case-execution/service.mjs +959 -0
  157. package/lh-plugins/case-execution-prompt.mjs +33 -0
  158. package/lh-plugins/lh-business-map.mjs +2431 -0
  159. package/lh-plugins/lh-case-execution.mjs +304 -0
  160. package/lh-plugins/lh-config.mjs +13 -0
  161. package/lh-plugins/lh-defect-submit.mjs +989 -0
  162. package/lh-plugins/lh-project-docs.mjs +31 -140
  163. package/lh-plugins/lh-reports.mjs +29 -57
  164. package/lh-plugins/lh-req-analysis.mjs +32 -3
  165. package/lh-plugins/lh-req-breakdown-library.mjs +1084 -0
  166. package/lh-plugins/lh-uiauto.mjs +514 -22
  167. package/lh-plugins/plugin-prompts.mjs +19 -15
  168. package/lh-plugins/req-analysis-revision.mjs +24 -0
  169. package/lh-plugins/test-points-prompt.mjs +2 -3
  170. package/lh-plugins/uiauto-auth-setup.mjs +218 -0
  171. package/lh-plugins/uiauto-explorer/apps.mjs +13 -2
  172. package/lh-plugins/uiauto-explorer/runner.mjs +15 -2
  173. package/lh-plugins/uiauto-explorer/sessions.mjs +305 -17
  174. package/lh-plugins/uiauto-node.mjs +102 -11
  175. package/lh-plugins/uiauto-prompt.mjs +20 -15
  176. package/lh-plugins/uiauto-sso.mjs +407 -0
  177. package/package.json +5 -2
  178. package/skills/case-execution/SKILL.md +30 -0
  179. package/skills/lantern-defect-submit/SKILL.md +15 -0
  180. package/skills/lantern-workflow/SKILL.md +57 -0
  181. package/skills/office/SKILL.md +26 -0
  182. package/dist/_astro/Base.Bkt1lrgu.css +0 -1
  183. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.UKTVQqk7.js +0 -2
  184. package/dist/_astro/CaseExecBoard.DICluCbK.js +0 -1
  185. package/dist/_astro/CaseGenerateApp.Be3h5XPG.js +0 -10
  186. package/dist/_astro/CasesLibrary.Buys7Cy-.js +0 -21
  187. package/dist/_astro/ChatApp.D3BheKci.js +0 -227
  188. package/dist/_astro/DashboardBoard.Qvf8o4v1.js +0 -5
  189. package/dist/_astro/DocsFileBrowser.DwKBffbM.js +0 -1
  190. package/dist/_astro/KnowledgeLibrary.MDpMqeOd.js +0 -1
  191. package/dist/_astro/LifeKrTasksBoard.DsvW_S66.js +0 -1
  192. package/dist/_astro/LifeKrTodosBoard.D2KTqvg1.js +0 -1
  193. package/dist/_astro/LifeObjectivesBoard.B0cDK934.js +0 -1
  194. package/dist/_astro/LifePlanTypeSelect.BELDvMWU.js +0 -1
  195. package/dist/_astro/LifeStagesBoard.CZftLR9K.js +0 -1
  196. package/dist/_astro/LifeYearCycleSelect.Bw2eRbSm.js +0 -1
  197. package/dist/_astro/LifeYearPlansBoard.DB-RJFEl.js +0 -1
  198. package/dist/_astro/MultiSelectDropdown.CBC7aNOv.js +0 -1
  199. package/dist/_astro/NavLibraries.DdQYsZbe.js +0 -1
  200. package/dist/_astro/OverflowHint.CHZeFfUj.js +0 -1
  201. package/dist/_astro/PluginsPage.C1JnInH4.js +0 -17
  202. package/dist/_astro/PluginsPage.C3eEwy3K.js +0 -1
  203. package/dist/_astro/PmBugsBoard.CGpXUTPu.js +0 -1
  204. package/dist/_astro/PmIterationsBoard.BaKiFIam.js +0 -1
  205. package/dist/_astro/PmProjectsBoard.BxoMF9gK.js +0 -1
  206. package/dist/_astro/PmRequirementsBoard.-SI8VZXI.js +0 -1
  207. package/dist/_astro/PmRequirementsBoard.DsK6RF7Q.js +0 -1
  208. package/dist/_astro/PmShared.BK8kWRSV.js +0 -1
  209. package/dist/_astro/PromptMountDialog.mrTx3U5T.js +0 -1
  210. package/dist/_astro/PromptsLibrary.B_SUf47p.js +0 -1
  211. package/dist/_astro/ReportsPage.B9lGg1_s.js +0 -16
  212. package/dist/_astro/ReqAnalysisBoard.CIZKnCQH.js +0 -39
  213. package/dist/_astro/RequirementsLibrary.cJc-bnGQ.js +0 -1
  214. package/dist/_astro/SearchableSelect.SyLRS-Jj.js +0 -1
  215. package/dist/_astro/SelectDropdown.T3CKHaLt.js +0 -1
  216. package/dist/_astro/SettingsDialog.DYdtCvLc.js +0 -1
  217. package/dist/_astro/SpaceSwitcher.C47_S1g9.js +0 -7
  218. package/dist/_astro/TasksBoard.BUEg2BYk.js +0 -1
  219. package/dist/_astro/TemplatesLibrary.BLVIphXO.js +0 -1
  220. package/dist/_astro/TestReportsLibrary.DVq30Jae.js +0 -1
  221. package/dist/_astro/TestStatsBoard.-5BWQ6bI.js +0 -1
  222. package/dist/_astro/Toast.BO2NFckG.js +0 -1
  223. package/dist/_astro/TodosBoard.DI_lTp2e.js +0 -1
  224. package/dist/_astro/UiAutoBoard.ChFdgv7s.js +0 -2
  225. package/dist/_astro/UiAutoEnvPanel.B50q4kYb.js +0 -19
  226. package/dist/_astro/UiAutoGenerationDialog.CLkFAHrm.js +0 -1
  227. package/dist/_astro/UiAutoProjectsPage.DCsDeN5d.js +0 -3
  228. package/dist/_astro/app-config.DkyjuL-S.js +0 -1
  229. package/dist/_astro/app-version.Cy-5oZO2.js +0 -1
  230. package/dist/_astro/case-gen-run.BklG1H8k.js +0 -22
  231. package/dist/_astro/case-types.DlFkbZJN.js +0 -1
  232. package/dist/_astro/dialog.DZHZCe_T.js +0 -1
  233. package/dist/_astro/doc-roots.CO3IBiY6.js +0 -1
  234. package/dist/_astro/i18n.D_aOCHSN.js +0 -7
  235. package/dist/_astro/markdown-client.BS19nLL3.js +0 -62
  236. package/dist/_astro/plugins.BRvXWHLe.js +0 -1
  237. package/dist/_astro/project-docs.CCjtiFjB.js +0 -1
  238. package/dist/_astro/prompts-meta.BUGutlsk.js +0 -2
  239. package/dist/_astro/report-prompt.B9C4cv84.js +0 -1
  240. package/dist/_astro/req-analysis.B12_MGMQ.js +0 -31
  241. package/dist/_astro/story-review.D2W5tEOY.js +0 -14
  242. package/dist/_astro/test-reports.CuIjlEyK.js +0 -19
  243. package/dist/_astro/ui-auto-prompt.H9_yhau9.js +0 -9
  244. package/dist/_astro/ui-auto.DMv940x4.js +0 -1
@@ -0,0 +1,2779 @@
1
+ /**
2
+ * Lantern MCP Bridge:让 Codex 通过结构化工具读写当前 Lantern 数据空间。
3
+ *
4
+ * 首版采用委托分析模式:
5
+ * - Codex 负责模型推理;
6
+ * - Lantern 提供技能正文、需求源文、存储、编号、校验与 revision;
7
+ * - Bridge 不直接改 JSON,所有写入都走现有 HTTP API。
8
+ */
9
+ import crypto from 'node:crypto';
10
+ import fs from 'node:fs';
11
+ import net from 'node:net';
12
+ import path from 'node:path';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
15
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
16
+ import * as z from 'zod/v4';
17
+
18
+ import { DEFECT_API } from '../lh-plugins/lh-defect-submit.mjs';
19
+ import { analysisRevision } from '../lh-plugins/req-analysis-revision.mjs';
20
+ import { startLocalServer } from './server.mjs';
21
+
22
+ const API_PREFIX = '/__tb_';
23
+ const DOC_API = `${API_PREFIX}requirements`;
24
+ const REQ_API = `${API_PREFIX}reqanalysis`;
25
+ const SKILL_API = `${API_PREFIX}fs/skill-store`;
26
+ const CONFIG_API = `/${API_PREFIX.slice(1)}config`;
27
+ const BUSINESS_MAP_API = `/${API_PREFIX.slice(1)}business_map`;
28
+ const REQ_BREAKDOWN_API = `/${API_PREFIX.slice(1)}req_breakdowns`;
29
+ const CASE_EXECUTION_API = `/${API_PREFIX.slice(1)}case_run`;
30
+ const SKILL_PROMPT_ROUTES = {
31
+ '需求分析提示词.md': `/${API_PREFIX.slice(1)}reqanalysis/prompt`,
32
+ '原文结构提示词.md': `/${API_PREFIX.slice(1)}reqanalysis/prompt`,
33
+ '用户故事审查提示词.md': `/${API_PREFIX.slice(1)}storyreview/prompt`,
34
+ '测试点生成提示词.md': `/${API_PREFIX.slice(1)}testpoints/prompt`,
35
+ };
36
+ const REQUIREMENT_WORKFLOW_PLUGINS = ['requirements', 'reqAnalysis', 'storyReview', 'testPoints'];
37
+ const ALLOWED_REQUIREMENT_EXT = new Set(['.md', '.txt', '.docx', '.csv', '.xlsx', '.xls']);
38
+ const MAX_IMPORT_BYTES = 12 * 1024 * 1024;
39
+ const MAX_BUSINESS_MATERIAL_BYTES = 25 * 1024 * 1024;
40
+ const DEFAULT_SOURCE_CHARS = 80_000;
41
+ const businessEvidenceInput = z.array(z.record(z.string(), z.unknown())).optional();
42
+ const businessDependencyInput = z
43
+ .array(
44
+ z.object({
45
+ system: z.string(),
46
+ label: z.string().optional(),
47
+ }),
48
+ )
49
+ .optional();
50
+
51
+ class BridgeError extends Error {
52
+ constructor(message, status = 0, details = null) {
53
+ super(message);
54
+ this.name = 'BridgeError';
55
+ this.status = status;
56
+ this.details = details;
57
+ }
58
+ }
59
+
60
+ function cleanBase(value) {
61
+ return String(value || '')
62
+ .replace(/\/+$/, '')
63
+ .trim();
64
+ }
65
+
66
+ function sha256(text) {
67
+ return crypto
68
+ .createHash('sha256')
69
+ .update(String(text ?? ''), 'utf8')
70
+ .digest('hex');
71
+ }
72
+
73
+ function safeJsonParse(text, fallback = null) {
74
+ try {
75
+ return JSON.parse(text);
76
+ } catch {
77
+ return fallback;
78
+ }
79
+ }
80
+
81
+ async function apiRequest(
82
+ apiBase,
83
+ route,
84
+ {
85
+ method = 'GET',
86
+ body,
87
+ rawBody,
88
+ contentType = 'application/json',
89
+ timeoutMs = 30_000,
90
+ raw = false,
91
+ } = {},
92
+ ) {
93
+ const url = `${cleanBase(apiBase)}${route}`;
94
+ const hasBody = body !== undefined || rawBody !== undefined;
95
+ const response = await fetch(url, {
96
+ method,
97
+ headers: hasBody ? { 'Content-Type': contentType } : undefined,
98
+ body: rawBody !== undefined ? rawBody : body === undefined ? undefined : JSON.stringify(body),
99
+ signal: AbortSignal.timeout(timeoutMs),
100
+ });
101
+ const text = await response.text();
102
+ const data = raw ? text : safeJsonParse(text, { raw: text });
103
+ if (!response.ok || (data && typeof data === 'object' && data.ok === false)) {
104
+ const message =
105
+ data && typeof data === 'object' && 'error' in data
106
+ ? String(data.error)
107
+ : `Lantern HTTP ${response.status}`;
108
+ throw new BridgeError(message, response.status, data);
109
+ }
110
+ return data;
111
+ }
112
+
113
+ function toolResult(data, summary = '') {
114
+ const structured =
115
+ data && typeof data === 'object' && !Array.isArray(data) ? data : { value: data };
116
+ const json = JSON.stringify(structured, null, 2);
117
+ return {
118
+ content: [{ type: 'text', text: summary ? `${summary}\n\n${json}` : json }],
119
+ structuredContent: structured,
120
+ };
121
+ }
122
+
123
+ function toolError(error) {
124
+ const message = error instanceof Error ? error.message : String(error);
125
+ const details =
126
+ error instanceof BridgeError && error.details ? { details: error.details } : undefined;
127
+ return {
128
+ isError: true,
129
+ content: [{ type: 'text', text: JSON.stringify({ ok: false, error: message, ...details }) }],
130
+ structuredContent: { ok: false, error: message, ...details },
131
+ };
132
+ }
133
+
134
+ function protectedTool(handler) {
135
+ return async (args, extra) => {
136
+ try {
137
+ return await handler(args, extra);
138
+ } catch (error) {
139
+ return toolError(error);
140
+ }
141
+ };
142
+ }
143
+
144
+ async function loadBusinessMapStore(apiBase) {
145
+ const data = await apiRequest(apiBase, BUSINESS_MAP_API);
146
+ if (!data.store || !Array.isArray(data.store.systems))
147
+ throw new BridgeError('Lantern 业务地图数据不可用', 502);
148
+ return data.store;
149
+ }
150
+
151
+ async function requireBusinessMapRevision(apiBase, expectedRevision) {
152
+ if (Number.isFinite(Number(expectedRevision)) && Number(expectedRevision) >= 0)
153
+ return Number(expectedRevision);
154
+ const store = await loadBusinessMapStore(apiBase);
155
+ throw new BridgeError('修改业务地图必须提供 expectedRevision;请先读取最新 map', 428, {
156
+ currentRevision: store.revision,
157
+ });
158
+ }
159
+
160
+ function requireBusinessSystem(store, systemId) {
161
+ const system = store.systems.find((item) => item.id === systemId);
162
+ if (!system) throw new BridgeError(`业务系统不存在:${systemId}`, 404);
163
+ return system;
164
+ }
165
+
166
+ function businessMapSummary(store) {
167
+ return {
168
+ ok: true,
169
+ revision: store.revision,
170
+ updatedAt: store.updatedAt || '',
171
+ systems: store.systems.map((system) => ({
172
+ id: system.id,
173
+ name: system.name,
174
+ description: system.description || '',
175
+ entryUrl: system.entryUrl || '',
176
+ sourceDir: system.sourceDir || '',
177
+ directoryCount: system.directories.length,
178
+ functionCount: system.functions.length,
179
+ flowCount: system.flows.length,
180
+ updatedAt: system.updatedAt || '',
181
+ })),
182
+ };
183
+ }
184
+
185
+ function stripBusinessEvidence(item, includeEvidence) {
186
+ if (includeEvidence || !item || typeof item !== 'object') return item;
187
+ const { evidence: _evidence, ...rest } = item;
188
+ return rest;
189
+ }
190
+
191
+ function projectBusinessSystem(system, args) {
192
+ const includeEvidence = args.includeEvidence === true;
193
+ const query = String(args.query || '')
194
+ .trim()
195
+ .toLowerCase();
196
+ let directories = [...system.directories];
197
+ let functions = [...system.functions];
198
+ let flows = [...system.flows];
199
+
200
+ if (args.directoryId) {
201
+ const directoryIds = new Set([args.directoryId]);
202
+ const queue = [args.directoryId];
203
+ while (queue.length) {
204
+ const parentId = queue.shift();
205
+ for (const directory of directories) {
206
+ if (directory.parentId === parentId && !directoryIds.has(directory.id)) {
207
+ directoryIds.add(directory.id);
208
+ queue.push(directory.id);
209
+ }
210
+ }
211
+ }
212
+ directories = directories.filter((directory) => directoryIds.has(directory.id));
213
+ functions = functions.filter((fn) => directoryIds.has(fn.directoryId));
214
+ flows = flows.filter((flow) =>
215
+ flow.steps.some((step) => functions.some((fn) => fn.id === step.functionId)),
216
+ );
217
+ }
218
+
219
+ if (args.functionId) {
220
+ functions = functions.filter((fn) => fn.id === args.functionId);
221
+ const functionIds = new Set(functions.map((fn) => fn.id));
222
+ flows = flows.filter((flow) => flow.steps.some((step) => functionIds.has(step.functionId)));
223
+ }
224
+
225
+ if (args.flowId) {
226
+ flows = flows.filter((flow) => flow.id === args.flowId);
227
+ const functionIds = new Set(flows.flatMap((flow) => flow.steps.map((step) => step.functionId)));
228
+ if (functionIds.size) functions = functions.filter((fn) => functionIds.has(fn.id));
229
+ }
230
+
231
+ if (query) {
232
+ directories = directories.filter((directory) =>
233
+ [directory.name, ...(directory.menuPath || [])].join(' ').toLowerCase().includes(query),
234
+ );
235
+ functions = functions.filter((fn) =>
236
+ [fn.id, fn.code, fn.name, fn.purpose, fn.entry, fn.domain, fn.module, ...(fn.roles || [])]
237
+ .join(' ')
238
+ .toLowerCase()
239
+ .includes(query),
240
+ );
241
+ flows = flows.filter((flow) =>
242
+ [flow.id, flow.code, flow.name, flow.result].join(' ').toLowerCase().includes(query),
243
+ );
244
+ }
245
+
246
+ return {
247
+ system: {
248
+ id: system.id,
249
+ name: system.name,
250
+ description: system.description || '',
251
+ entryUrl: system.entryUrl || '',
252
+ sourceDir: system.sourceDir || '',
253
+ analysisScope: system.analysisScope || '',
254
+ docs: system.docs,
255
+ createdAt: system.createdAt,
256
+ updatedAt: system.updatedAt,
257
+ },
258
+ directories: directories.map((item) => stripBusinessEvidence(item, includeEvidence)),
259
+ functions: functions.map((item) => stripBusinessEvidence(item, includeEvidence)),
260
+ flows: flows.map((flow) => ({
261
+ ...stripBusinessEvidence(flow, includeEvidence),
262
+ steps: flow.steps.map((step) => stripBusinessEvidence(step, includeEvidence)),
263
+ })),
264
+ };
265
+ }
266
+
267
+ async function loadBusinessModelSettings(apiBase) {
268
+ const data = await apiRequest(apiBase, CONFIG_API);
269
+ const config = data.config && typeof data.config === 'object' ? data.config : {};
270
+ const modelConfig = config.model && typeof config.model === 'object' ? config.model : {};
271
+ const providers = Array.isArray(modelConfig.providers) ? modelConfig.providers : [];
272
+ const provider =
273
+ providers.find((item) => item.id === modelConfig.activeId) || providers[0] || modelConfig;
274
+ const settings = {
275
+ baseURL: String(provider.baseURL || '').trim(),
276
+ model: String(provider.model || '').trim(),
277
+ apiKey: String(data.apiKey || provider.apiKey || '').trim(),
278
+ ...(modelConfig.reasoningEffort
279
+ ? { reasoningEffort: String(modelConfig.reasoningEffort) }
280
+ : {}),
281
+ };
282
+ if (!settings.baseURL || !settings.model || !settings.apiKey) {
283
+ throw new BridgeError('请先在 Lantern 设置中配置可用的模型与 API Key', 400);
284
+ }
285
+ return settings;
286
+ }
287
+
288
+ async function waitForBusinessAssistant(apiBase, systemId, timeoutMs, afterSeq = 0) {
289
+ const deadline = Date.now() + Math.max(1000, Math.min(Number(timeoutMs) || 25_000, 55_000));
290
+ let latest = null;
291
+ while (Date.now() < deadline) {
292
+ const data = await apiRequest(
293
+ apiBase,
294
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}/assistant`,
295
+ );
296
+ latest = data.session;
297
+ if (latest?.status !== 'running') break;
298
+ await new Promise((resolve) => setTimeout(resolve, 1000));
299
+ }
300
+ if (!latest) {
301
+ const data = await apiRequest(
302
+ apiBase,
303
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}/assistant`,
304
+ );
305
+ latest = data.session;
306
+ }
307
+ return {
308
+ ok: true,
309
+ session: {
310
+ ...latest,
311
+ events: (latest?.events || []).filter(
312
+ (event) => Number(event.seq) > Math.max(0, Number(afterSeq) || 0),
313
+ ),
314
+ },
315
+ };
316
+ }
317
+
318
+ async function waitForCaseExecution(apiBase, runId, timeoutMs, afterSeq = 0) {
319
+ const deadline = Date.now() + Math.max(1000, Math.min(Number(timeoutMs) || 25_000, 55_000));
320
+ let latest = null;
321
+ while (Date.now() < deadline) {
322
+ const data = await apiRequest(
323
+ apiBase,
324
+ `${CASE_EXECUTION_API}/runs/${encodeURIComponent(runId)}`,
325
+ );
326
+ latest = data.run;
327
+ if (latest?.status !== 'running') break;
328
+ await new Promise((resolve) => setTimeout(resolve, 1000));
329
+ }
330
+ if (!latest) {
331
+ const data = await apiRequest(
332
+ apiBase,
333
+ `${CASE_EXECUTION_API}/runs/${encodeURIComponent(runId)}`,
334
+ );
335
+ latest = data.run;
336
+ }
337
+ return {
338
+ ok: true,
339
+ run: {
340
+ ...latest,
341
+ events: (latest?.events || []).filter(
342
+ (event) => Number(event.seq) > Math.max(0, Number(afterSeq) || 0),
343
+ ),
344
+ },
345
+ };
346
+ }
347
+
348
+ async function loadRequirementBreakdownList(apiBase) {
349
+ const data = await apiRequest(apiBase, `${REQ_BREAKDOWN_API}/list`);
350
+ if (!Array.isArray(data.entries)) throw new BridgeError('需求拆解库数据不可用', 502);
351
+ return { revision: Number(data.revision) || 0, entries: data.entries };
352
+ }
353
+
354
+ async function requireRequirementBreakdownRevision(apiBase, expectedRevision) {
355
+ if (Number.isFinite(Number(expectedRevision)) && Number(expectedRevision) >= 0)
356
+ return Number(expectedRevision);
357
+ const data = await loadRequirementBreakdownList(apiBase);
358
+ throw new BridgeError('修改需求拆解库必须提供 expectedRevision', 428, {
359
+ currentRevision: data.revision,
360
+ });
361
+ }
362
+
363
+ function parseBridgeArgs(argv = []) {
364
+ const out = { url: '', dataRoot: '', port: 0 };
365
+ for (let i = 0; i < argv.length; i += 1) {
366
+ const value = argv[i];
367
+ if (value === '--url') out.url = String(argv[++i] || '');
368
+ else if (value.startsWith('--url=')) out.url = value.slice('--url='.length);
369
+ else if (value === '--data-root') out.dataRoot = String(argv[++i] || '');
370
+ else if (value.startsWith('--data-root=')) out.dataRoot = value.slice('--data-root='.length);
371
+ else if (value === '--port') out.port = Number(argv[++i]) || 0;
372
+ else if (value.startsWith('--port=')) out.port = Number(value.slice('--port='.length)) || 0;
373
+ }
374
+ return out;
375
+ }
376
+
377
+ async function probeLantern(apiBase) {
378
+ try {
379
+ const data = await apiRequest(apiBase, `/${API_PREFIX.slice(1)}spaces`, {
380
+ timeoutMs: 1500,
381
+ });
382
+ return data && typeof data === 'object' && Array.isArray(data.spaces);
383
+ } catch {
384
+ return false;
385
+ }
386
+ }
387
+
388
+ async function freePort() {
389
+ return await new Promise((resolve, reject) => {
390
+ const server = net.createServer();
391
+ server.unref();
392
+ server.once('error', reject);
393
+ server.listen(0, '127.0.0.1', () => {
394
+ const address = server.address();
395
+ const port = address && typeof address === 'object' ? address.port : 0;
396
+ server.close((error) => (error ? reject(error) : resolve(port)));
397
+ });
398
+ });
399
+ }
400
+
401
+ async function ensureLanternApi({ url = '', dataRoot, port = 0 }) {
402
+ const requested = cleanBase(url);
403
+ if (requested) {
404
+ if (!(await probeLantern(requested))) {
405
+ throw new Error(`无法连接 Lantern 服务:${requested}`);
406
+ }
407
+ return { apiBase: requested, localServer: null };
408
+ }
409
+
410
+ const defaultBase = `http://127.0.0.1:${Number(port) || 4321}`;
411
+ if (await probeLantern(defaultBase)) {
412
+ return { apiBase: defaultBase, localServer: null };
413
+ }
414
+
415
+ if (!dataRoot) throw new Error('没有可用的 Lantern 服务,也没有配置数据池根');
416
+ const chosenPort = Number(port) || (await freePort());
417
+ const started = await startLocalServer({
418
+ dataRoot,
419
+ host: '127.0.0.1',
420
+ port: chosenPort,
421
+ });
422
+ return {
423
+ apiBase: cleanBase(started.url),
424
+ localServer: started.server,
425
+ };
426
+ }
427
+
428
+ async function listSpaceSkills(apiBase) {
429
+ const data = await apiRequest(apiBase, SKILL_API, {
430
+ method: 'POST',
431
+ body: { action: 'list' },
432
+ });
433
+ return Array.isArray(data.skills) ? data.skills : [];
434
+ }
435
+
436
+ async function readSpaceSkill(apiBase, id) {
437
+ const data = await apiRequest(apiBase, SKILL_API, {
438
+ method: 'POST',
439
+ body: { action: 'read', id: String(id || '').replace(/^space:/, '') },
440
+ });
441
+ return data.skill;
442
+ }
443
+
444
+ async function findSpaceSkillByLegacy(apiBase, legacyPath, { includeDisabled = false } = {}) {
445
+ const skills = await listSpaceSkills(apiBase);
446
+ return (
447
+ skills.find(
448
+ (item) => item.legacyPath === legacyPath && (includeDisabled || item.active !== false),
449
+ ) || null
450
+ );
451
+ }
452
+
453
+ async function requirementDocs(apiBase) {
454
+ const data = await apiRequest(apiBase, `/${REQ_API.slice(1)}/list`);
455
+ return Array.isArray(data.docs) ? data.docs : [];
456
+ }
457
+
458
+ async function findAnalysis(apiBase, { analysisId, sourcePath }) {
459
+ const docs = await requirementDocs(apiBase);
460
+ if (analysisId) return docs.find((doc) => doc.id === analysisId) || null;
461
+ if (sourcePath) return docs.find((doc) => doc.sourcePath === sourcePath) || null;
462
+ return null;
463
+ }
464
+
465
+ async function listRequirementEntries(apiBase, parent) {
466
+ const data = await apiRequest(apiBase, `/${DOC_API.slice(1)}/list`, {
467
+ method: 'POST',
468
+ body: { path: parent || '.' },
469
+ });
470
+ return Array.isArray(data.entries) ? data.entries : [];
471
+ }
472
+
473
+ function uniqueUploadName(entries, originalName, ext) {
474
+ const taken = new Set(
475
+ (Array.isArray(entries) ? entries : [])
476
+ .map((entry) => String(entry?.name || ''))
477
+ .filter(Boolean),
478
+ );
479
+ if (!taken.has(originalName)) return originalName;
480
+ const stem = path.basename(originalName, ext);
481
+ const stamp = new Date().toISOString().replace(/\D/g, '').slice(0, 14);
482
+ let name = `${stem}-${stamp}${ext}`;
483
+ for (let suffix = 2; taken.has(name); suffix += 1) {
484
+ name = `${stem}-${stamp}-${suffix}${ext}`;
485
+ }
486
+ return name;
487
+ }
488
+
489
+ async function readRequirementSource(apiBase, sourcePath) {
490
+ const route = `/${REQ_API.slice(1)}/source?path=${encodeURIComponent(sourcePath)}`;
491
+ return await apiRequest(apiBase, route, { timeoutMs: 60_000 });
492
+ }
493
+
494
+ async function withAnalysisSkillContext(apiBase, skillFile) {
495
+ let entry = await findSpaceSkillByLegacy(apiBase, skillFile, { includeDisabled: true });
496
+ if (!entry && SKILL_PROMPT_ROUTES[skillFile]) {
497
+ // 新空间尚未打开过插件页时,先按插件边界补种子提示词,再迁移为空间技能。
498
+ await apiRequest(apiBase, SKILL_PROMPT_ROUTES[skillFile]);
499
+ await apiRequest(apiBase, SKILL_API, {
500
+ method: 'POST',
501
+ body: { action: 'migrate' },
502
+ });
503
+ entry = await findSpaceSkillByLegacy(apiBase, skillFile, { includeDisabled: true });
504
+ }
505
+ if (!entry) {
506
+ throw new BridgeError(`未找到技能:${skillFile}`, 404);
507
+ }
508
+ if (entry.active === false) {
509
+ throw new BridgeError(`技能已停用:${skillFile}`, 409, {
510
+ skillId: entry.id,
511
+ legacyPath: skillFile,
512
+ });
513
+ }
514
+ return await readSpaceSkill(apiBase, entry.id);
515
+ }
516
+
517
+ async function prepareRequirementWorkflow(apiBase) {
518
+ const current = await apiRequest(apiBase, CONFIG_API);
519
+ const config = current.config || {};
520
+ const plugins = config.plugins || {};
521
+ const missing = REQUIREMENT_WORKFLOW_PLUGINS.filter((id) => plugins[id] !== true);
522
+ if (missing.length) {
523
+ await apiRequest(apiBase, CONFIG_API, {
524
+ method: 'PUT',
525
+ body: {
526
+ configTarget: current.configTarget,
527
+ config: {
528
+ ...config,
529
+ plugins: Object.fromEntries([
530
+ ...Object.entries(plugins),
531
+ ...REQUIREMENT_WORKFLOW_PLUGINS.map((id) => [id, true]),
532
+ ]),
533
+ },
534
+ },
535
+ });
536
+ }
537
+ await Promise.all(
538
+ [
539
+ `/${API_PREFIX.slice(1)}reqanalysis/prompt`,
540
+ `/${API_PREFIX.slice(1)}storyreview/prompt`,
541
+ `/${API_PREFIX.slice(1)}testpoints/prompt`,
542
+ ].map((route) => apiRequest(apiBase, route)),
543
+ );
544
+ await apiRequest(apiBase, SKILL_API, {
545
+ method: 'POST',
546
+ body: { action: 'migrate' },
547
+ });
548
+ const skills = await listSpaceSkills(apiBase);
549
+ const enabled = Object.fromEntries(REQUIREMENT_WORKFLOW_PLUGINS.map((id) => [id, true]));
550
+ return {
551
+ enabled,
552
+ changed: missing.length > 0,
553
+ missing,
554
+ skillCount: skills.filter((skill) => skill.active !== false).length,
555
+ skills: skills
556
+ .filter((skill) => skill.active !== false)
557
+ .map((skill) => ({
558
+ id: skill.id,
559
+ name: skill.name,
560
+ variant: skill.variant,
561
+ version: skill.version,
562
+ legacyPath: skill.legacyPath,
563
+ })),
564
+ };
565
+ }
566
+
567
+ function artifactUrl(apiBase, doc) {
568
+ return `${cleanBase(apiBase)}/requirement-analysis/?id=${encodeURIComponent(doc.id)}`;
569
+ }
570
+
571
+ function requireExpectedRevision(analysis, expectedRevision) {
572
+ const currentRevision = analysisRevision(analysis);
573
+ if (!expectedRevision) {
574
+ throw new BridgeError('修改已有需求分析必须提供 expectedRevision;请先重新读取最新内容', 428, {
575
+ analysisId: analysis.id,
576
+ currentRevision,
577
+ currentUpdatedAt: analysis.updatedAt || '',
578
+ });
579
+ }
580
+ if (expectedRevision !== currentRevision) {
581
+ throw new BridgeError('需求分析已被更新,请重新读取后再修改', 409, {
582
+ analysisId: analysis.id,
583
+ currentRevision,
584
+ currentUpdatedAt: analysis.updatedAt || '',
585
+ });
586
+ }
587
+ return currentRevision;
588
+ }
589
+
590
+ /**
591
+ * @param {{ apiBase: string, version?: string }} opts
592
+ */
593
+ export function createLanternMcpServer({ apiBase, version = '1.0.0' }) {
594
+ const server = new McpServer(
595
+ { name: 'lantern-harness', version, title: 'Lantern Harness Capabilities' },
596
+ {
597
+ instructions:
598
+ 'Lantern 提供测试业务规则、需求文档、需求分析、需求拆解库、测试点、用例执行、缺陷规则与提交、业务地图和确定性校验。需求分析可列举和批量删除;需求拆解库通过 lantern_requirement_breakdown_* 管理本地 XMind 文件;用例执行通过 lantern_case_execution_* 对单条用例启动 AI 浏览器执行、等待、停止、确认写回和同步统计;业务地图系统、目录、功能、流程、登录状态和本地资料可通过对应 lantern_business_* 工具管理,AI 目录/流程识别通过 lantern_business_assistant_* 启动和控制;缺陷规则、草稿、提交和回执通过 lantern_defect_* 管理。业务地图写入必须携带 expectedRevision。需要推理时先读取上下文,生成结构化结果后通过 Lantern 保存工具写回。外接 MCP(如腾讯文档)通过 lantern_mcp_tools 发现、lantern_mcp_call 调用,复用当前空间连接和权限。不要用浏览器点击 Lantern 页面。',
599
+ },
600
+ );
601
+
602
+ server.registerTool(
603
+ 'lantern_status',
604
+ {
605
+ title: 'Lantern 状态',
606
+ description: '检查 Lantern 本地能力服务、当前活动空间和可用空间列表。',
607
+ annotations: { readOnlyHint: true },
608
+ },
609
+ protectedTool(async () => {
610
+ const spaces = await apiRequest(apiBase, `/${API_PREFIX.slice(1)}spaces`);
611
+ return toolResult({
612
+ ok: true,
613
+ apiBase,
614
+ activeId: spaces.activeId || '',
615
+ spaces: spaces.spaces || [],
616
+ });
617
+ }),
618
+ );
619
+
620
+ server.registerTool(
621
+ 'lantern_space_list',
622
+ {
623
+ title: '列出 Lantern 空间',
624
+ description: '列出当前 Lantern 池根下的数据空间,并标记活动空间。',
625
+ annotations: { readOnlyHint: true },
626
+ },
627
+ protectedTool(async () => {
628
+ const data = await apiRequest(apiBase, `/${API_PREFIX.slice(1)}spaces`);
629
+ return toolResult(data);
630
+ }),
631
+ );
632
+
633
+ server.registerTool(
634
+ 'lantern_business_map_list',
635
+ {
636
+ title: '业务地图系统列表',
637
+ description: '列出当前空间业务地图中的系统及目录、功能、流程数量,并返回当前 revision。',
638
+ annotations: { readOnlyHint: true },
639
+ },
640
+ protectedTool(async () => toolResult(businessMapSummary(await loadBusinessMapStore(apiBase)))),
641
+ );
642
+
643
+ server.registerTool(
644
+ 'lantern_business_map_get',
645
+ {
646
+ title: '读取业务地图',
647
+ description:
648
+ '读取指定业务系统的目录、功能和流程。可按目录、功能、流程或关键词缩小范围;证据默认省略。',
649
+ inputSchema: {
650
+ systemId: z.string().describe('业务系统 ID'),
651
+ directoryId: z.string().optional().describe('只返回该目录及其子目录'),
652
+ functionId: z.string().optional().describe('只返回该功能及相关流程'),
653
+ flowId: z.string().optional().describe('只返回该流程及相关功能'),
654
+ query: z.string().optional().describe('按名称、编号、作用、角色等过滤'),
655
+ includeEvidence: z.boolean().optional().describe('是否返回证据数组,默认 false'),
656
+ },
657
+ annotations: { readOnlyHint: true },
658
+ },
659
+ protectedTool(async (args) => {
660
+ const store = await loadBusinessMapStore(apiBase);
661
+ const system = requireBusinessSystem(store, args.systemId);
662
+ return toolResult({
663
+ ok: true,
664
+ revision: store.revision,
665
+ ...projectBusinessSystem(system, args),
666
+ });
667
+ }),
668
+ );
669
+
670
+ server.registerTool(
671
+ 'lantern_business_login_status',
672
+ {
673
+ title: '读取业务系统登录状态',
674
+ description:
675
+ '读取业务系统已保存的登录方式、账号是否存在、是否已有可用登录态;不会返回密码、Cookie 或 Token。',
676
+ inputSchema: { systemId: z.string() },
677
+ annotations: { readOnlyHint: true },
678
+ },
679
+ protectedTool(async ({ systemId }) =>
680
+ toolResult(
681
+ await apiRequest(
682
+ apiBase,
683
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}/login`,
684
+ ),
685
+ ),
686
+ ),
687
+ );
688
+
689
+ server.registerTool(
690
+ 'lantern_business_login_start',
691
+ {
692
+ title: '启动业务系统登录验证',
693
+ description:
694
+ '使用 Lantern 已保存的登录配置启动验证;manual=true 时打开登录页面等待用户完成验证码或扫码。不接收密码。',
695
+ inputSchema: {
696
+ systemId: z.string(),
697
+ manual: z.boolean().optional().describe('是否强制进入手动登录页面'),
698
+ },
699
+ annotations: { destructiveHint: true, openWorldHint: true },
700
+ },
701
+ protectedTool(async ({ systemId, manual = false }) =>
702
+ toolResult(
703
+ await apiRequest(
704
+ apiBase,
705
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}/login/start`,
706
+ { method: 'POST', body: { manual }, timeoutMs: 90_000 },
707
+ ),
708
+ ),
709
+ ),
710
+ );
711
+
712
+ server.registerTool(
713
+ 'lantern_business_login_complete',
714
+ {
715
+ title: '保存已完成的业务登录态',
716
+ description: '用户已在 Lantern 打开的登录页面完成验证码、扫码或 SSO 后,保存浏览器登录态。',
717
+ inputSchema: { systemId: z.string() },
718
+ annotations: { destructiveHint: true, openWorldHint: true },
719
+ },
720
+ protectedTool(async ({ systemId }) =>
721
+ toolResult(
722
+ await apiRequest(
723
+ apiBase,
724
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}/login/complete`,
725
+ { method: 'POST', body: {}, timeoutMs: 60_000 },
726
+ ),
727
+ ),
728
+ ),
729
+ );
730
+
731
+ server.registerTool(
732
+ 'lantern_business_login_cancel',
733
+ {
734
+ title: '取消业务系统登录验证',
735
+ description: '关闭当前业务系统的登录窗口,不修改已经保存的登录配置。',
736
+ inputSchema: { systemId: z.string() },
737
+ annotations: { destructiveHint: true },
738
+ },
739
+ protectedTool(async ({ systemId }) =>
740
+ toolResult(
741
+ await apiRequest(
742
+ apiBase,
743
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}/login/cancel`,
744
+ { method: 'POST', body: {} },
745
+ ),
746
+ ),
747
+ ),
748
+ );
749
+
750
+ server.registerTool(
751
+ 'lantern_business_material_list',
752
+ {
753
+ title: '列出业务地图本地资料',
754
+ description: '列出指定业务系统已上传的本地业务资料,返回文件名、大小和更新时间。',
755
+ inputSchema: { systemId: z.string() },
756
+ annotations: { readOnlyHint: true },
757
+ },
758
+ protectedTool(async ({ systemId }) =>
759
+ toolResult(
760
+ await apiRequest(
761
+ apiBase,
762
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}/materials`,
763
+ ),
764
+ ),
765
+ ),
766
+ );
767
+
768
+ server.registerTool(
769
+ 'lantern_business_material_upload',
770
+ {
771
+ title: '上传业务地图本地资料',
772
+ description:
773
+ '把 Codex 可访问的 Word、Excel、Markdown、XMind、PPTX 等本地资料上传到指定业务系统,供后续 AI 识别使用。',
774
+ inputSchema: {
775
+ systemId: z.string(),
776
+ filePath: z.string().describe('本地文件绝对路径'),
777
+ },
778
+ annotations: { destructiveHint: true },
779
+ },
780
+ protectedTool(async ({ systemId, filePath }) => {
781
+ const absolute = path.resolve(String(filePath || ''));
782
+ const stat = fs.statSync(absolute);
783
+ if (!stat.isFile()) throw new BridgeError('filePath 不是文件');
784
+ if (stat.size > MAX_BUSINESS_MATERIAL_BYTES) {
785
+ throw new BridgeError(`业务资料超过 ${MAX_BUSINESS_MATERIAL_BYTES / 1024 / 1024} MB`);
786
+ }
787
+ const content = fs.readFileSync(absolute);
788
+ return toolResult(
789
+ await apiRequest(
790
+ apiBase,
791
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}/materials?name=${encodeURIComponent(path.basename(absolute))}`,
792
+ {
793
+ method: 'POST',
794
+ rawBody: content,
795
+ contentType: 'application/octet-stream',
796
+ timeoutMs: 90_000,
797
+ },
798
+ ),
799
+ );
800
+ }),
801
+ );
802
+
803
+ server.registerTool(
804
+ 'lantern_business_material_delete',
805
+ {
806
+ title: '删除业务地图本地资料',
807
+ description: '按文件名删除指定业务系统已上传的本地资料。',
808
+ inputSchema: {
809
+ systemId: z.string(),
810
+ name: z.string().min(1),
811
+ },
812
+ annotations: { destructiveHint: true },
813
+ },
814
+ protectedTool(async ({ systemId, name }) =>
815
+ toolResult(
816
+ await apiRequest(
817
+ apiBase,
818
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}/materials?name=${encodeURIComponent(name)}`,
819
+ { method: 'DELETE' },
820
+ ),
821
+ ),
822
+ ),
823
+ );
824
+
825
+ server.registerTool(
826
+ 'lantern_business_system_save',
827
+ {
828
+ title: '新建或修改业务系统',
829
+ description:
830
+ '创建业务系统或修改系统名称、说明、入口、源码目录和文档范围。修改时必须携带 expectedRevision。',
831
+ inputSchema: {
832
+ expectedRevision: z.number().int().nonnegative().optional(),
833
+ systemId: z.string().optional().describe('为空时新建'),
834
+ name: z.string().optional(),
835
+ description: z.string().optional(),
836
+ entryUrl: z.string().optional(),
837
+ sourceDir: z.string().optional(),
838
+ analysisScope: z.string().optional(),
839
+ docs: z
840
+ .object({
841
+ requirements: z.boolean().optional(),
842
+ knowledge: z.boolean().optional(),
843
+ scope: z.string().optional(),
844
+ })
845
+ .optional(),
846
+ },
847
+ annotations: { destructiveHint: true },
848
+ },
849
+ protectedTool(async (args) => {
850
+ const revision = await requireBusinessMapRevision(apiBase, args.expectedRevision);
851
+ const system = {
852
+ ...(args.name !== undefined ? { name: args.name } : {}),
853
+ ...(args.description !== undefined ? { description: args.description } : {}),
854
+ ...(args.entryUrl !== undefined ? { entryUrl: args.entryUrl } : {}),
855
+ ...(args.sourceDir !== undefined ? { sourceDir: args.sourceDir } : {}),
856
+ ...(args.analysisScope !== undefined ? { analysisScope: args.analysisScope } : {}),
857
+ ...(args.docs !== undefined ? { docs: args.docs } : {}),
858
+ };
859
+ let data;
860
+ if (args.systemId) {
861
+ data = await apiRequest(
862
+ apiBase,
863
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(args.systemId)}`,
864
+ { method: 'PUT', body: { revision, system } },
865
+ );
866
+ } else {
867
+ if (!String(args.name || '').trim()) throw new BridgeError('新建系统必须提供 name');
868
+ data = await apiRequest(apiBase, `${BUSINESS_MAP_API}/systems`, {
869
+ method: 'POST',
870
+ body: { revision, system },
871
+ });
872
+ }
873
+ const saved = requireBusinessSystem(data.store, args.systemId || data.systemId);
874
+ return toolResult({
875
+ ok: true,
876
+ revision: data.store.revision,
877
+ systemId: saved.id,
878
+ system: projectBusinessSystem(saved, {}).system,
879
+ });
880
+ }),
881
+ );
882
+
883
+ server.registerTool(
884
+ 'lantern_business_system_delete',
885
+ {
886
+ title: '删除业务系统',
887
+ description: '删除业务系统及其全部目录、功能、流程、AI 会话和本机资料。',
888
+ inputSchema: {
889
+ systemId: z.string(),
890
+ expectedRevision: z.number().int().nonnegative().optional(),
891
+ },
892
+ annotations: { destructiveHint: true },
893
+ },
894
+ protectedTool(async ({ systemId, expectedRevision }) => {
895
+ const revision = await requireBusinessMapRevision(apiBase, expectedRevision);
896
+ const data = await apiRequest(
897
+ apiBase,
898
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}`,
899
+ { method: 'DELETE', body: { revision } },
900
+ );
901
+ return toolResult({ ok: true, revision: data.store.revision, deletedSystemId: systemId });
902
+ }),
903
+ );
904
+
905
+ server.registerTool(
906
+ 'lantern_business_directory_save',
907
+ {
908
+ title: '新建或修改功能目录',
909
+ description:
910
+ '新建目录或修改目录名称、父目录、排序、菜单路径和入口。写入必须携带 expectedRevision。',
911
+ inputSchema: {
912
+ expectedRevision: z.number().int().nonnegative().optional(),
913
+ systemId: z.string(),
914
+ directoryId: z.string().optional().describe('为空时新建目录'),
915
+ name: z.string().optional(),
916
+ parentId: z.string().optional().describe('根目录为空字符串'),
917
+ order: z.number().int().nonnegative().optional(),
918
+ source: z.enum(['menu', 'ai', 'manual']).optional(),
919
+ menuPath: z.array(z.string()).optional(),
920
+ entryUrl: z.string().optional(),
921
+ evidence: businessEvidenceInput,
922
+ },
923
+ annotations: { destructiveHint: true },
924
+ },
925
+ protectedTool(async (args) => {
926
+ const revision = await requireBusinessMapRevision(apiBase, args.expectedRevision);
927
+ const directory = {
928
+ ...(args.name !== undefined ? { name: args.name } : {}),
929
+ ...(args.parentId !== undefined ? { parentId: args.parentId } : {}),
930
+ ...(args.order !== undefined ? { order: args.order } : {}),
931
+ ...(args.source !== undefined ? { source: args.source } : {}),
932
+ ...(args.menuPath !== undefined ? { menuPath: args.menuPath } : {}),
933
+ ...(args.entryUrl !== undefined ? { entryUrl: args.entryUrl } : {}),
934
+ ...(args.evidence !== undefined ? { evidence: args.evidence } : {}),
935
+ };
936
+ let data;
937
+ if (args.directoryId) {
938
+ data = await apiRequest(
939
+ apiBase,
940
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(args.systemId)}/directories/${encodeURIComponent(args.directoryId)}`,
941
+ { method: 'PUT', body: { revision, directory } },
942
+ );
943
+ } else {
944
+ if (!String(args.name || '').trim()) throw new BridgeError('新建目录必须提供 name');
945
+ data = await apiRequest(
946
+ apiBase,
947
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(args.systemId)}/directories`,
948
+ { method: 'POST', body: { revision, directory } },
949
+ );
950
+ }
951
+ return toolResult({
952
+ ok: true,
953
+ revision: data.store.revision,
954
+ directory: data.directory,
955
+ });
956
+ }),
957
+ );
958
+
959
+ server.registerTool(
960
+ 'lantern_business_tree_move',
961
+ {
962
+ title: '移动或排序业务目录节点',
963
+ description:
964
+ '移动目录或功能到目标父级,并可通过 beforeId 指定插入位置。写入必须携带 expectedRevision。',
965
+ inputSchema: {
966
+ expectedRevision: z.number().int().nonnegative().optional(),
967
+ systemId: z.string(),
968
+ kind: z.enum(['directory', 'function']),
969
+ id: z.string(),
970
+ parentId: z.string().describe('目标父目录;根级为空字符串'),
971
+ beforeId: z.string().optional().describe('插入到该同级节点之前;省略则追加'),
972
+ },
973
+ annotations: { destructiveHint: true },
974
+ },
975
+ protectedTool(async ({ expectedRevision, systemId, kind, id, parentId, beforeId }) => {
976
+ const revision = await requireBusinessMapRevision(apiBase, expectedRevision);
977
+ const data = await apiRequest(
978
+ apiBase,
979
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}/tree/move`,
980
+ {
981
+ method: 'POST',
982
+ body: { revision, kind, id, parentId, ...(beforeId ? { beforeId } : {}) },
983
+ },
984
+ );
985
+ return toolResult({ ok: true, revision: data.store.revision });
986
+ }),
987
+ );
988
+
989
+ server.registerTool(
990
+ 'lantern_business_directory_delete',
991
+ {
992
+ title: '删除功能目录',
993
+ description:
994
+ '删除目录。非空目录首次调用会返回 impact;确认级联删除后传 cascade=true。写入必须携带 expectedRevision。',
995
+ inputSchema: {
996
+ expectedRevision: z.number().int().nonnegative().optional(),
997
+ systemId: z.string(),
998
+ directoryId: z.string(),
999
+ cascade: z.boolean().optional(),
1000
+ },
1001
+ annotations: { destructiveHint: true },
1002
+ },
1003
+ protectedTool(async ({ expectedRevision, systemId, directoryId, cascade = false }) => {
1004
+ const revision = await requireBusinessMapRevision(apiBase, expectedRevision);
1005
+ const data = await apiRequest(
1006
+ apiBase,
1007
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}/directories/${encodeURIComponent(directoryId)}`,
1008
+ { method: 'DELETE', body: { revision, cascade } },
1009
+ );
1010
+ return toolResult({
1011
+ ok: true,
1012
+ revision: data.store.revision,
1013
+ deletedDirectoryId: directoryId,
1014
+ ...(data.impact ? { impact: data.impact } : {}),
1015
+ });
1016
+ }),
1017
+ );
1018
+
1019
+ server.registerTool(
1020
+ 'lantern_business_function_save',
1021
+ {
1022
+ title: '新建或修改业务功能',
1023
+ description:
1024
+ '新建功能或修改所属目录、名称、作用、角色、规则、证据等字段。写入必须携带 expectedRevision。',
1025
+ inputSchema: {
1026
+ expectedRevision: z.number().int().nonnegative().optional(),
1027
+ systemId: z.string(),
1028
+ functionId: z.string().optional().describe('为空时新建功能'),
1029
+ name: z.string().optional(),
1030
+ code: z.string().optional(),
1031
+ directoryId: z.string().optional(),
1032
+ order: z.number().int().nonnegative().optional(),
1033
+ domain: z.string().optional(),
1034
+ module: z.string().optional(),
1035
+ status: z.enum(['在用', '停用', '草稿']).optional(),
1036
+ purpose: z.string().optional(),
1037
+ roles: z.array(z.string()).optional(),
1038
+ entry: z.string().optional(),
1039
+ inputs: z.array(z.string()).optional(),
1040
+ outputs: z.array(z.string()).optional(),
1041
+ rules: z.array(z.string()).optional(),
1042
+ writes: z.array(z.string()).optional(),
1043
+ exceptions: z.array(z.string()).optional(),
1044
+ implementation: z.array(z.string()).optional(),
1045
+ evidence: businessEvidenceInput,
1046
+ confidence: z.enum(['high', 'medium', 'low']).optional(),
1047
+ source: z.enum(['ai', 'manual', 'mixed']).optional(),
1048
+ confirmed: z.boolean().optional(),
1049
+ lockedFields: z.array(z.string()).optional(),
1050
+ },
1051
+ annotations: { destructiveHint: true },
1052
+ },
1053
+ protectedTool(async (args) => {
1054
+ const revision = await requireBusinessMapRevision(apiBase, args.expectedRevision);
1055
+ const fn = {
1056
+ ...(args.name !== undefined ? { name: args.name } : {}),
1057
+ ...(args.code !== undefined ? { code: args.code } : {}),
1058
+ ...(args.directoryId !== undefined ? { directoryId: args.directoryId } : {}),
1059
+ ...(args.order !== undefined ? { order: args.order } : {}),
1060
+ ...(args.domain !== undefined ? { domain: args.domain } : {}),
1061
+ ...(args.module !== undefined ? { module: args.module } : {}),
1062
+ ...(args.status !== undefined ? { status: args.status } : {}),
1063
+ ...(args.purpose !== undefined ? { purpose: args.purpose } : {}),
1064
+ ...(args.roles !== undefined ? { roles: args.roles } : {}),
1065
+ ...(args.entry !== undefined ? { entry: args.entry } : {}),
1066
+ ...(args.inputs !== undefined ? { inputs: args.inputs } : {}),
1067
+ ...(args.outputs !== undefined ? { outputs: args.outputs } : {}),
1068
+ ...(args.rules !== undefined ? { rules: args.rules } : {}),
1069
+ ...(args.writes !== undefined ? { writes: args.writes } : {}),
1070
+ ...(args.exceptions !== undefined ? { exceptions: args.exceptions } : {}),
1071
+ ...(args.implementation !== undefined ? { implementation: args.implementation } : {}),
1072
+ ...(args.evidence !== undefined ? { evidence: args.evidence } : {}),
1073
+ ...(args.confidence !== undefined ? { confidence: args.confidence } : {}),
1074
+ ...(args.source !== undefined ? { source: args.source } : {}),
1075
+ ...(args.confirmed !== undefined ? { confirmed: args.confirmed } : {}),
1076
+ ...(args.lockedFields !== undefined ? { lockedFields: args.lockedFields } : {}),
1077
+ };
1078
+ let data;
1079
+ if (args.functionId) {
1080
+ data = await apiRequest(
1081
+ apiBase,
1082
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(args.systemId)}/functions/${encodeURIComponent(args.functionId)}`,
1083
+ { method: 'PUT', body: { revision, function: fn } },
1084
+ );
1085
+ } else {
1086
+ if (!String(args.name || '').trim()) throw new BridgeError('新建功能必须提供 name');
1087
+ data = await apiRequest(
1088
+ apiBase,
1089
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(args.systemId)}/functions`,
1090
+ { method: 'POST', body: { revision, function: fn } },
1091
+ );
1092
+ }
1093
+ return toolResult({ ok: true, revision: data.store.revision, item: data.item });
1094
+ }),
1095
+ );
1096
+
1097
+ server.registerTool(
1098
+ 'lantern_business_function_delete',
1099
+ {
1100
+ title: '删除业务功能',
1101
+ description: '删除功能,并清空业务流程中对该功能的引用。写入必须携带 expectedRevision。',
1102
+ inputSchema: {
1103
+ expectedRevision: z.number().int().nonnegative().optional(),
1104
+ systemId: z.string(),
1105
+ functionId: z.string(),
1106
+ },
1107
+ annotations: { destructiveHint: true },
1108
+ },
1109
+ protectedTool(async ({ expectedRevision, systemId, functionId }) => {
1110
+ const revision = await requireBusinessMapRevision(apiBase, expectedRevision);
1111
+ const data = await apiRequest(
1112
+ apiBase,
1113
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}/functions/${encodeURIComponent(functionId)}`,
1114
+ { method: 'DELETE', body: { revision } },
1115
+ );
1116
+ return toolResult({ ok: true, revision: data.store.revision, deletedFunctionId: functionId });
1117
+ }),
1118
+ );
1119
+
1120
+ server.registerTool(
1121
+ 'lantern_business_flow_save',
1122
+ {
1123
+ title: '新建或修改业务流程',
1124
+ description:
1125
+ '新建或修改业务流程及纵向步骤。系统步骤必须引用已存在功能;写入必须携带 expectedRevision。',
1126
+ inputSchema: {
1127
+ expectedRevision: z.number().int().nonnegative().optional(),
1128
+ systemId: z.string(),
1129
+ flowId: z.string().optional().describe('为空时新建流程'),
1130
+ name: z.string().optional(),
1131
+ result: z.string().optional(),
1132
+ status: z.enum(['健康', '待补全', '草稿']).optional(),
1133
+ steps: z
1134
+ .array(
1135
+ z.object({
1136
+ id: z.string().optional(),
1137
+ n: z.number().int().min(1).optional(),
1138
+ title: z.string(),
1139
+ role: z.string().optional(),
1140
+ system: z.string().optional(),
1141
+ functionId: z.string().optional(),
1142
+ input: z.string().optional(),
1143
+ output: z.string().optional(),
1144
+ next: z.string().optional(),
1145
+ branch: z.string().optional(),
1146
+ branchBroken: z.boolean().optional(),
1147
+ manual: z.boolean().optional(),
1148
+ dependencies: businessDependencyInput,
1149
+ evidence: businessEvidenceInput,
1150
+ }),
1151
+ )
1152
+ .optional(),
1153
+ evidence: businessEvidenceInput,
1154
+ },
1155
+ annotations: { destructiveHint: true },
1156
+ },
1157
+ protectedTool(async (args) => {
1158
+ const revision = await requireBusinessMapRevision(apiBase, args.expectedRevision);
1159
+ const flow = {
1160
+ ...(args.name !== undefined ? { name: args.name } : {}),
1161
+ ...(args.result !== undefined ? { result: args.result } : {}),
1162
+ ...(args.status !== undefined ? { status: args.status } : {}),
1163
+ ...(args.steps !== undefined ? { steps: args.steps } : {}),
1164
+ ...(args.evidence !== undefined ? { evidence: args.evidence } : {}),
1165
+ };
1166
+ let data;
1167
+ if (args.flowId) {
1168
+ data = await apiRequest(
1169
+ apiBase,
1170
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(args.systemId)}/flows/${encodeURIComponent(args.flowId)}`,
1171
+ { method: 'PUT', body: { revision, flow } },
1172
+ );
1173
+ } else {
1174
+ if (!String(args.name || '').trim()) throw new BridgeError('新建流程必须提供 name');
1175
+ data = await apiRequest(
1176
+ apiBase,
1177
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(args.systemId)}/flows`,
1178
+ { method: 'POST', body: { revision, flow } },
1179
+ );
1180
+ }
1181
+ return toolResult({ ok: true, revision: data.store.revision, item: data.item });
1182
+ }),
1183
+ );
1184
+
1185
+ server.registerTool(
1186
+ 'lantern_business_flow_delete',
1187
+ {
1188
+ title: '删除业务流程',
1189
+ description: '删除业务流程。写入必须携带 expectedRevision。',
1190
+ inputSchema: {
1191
+ expectedRevision: z.number().int().nonnegative().optional(),
1192
+ systemId: z.string(),
1193
+ flowId: z.string(),
1194
+ },
1195
+ annotations: { destructiveHint: true },
1196
+ },
1197
+ protectedTool(async ({ expectedRevision, systemId, flowId }) => {
1198
+ const revision = await requireBusinessMapRevision(apiBase, expectedRevision);
1199
+ const data = await apiRequest(
1200
+ apiBase,
1201
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}/flows/${encodeURIComponent(flowId)}`,
1202
+ { method: 'DELETE', body: { revision } },
1203
+ );
1204
+ return toolResult({ ok: true, revision: data.store.revision, deletedFlowId: flowId });
1205
+ }),
1206
+ );
1207
+
1208
+ server.registerTool(
1209
+ 'lantern_business_assistant_get',
1210
+ {
1211
+ title: '读取业务地图 AI 会话',
1212
+ description:
1213
+ '读取指定系统的持久化 AI 会话、当前草案、消息和增量日志。afterSeq 用于只返回新事件。',
1214
+ inputSchema: {
1215
+ systemId: z.string(),
1216
+ afterSeq: z.number().int().nonnegative().optional(),
1217
+ },
1218
+ annotations: { readOnlyHint: true },
1219
+ },
1220
+ protectedTool(async ({ systemId, afterSeq = 0 }) => {
1221
+ const data = await apiRequest(
1222
+ apiBase,
1223
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}/assistant`,
1224
+ );
1225
+ const session = data.session;
1226
+ return toolResult({
1227
+ ok: true,
1228
+ session: {
1229
+ ...session,
1230
+ events: (session?.events || []).filter(
1231
+ (event) => Number(event.seq) > Math.max(0, Number(afterSeq) || 0),
1232
+ ),
1233
+ },
1234
+ });
1235
+ }),
1236
+ );
1237
+
1238
+ server.registerTool(
1239
+ 'lantern_business_assistant_send',
1240
+ {
1241
+ title: '启动业务地图 AI 识别',
1242
+ description:
1243
+ '启动功能目录或业务流程识别回合,后台继续执行。使用 Lantern 当前模型配置,不接收模型密钥。',
1244
+ inputSchema: {
1245
+ expectedRevision: z.number().int().nonnegative().optional(),
1246
+ systemId: z.string(),
1247
+ phase: z.enum(['directory', 'flow']),
1248
+ message: z.string().min(1),
1249
+ refresh: z.boolean().optional().describe('是否强制重新扫描菜单和页面'),
1250
+ maxPages: z.number().int().min(1).max(300).optional(),
1251
+ },
1252
+ annotations: { destructiveHint: true, openWorldHint: true },
1253
+ },
1254
+ protectedTool(async ({ expectedRevision, systemId, phase, message, refresh, maxPages }) => {
1255
+ const revision = await requireBusinessMapRevision(apiBase, expectedRevision);
1256
+ const settings = await loadBusinessModelSettings(apiBase);
1257
+ const data = await apiRequest(
1258
+ apiBase,
1259
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}/assistant/messages`,
1260
+ {
1261
+ method: 'POST',
1262
+ body: {
1263
+ revision,
1264
+ phase,
1265
+ message,
1266
+ ...(refresh !== undefined ? { refresh } : {}),
1267
+ ...(maxPages !== undefined ? { maxPages } : {}),
1268
+ settings,
1269
+ },
1270
+ timeoutMs: 60_000,
1271
+ },
1272
+ );
1273
+ return toolResult({ ok: true, session: data.session });
1274
+ }),
1275
+ );
1276
+
1277
+ server.registerTool(
1278
+ 'lantern_business_assistant_stop',
1279
+ {
1280
+ title: '停止业务地图 AI 识别',
1281
+ description: '停止当前系统的 AI 回合,保留会话历史和草案。',
1282
+ inputSchema: { systemId: z.string() },
1283
+ annotations: { destructiveHint: true },
1284
+ },
1285
+ protectedTool(async ({ systemId }) => {
1286
+ const data = await apiRequest(
1287
+ apiBase,
1288
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}/assistant/stop`,
1289
+ { method: 'POST', body: {} },
1290
+ );
1291
+ return toolResult({ ok: true, session: data.session });
1292
+ }),
1293
+ );
1294
+
1295
+ server.registerTool(
1296
+ 'lantern_business_assistant_reset',
1297
+ {
1298
+ title: '重置业务地图 AI 会话',
1299
+ description: '清空指定系统的消息、日志和草案,不修改已经应用的正式业务地图。',
1300
+ inputSchema: { systemId: z.string() },
1301
+ annotations: { destructiveHint: true },
1302
+ },
1303
+ protectedTool(async ({ systemId }) => {
1304
+ const data = await apiRequest(
1305
+ apiBase,
1306
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}/assistant/reset`,
1307
+ { method: 'POST', body: {} },
1308
+ );
1309
+ return toolResult({ ok: true, session: data.session });
1310
+ }),
1311
+ );
1312
+
1313
+ server.registerTool(
1314
+ 'lantern_business_assistant_apply',
1315
+ {
1316
+ title: '应用业务地图 AI 草案',
1317
+ description: '把当前等待确认的目录或流程草案写入正式地图。必须携带 expectedRevision。',
1318
+ inputSchema: {
1319
+ systemId: z.string(),
1320
+ expectedRevision: z.number().int().nonnegative().optional(),
1321
+ },
1322
+ annotations: { destructiveHint: true },
1323
+ },
1324
+ protectedTool(async ({ systemId, expectedRevision }) => {
1325
+ const revision = await requireBusinessMapRevision(apiBase, expectedRevision);
1326
+ const data = await apiRequest(
1327
+ apiBase,
1328
+ `${BUSINESS_MAP_API}/systems/${encodeURIComponent(systemId)}/assistant/apply`,
1329
+ { method: 'POST', body: { revision } },
1330
+ );
1331
+ return toolResult({
1332
+ ok: true,
1333
+ session: data.session,
1334
+ revision: data.store?.revision ?? revision + 1,
1335
+ });
1336
+ }),
1337
+ );
1338
+
1339
+ server.registerTool(
1340
+ 'lantern_business_assistant_wait',
1341
+ {
1342
+ title: '等待业务地图 AI 回合',
1343
+ description: '轮询当前 AI 会话,直到结束或超时;返回最新状态和 afterSeq 之后的日志。',
1344
+ inputSchema: {
1345
+ systemId: z.string(),
1346
+ timeoutMs: z.number().int().min(1000).max(55_000).optional(),
1347
+ afterSeq: z.number().int().nonnegative().optional(),
1348
+ },
1349
+ annotations: { readOnlyHint: true, openWorldHint: true },
1350
+ },
1351
+ protectedTool(async ({ systemId, timeoutMs = 25_000, afterSeq = 0 }) =>
1352
+ toolResult(await waitForBusinessAssistant(apiBase, systemId, timeoutMs, afterSeq)),
1353
+ ),
1354
+ );
1355
+
1356
+ server.registerTool(
1357
+ 'lantern_case_execution_files',
1358
+ {
1359
+ title: '列出可执行用例文件',
1360
+ description: '列出用例管理中的用例文件、用例数量、是否具备状态和实际结果列。',
1361
+ annotations: { readOnlyHint: true },
1362
+ },
1363
+ protectedTool(async () => toolResult(await apiRequest(apiBase, `${CASE_EXECUTION_API}/files`))),
1364
+ );
1365
+
1366
+ server.registerTool(
1367
+ 'lantern_case_execution_cases',
1368
+ {
1369
+ title: '读取用例执行明细',
1370
+ description: '读取指定用例文件的字段、单条用例和当前执行状态。',
1371
+ inputSchema: { casePath: z.string() },
1372
+ annotations: { readOnlyHint: true },
1373
+ },
1374
+ protectedTool(async ({ casePath }) =>
1375
+ toolResult(
1376
+ await apiRequest(
1377
+ apiBase,
1378
+ `${CASE_EXECUTION_API}/cases?path=${encodeURIComponent(casePath)}`,
1379
+ ),
1380
+ ),
1381
+ ),
1382
+ );
1383
+
1384
+ server.registerTool(
1385
+ 'lantern_case_execution_login_start',
1386
+ {
1387
+ title: '打开用例执行登录页面',
1388
+ description: '打开目标系统登录窗口,由用户完成登录;工具不接收账号密码。',
1389
+ inputSchema: { url: z.string() },
1390
+ annotations: { destructiveHint: true, openWorldHint: true },
1391
+ },
1392
+ protectedTool(async ({ url }) =>
1393
+ toolResult(
1394
+ await apiRequest(apiBase, `${CASE_EXECUTION_API}/auth/start`, {
1395
+ method: 'POST',
1396
+ body: { url },
1397
+ timeoutMs: 60_000,
1398
+ }),
1399
+ ),
1400
+ ),
1401
+ );
1402
+
1403
+ server.registerTool(
1404
+ 'lantern_case_execution_login_complete',
1405
+ {
1406
+ title: '保存用例执行登录态',
1407
+ description: '用户完成登录后保存当前目标的浏览器 storageState。',
1408
+ annotations: { destructiveHint: true, openWorldHint: true },
1409
+ },
1410
+ protectedTool(async () =>
1411
+ toolResult(
1412
+ await apiRequest(apiBase, `${CASE_EXECUTION_API}/auth/complete`, {
1413
+ method: 'POST',
1414
+ body: {},
1415
+ timeoutMs: 60_000,
1416
+ }),
1417
+ ),
1418
+ ),
1419
+ );
1420
+
1421
+ server.registerTool(
1422
+ 'lantern_case_execution_start',
1423
+ {
1424
+ title: '启动单条用例 AI 执行',
1425
+ description:
1426
+ '按用例文件路径和行号启动单条 AI 浏览器执行。只使用已有登录态路径,不接收账号密码。',
1427
+ inputSchema: {
1428
+ casePath: z.string(),
1429
+ rowIndex: z.number().int().nonnegative(),
1430
+ url: z.string(),
1431
+ storageStatePath: z.string().optional(),
1432
+ },
1433
+ annotations: { destructiveHint: true, openWorldHint: true },
1434
+ },
1435
+ protectedTool(async (args) =>
1436
+ toolResult(
1437
+ await apiRequest(apiBase, `${CASE_EXECUTION_API}/runs`, {
1438
+ method: 'POST',
1439
+ body: args,
1440
+ timeoutMs: 60_000,
1441
+ }),
1442
+ ),
1443
+ ),
1444
+ );
1445
+
1446
+ server.registerTool(
1447
+ 'lantern_case_execution_get',
1448
+ {
1449
+ title: '读取用例执行会话',
1450
+ description: '读取单条用例执行状态、进度、事件和待确认结果。',
1451
+ inputSchema: { runId: z.string() },
1452
+ annotations: { readOnlyHint: true },
1453
+ },
1454
+ protectedTool(async ({ runId }) =>
1455
+ toolResult(
1456
+ await apiRequest(apiBase, `${CASE_EXECUTION_API}/runs/${encodeURIComponent(runId)}`),
1457
+ ),
1458
+ ),
1459
+ );
1460
+
1461
+ server.registerTool(
1462
+ 'lantern_case_execution_wait',
1463
+ {
1464
+ title: '等待用例执行回合',
1465
+ description: '轮询单条用例执行,直到结束或超时,并返回 afterSeq 之后的日志。',
1466
+ inputSchema: {
1467
+ runId: z.string(),
1468
+ timeoutMs: z.number().int().min(1000).max(55_000).optional(),
1469
+ afterSeq: z.number().int().nonnegative().optional(),
1470
+ },
1471
+ annotations: { readOnlyHint: true, openWorldHint: true },
1472
+ },
1473
+ protectedTool(async ({ runId, timeoutMs = 25_000, afterSeq = 0 }) =>
1474
+ toolResult(await waitForCaseExecution(apiBase, runId, timeoutMs, afterSeq)),
1475
+ ),
1476
+ );
1477
+
1478
+ server.registerTool(
1479
+ 'lantern_case_execution_stop',
1480
+ {
1481
+ title: '停止用例执行',
1482
+ description: '停止当前单条用例执行并保留已有日志和截图。',
1483
+ inputSchema: { runId: z.string() },
1484
+ annotations: { destructiveHint: true },
1485
+ },
1486
+ protectedTool(async ({ runId }) =>
1487
+ toolResult(
1488
+ await apiRequest(apiBase, `${CASE_EXECUTION_API}/runs/${encodeURIComponent(runId)}/stop`, {
1489
+ method: 'POST',
1490
+ body: {},
1491
+ }),
1492
+ ),
1493
+ ),
1494
+ );
1495
+
1496
+ server.registerTool(
1497
+ 'lantern_case_execution_apply',
1498
+ {
1499
+ title: '确认并写回用例执行结果',
1500
+ description:
1501
+ '用户确认后,把状态和实际结果写回用例文件已有的执行列;文件被外部修改时拒绝覆盖。',
1502
+ inputSchema: {
1503
+ runId: z.string(),
1504
+ status: z.enum(['待验证', '通过', '不通过', '阻塞', '跳过']),
1505
+ actualResult: z.string(),
1506
+ executor: z.string().optional(),
1507
+ defectNo: z.string().optional(),
1508
+ },
1509
+ annotations: { destructiveHint: true },
1510
+ },
1511
+ protectedTool(async ({ runId, ...values }) =>
1512
+ toolResult(
1513
+ await apiRequest(apiBase, `${CASE_EXECUTION_API}/runs/${encodeURIComponent(runId)}/apply`, {
1514
+ method: 'POST',
1515
+ body: values,
1516
+ }),
1517
+ ),
1518
+ ),
1519
+ );
1520
+
1521
+ server.registerTool(
1522
+ 'lantern_case_execution_sync_stats',
1523
+ {
1524
+ title: '同步用例执行统计',
1525
+ description:
1526
+ '按用例文件生成统计预览,并在用户确认后同步到现有用例执行统计;已有手工统计不自动覆盖。',
1527
+ inputSchema: {
1528
+ casePath: z.string(),
1529
+ project: z.string(),
1530
+ date: z.string(),
1531
+ mode: z.enum(['preview', 'skip', 'overwrite']),
1532
+ },
1533
+ annotations: { destructiveHint: true },
1534
+ },
1535
+ protectedTool(async (args) =>
1536
+ toolResult(
1537
+ await apiRequest(apiBase, `${CASE_EXECUTION_API}/stats/sync`, {
1538
+ method: 'POST',
1539
+ body: args,
1540
+ }),
1541
+ ),
1542
+ ),
1543
+ );
1544
+
1545
+ server.registerTool(
1546
+ 'lantern_requirement_breakdown_list',
1547
+ {
1548
+ title: '需求拆解库列表',
1549
+ description:
1550
+ '列出实际 XMind 拆解文件及项目、迭代、来源、文件状态,可按关键词、项目、迭代和类型过滤。',
1551
+ inputSchema: {
1552
+ query: z.string().optional(),
1553
+ project: z.string().optional(),
1554
+ iteration: z.string().optional(),
1555
+ kind: z.enum(['generated', 'uploaded']).optional(),
1556
+ },
1557
+ annotations: { readOnlyHint: true },
1558
+ },
1559
+ protectedTool(async ({ query = '', project = '', iteration = '', kind = '' }) => {
1560
+ const data = await loadRequirementBreakdownList(apiBase);
1561
+ const needle = String(query).trim().toLowerCase();
1562
+ const entries = data.entries.filter(
1563
+ (entry) =>
1564
+ (!project || entry.project === project) &&
1565
+ (!iteration || entry.iteration === iteration) &&
1566
+ (!kind || entry.kind === kind) &&
1567
+ (!needle ||
1568
+ [
1569
+ entry.title,
1570
+ entry.fileName,
1571
+ entry.project,
1572
+ entry.iteration,
1573
+ entry.sourceTitle,
1574
+ entry.sourcePath,
1575
+ entry.note,
1576
+ ]
1577
+ .join(' ')
1578
+ .toLowerCase()
1579
+ .includes(needle)),
1580
+ );
1581
+ return toolResult({
1582
+ ok: true,
1583
+ revision: data.revision,
1584
+ count: entries.length,
1585
+ entries,
1586
+ });
1587
+ }),
1588
+ );
1589
+
1590
+ server.registerTool(
1591
+ 'lantern_requirement_breakdown_get',
1592
+ {
1593
+ title: '读取需求拆解条目',
1594
+ description: '读取单条拆解库记录;可选解析最新 XMind 文件,返回层级文本和主题列表。',
1595
+ inputSchema: {
1596
+ entryId: z.string(),
1597
+ includeContent: z.boolean().optional(),
1598
+ },
1599
+ annotations: { readOnlyHint: true },
1600
+ },
1601
+ protectedTool(async ({ entryId, includeContent = false }) => {
1602
+ const data = await apiRequest(
1603
+ apiBase,
1604
+ `${REQ_BREAKDOWN_API}/entries/${encodeURIComponent(entryId)}${includeContent ? '?includeContent=1' : ''}`,
1605
+ );
1606
+ return toolResult({ ok: true, ...data });
1607
+ }),
1608
+ );
1609
+
1610
+ server.registerTool(
1611
+ 'lantern_requirement_breakdown_import',
1612
+ {
1613
+ title: '导入需求拆解 XMind',
1614
+ description: '把 Codex 可访问的本地 .xmind 导入需求拆解库,按现有命名规则生成标题。',
1615
+ inputSchema: {
1616
+ filePath: z.string(),
1617
+ expectedRevision: z.number().int().nonnegative().optional(),
1618
+ project: z.string().optional(),
1619
+ iteration: z.string().optional(),
1620
+ note: z.string().optional(),
1621
+ },
1622
+ annotations: { destructiveHint: true },
1623
+ },
1624
+ protectedTool(async ({ filePath, expectedRevision, project, iteration, note }) => {
1625
+ const revision = await requireRequirementBreakdownRevision(apiBase, expectedRevision);
1626
+ const absolute = path.resolve(String(filePath || ''));
1627
+ const stat = fs.statSync(absolute);
1628
+ if (!stat.isFile() || !/\.xmind$/i.test(absolute))
1629
+ throw new BridgeError('filePath 必须是 .xmind 文件');
1630
+ const content = fs.readFileSync(absolute);
1631
+ return toolResult(
1632
+ await apiRequest(apiBase, `${REQ_BREAKDOWN_API}/import`, {
1633
+ method: 'POST',
1634
+ body: {
1635
+ name: path.basename(absolute),
1636
+ contentBase64: content.toString('base64'),
1637
+ expectedRevision: revision,
1638
+ ...(project ? { project } : {}),
1639
+ ...(iteration ? { iteration } : {}),
1640
+ ...(note ? { note } : {}),
1641
+ },
1642
+ timeoutMs: 60_000,
1643
+ }),
1644
+ );
1645
+ }),
1646
+ );
1647
+
1648
+ server.registerTool(
1649
+ 'lantern_requirement_breakdown_backfill_candidates',
1650
+ {
1651
+ title: '读取可补录历史分析',
1652
+ description:
1653
+ '列出已包含原文结构的需求分析,并标记是否已入库;用于选择 analysisIds 后再补录。',
1654
+ inputSchema: {},
1655
+ annotations: { readOnlyHint: true },
1656
+ },
1657
+ protectedTool(async () => {
1658
+ const data = await apiRequest(apiBase, `${REQ_BREAKDOWN_API}/backfill`);
1659
+ return toolResult({ ok: true, ...data });
1660
+ }),
1661
+ );
1662
+
1663
+ server.registerTool(
1664
+ 'lantern_requirement_breakdown_record_analysis',
1665
+ {
1666
+ title: '历史分析补录到拆解库',
1667
+ description: '从已有且包含原文结构的需求分析生成 XMind 文件并加入拆解库。',
1668
+ inputSchema: {
1669
+ analysisIds: z.array(z.string()).min(1),
1670
+ expectedRevision: z.number().int().nonnegative().optional(),
1671
+ },
1672
+ annotations: { destructiveHint: true },
1673
+ },
1674
+ protectedTool(async ({ analysisIds, expectedRevision }) => {
1675
+ const revision = await requireRequirementBreakdownRevision(apiBase, expectedRevision);
1676
+ return toolResult(
1677
+ await apiRequest(apiBase, `${REQ_BREAKDOWN_API}/backfill`, {
1678
+ method: 'POST',
1679
+ body: { analysisIds, expectedRevision: revision },
1680
+ timeoutMs: 90_000,
1681
+ }),
1682
+ );
1683
+ }),
1684
+ );
1685
+
1686
+ server.registerTool(
1687
+ 'lantern_requirement_breakdown_retry',
1688
+ {
1689
+ title: '重新生成需求拆解 XMind',
1690
+ description: '按原需求分析重新生成缺失或损坏的自动拆解文件。',
1691
+ inputSchema: {
1692
+ entryId: z.string(),
1693
+ expectedRevision: z.number().int().nonnegative().optional(),
1694
+ },
1695
+ annotations: { destructiveHint: true },
1696
+ },
1697
+ protectedTool(async ({ entryId, expectedRevision }) => {
1698
+ const revision = await requireRequirementBreakdownRevision(apiBase, expectedRevision);
1699
+ return toolResult(
1700
+ await apiRequest(
1701
+ apiBase,
1702
+ `${REQ_BREAKDOWN_API}/entries/${encodeURIComponent(entryId)}/retry`,
1703
+ { method: 'POST', body: { expectedRevision: revision }, timeoutMs: 60_000 },
1704
+ ),
1705
+ );
1706
+ }),
1707
+ );
1708
+
1709
+ server.registerTool(
1710
+ 'lantern_requirement_breakdown_update',
1711
+ {
1712
+ title: '修改需求拆解条目',
1713
+ description: '修改拆解库条目的标题或备注;标题变更会同步重命名本地 XMind。',
1714
+ inputSchema: {
1715
+ entryId: z.string(),
1716
+ expectedRevision: z.number().int().nonnegative().optional(),
1717
+ title: z.string().optional(),
1718
+ note: z.string().optional(),
1719
+ },
1720
+ annotations: { destructiveHint: true },
1721
+ },
1722
+ protectedTool(async ({ entryId, expectedRevision, title, note }) => {
1723
+ const revision = await requireRequirementBreakdownRevision(apiBase, expectedRevision);
1724
+ return toolResult(
1725
+ await apiRequest(apiBase, `${REQ_BREAKDOWN_API}/entries/${encodeURIComponent(entryId)}`, {
1726
+ method: 'PUT',
1727
+ body: {
1728
+ expectedRevision: revision,
1729
+ ...(title !== undefined ? { title } : {}),
1730
+ ...(note !== undefined ? { note } : {}),
1731
+ },
1732
+ }),
1733
+ );
1734
+ }),
1735
+ );
1736
+
1737
+ server.registerTool(
1738
+ 'lantern_requirement_breakdown_open',
1739
+ {
1740
+ title: '本地打开需求拆解 XMind',
1741
+ description: '用系统默认 XMind 程序打开拆解库条目。',
1742
+ inputSchema: { entryId: z.string() },
1743
+ annotations: { openWorldHint: true },
1744
+ },
1745
+ protectedTool(async ({ entryId }) =>
1746
+ toolResult(
1747
+ await apiRequest(
1748
+ apiBase,
1749
+ `${REQ_BREAKDOWN_API}/entries/${encodeURIComponent(entryId)}/open`,
1750
+ { method: 'POST', body: {} },
1751
+ ),
1752
+ ),
1753
+ ),
1754
+ );
1755
+
1756
+ server.registerTool(
1757
+ 'lantern_requirement_breakdown_delete',
1758
+ {
1759
+ title: '删除需求拆解条目',
1760
+ description: '删除拆解库记录,并把对应 XMind 文件移入系统废纸篓。',
1761
+ inputSchema: {
1762
+ entryId: z.string(),
1763
+ expectedRevision: z.number().int().nonnegative().optional(),
1764
+ },
1765
+ annotations: { destructiveHint: true },
1766
+ },
1767
+ protectedTool(async ({ entryId, expectedRevision }) => {
1768
+ const revision = await requireRequirementBreakdownRevision(apiBase, expectedRevision);
1769
+ return toolResult(
1770
+ await apiRequest(apiBase, `${REQ_BREAKDOWN_API}/entries/${encodeURIComponent(entryId)}`, {
1771
+ method: 'DELETE',
1772
+ body: { expectedRevision: revision },
1773
+ }),
1774
+ );
1775
+ }),
1776
+ );
1777
+
1778
+ server.registerTool(
1779
+ 'lantern_mcp_tools',
1780
+ {
1781
+ title: '查询 Lantern 外接 MCP 工具',
1782
+ description:
1783
+ '发现当前 Lantern 活动空间已连接的外接 MCP 工具(包括腾讯文档),返回真实工具名、inputSchema、说明和连接错误。可按服务器或关键词筛选。先读取参数定义,再用 lantern_mcp_call 调用;不需要另配连接器或复制凭据。',
1784
+ inputSchema: {
1785
+ server: z.string().optional().describe('服务器名称,例如 tencent-docs'),
1786
+ query: z.string().optional().describe('工具名或说明中的关键词'),
1787
+ },
1788
+ annotations: { readOnlyHint: true, openWorldHint: true },
1789
+ },
1790
+ protectedTool(async ({ server: serverName, query }) => {
1791
+ const data = await apiRequest(apiBase, '/__tb_mcp/tools', { timeoutMs: 90_000 });
1792
+ const keyword = String(query || '')
1793
+ .trim()
1794
+ .toLowerCase();
1795
+ const tools = (data.tools || []).filter(
1796
+ (tool) =>
1797
+ (!serverName || tool.server === serverName) &&
1798
+ (!keyword || `${tool.name} ${tool.description || ''}`.toLowerCase().includes(keyword)),
1799
+ );
1800
+ return toolResult({ ...data, tools, count: tools.length });
1801
+ }),
1802
+ );
1803
+
1804
+ server.registerTool(
1805
+ 'lantern_mcp_call',
1806
+ {
1807
+ title: '调用 Lantern 外接 MCP 工具',
1808
+ description:
1809
+ '通过 Lantern 现有连接调用当前活动空间的外接 MCP,复用该空间凭据和远端权限。必须先用 lantern_mcp_tools 查询真实名称及 inputSchema;arguments 按该定义填写。支持读取和写入,写入须符合用户授权;缺陷提交优先走 lantern_defect_* 草稿和回执流程。返回远端原始内容、结构化结果或错误,不自动重试。',
1810
+ inputSchema: {
1811
+ name: z.string().min(1).describe('lantern_mcp_tools 返回的完整工具名'),
1812
+ arguments: z.record(z.string(), z.unknown()).default({}),
1813
+ },
1814
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
1815
+ },
1816
+ protectedTool(async ({ name, arguments: args }) => {
1817
+ // 重新发现以服从活动空间和配置变化,不允许猜名称绕过当前工具目录。
1818
+ const listed = await apiRequest(apiBase, '/__tb_mcp/tools', { timeoutMs: 90_000 });
1819
+ if (!(listed.tools || []).some((tool) => tool.name === name)) {
1820
+ throw new BridgeError('当前空间没有这个 MCP 工具;请重新调用 lantern_mcp_tools', 404, {
1821
+ errors: listed.errors || [],
1822
+ });
1823
+ }
1824
+ let result;
1825
+ try {
1826
+ result = await apiRequest(apiBase, '/__tb_mcp/call', {
1827
+ method: 'POST',
1828
+ body: { name, arguments: args },
1829
+ timeoutMs: 90_000,
1830
+ });
1831
+ } catch (error) {
1832
+ if (!(error instanceof BridgeError) || !error.details?.isError) throw error;
1833
+ result = error.details;
1834
+ }
1835
+ return {
1836
+ content: Array.isArray(result.content)
1837
+ ? result.content
1838
+ : [{ type: 'text', text: result.text || JSON.stringify(result) }],
1839
+ ...(result.structuredContent ? { structuredContent: result.structuredContent } : {}),
1840
+ isError: Boolean(result.isError || result.ok === false),
1841
+ };
1842
+ }),
1843
+ );
1844
+
1845
+ server.registerTool(
1846
+ 'lantern_requirement_prepare',
1847
+ {
1848
+ title: '准备需求分析工作区',
1849
+ description:
1850
+ '启用需求文档库、需求分析、用户故事审查和测试点插件,补种技能并迁移为当前空间技能。首次导入或分析需求前调用;重复调用无副作用。',
1851
+ annotations: { destructiveHint: true },
1852
+ },
1853
+ protectedTool(async () => {
1854
+ const prepared = await prepareRequirementWorkflow(apiBase);
1855
+ return toolResult(
1856
+ { ok: true, ...prepared },
1857
+ prepared.changed ? '已准备需求分析工作区。' : '需求分析工作区已就绪。',
1858
+ );
1859
+ }),
1860
+ );
1861
+
1862
+ server.registerTool(
1863
+ 'lantern_skill_list',
1864
+ {
1865
+ title: '列出技能',
1866
+ description: '列出当前空间技能、内部变体、启用状态、插件推荐关系和版本。',
1867
+ inputSchema: {
1868
+ query: z.string().optional().describe('按名称、描述或变体过滤'),
1869
+ includeDisabled: z.boolean().optional().describe('是否包含已停用技能,默认 false'),
1870
+ },
1871
+ annotations: { readOnlyHint: true },
1872
+ },
1873
+ protectedTool(async ({ query = '', includeDisabled = false }) => {
1874
+ const needle = String(query).trim().toLowerCase();
1875
+ const skills = (await listSpaceSkills(apiBase)).filter(
1876
+ (item) =>
1877
+ (includeDisabled || item.active !== false) &&
1878
+ (!needle ||
1879
+ `${item.name} ${item.variant} ${item.description}`.toLowerCase().includes(needle)),
1880
+ );
1881
+ return toolResult({ ok: true, count: skills.length, skills });
1882
+ }),
1883
+ );
1884
+
1885
+ server.registerTool(
1886
+ 'lantern_skill_load',
1887
+ {
1888
+ title: '加载技能',
1889
+ description: '按技能 ID 或当前空间内旧提示词路径加载完整技能规则与流程。',
1890
+ inputSchema: {
1891
+ id: z.string().optional().describe('技能 ID,可带 space: 前缀'),
1892
+ legacyPath: z.string().optional().describe('旧提示词文件名,例如 需求分析提示词.md'),
1893
+ },
1894
+ annotations: { readOnlyHint: true },
1895
+ },
1896
+ protectedTool(async ({ id = '', legacyPath = '' }) => {
1897
+ let resolved = id;
1898
+ if (!resolved && legacyPath) {
1899
+ const entry = await findSpaceSkillByLegacy(apiBase, legacyPath);
1900
+ if (!entry) throw new BridgeError(`未找到技能:${legacyPath}`, 404);
1901
+ resolved = entry.id;
1902
+ }
1903
+ if (!resolved) throw new BridgeError('id 或 legacyPath 至少需要一个');
1904
+ return toolResult({ ok: true, skill: await readSpaceSkill(apiBase, resolved) });
1905
+ }),
1906
+ );
1907
+
1908
+ server.registerTool(
1909
+ 'lantern_skill_validate',
1910
+ {
1911
+ title: '校验技能输出',
1912
+ description:
1913
+ '使用 Lantern 技能校验器检查 rows、columns、sourceIds、编号、优先级、统计和章节等结构。',
1914
+ inputSchema: {
1915
+ id: z.string().describe('技能 ID'),
1916
+ input: z.record(z.string(), z.unknown()).describe('待校验的 JSON'),
1917
+ },
1918
+ annotations: { readOnlyHint: true },
1919
+ },
1920
+ protectedTool(async ({ id, input }) => {
1921
+ const data = await apiRequest(apiBase, SKILL_API, {
1922
+ method: 'POST',
1923
+ body: { action: 'validate', id, input },
1924
+ });
1925
+ return toolResult(data);
1926
+ }),
1927
+ );
1928
+
1929
+ server.registerTool(
1930
+ 'lantern_requirement_list',
1931
+ {
1932
+ title: '需求文档列表',
1933
+ description: '列出 Lantern 需求文档库中的文件夹与文件。',
1934
+ inputSchema: {
1935
+ path: z.string().optional().describe('相对目录,默认根目录'),
1936
+ },
1937
+ annotations: { readOnlyHint: true },
1938
+ },
1939
+ protectedTool(async ({ path: parent = '.' }) => {
1940
+ const entries = await listRequirementEntries(apiBase, parent);
1941
+ return toolResult({ ok: true, path: parent, entries });
1942
+ }),
1943
+ );
1944
+
1945
+ server.registerTool(
1946
+ 'lantern_requirement_import',
1947
+ {
1948
+ title: '导入需求文档',
1949
+ description:
1950
+ '把 Codex 可访问的本地需求文档复制到 Lantern 需求文档库。支持 md、txt、docx、csv、xlsx、xls。',
1951
+ inputSchema: {
1952
+ filePath: z.string().describe('本地文件绝对路径'),
1953
+ folder: z.string().optional().describe('需求文档库内相对目录,默认根目录'),
1954
+ overwrite: z.boolean().optional().describe('同名时是否覆盖,默认 false'),
1955
+ },
1956
+ annotations: { destructiveHint: true },
1957
+ },
1958
+ protectedTool(async ({ filePath, folder = '.', overwrite = false }) => {
1959
+ const absolute = path.resolve(String(filePath || ''));
1960
+ const stat = fs.statSync(absolute);
1961
+ if (!stat.isFile()) throw new BridgeError('filePath 不是文件');
1962
+ if (stat.size > MAX_IMPORT_BYTES) throw new BridgeError('需求文档超过 12MB');
1963
+ const ext = path.extname(absolute).toLowerCase();
1964
+ if (!ALLOWED_REQUIREMENT_EXT.has(ext)) {
1965
+ throw new BridgeError(`不支持的需求文档类型:${ext || '(无扩展名)'}`);
1966
+ }
1967
+ let name = path.basename(absolute);
1968
+ const entries = await listRequirementEntries(apiBase, folder);
1969
+ if (entries.some((entry) => entry.name === name) && !overwrite) {
1970
+ name = uniqueUploadName(entries, name, ext);
1971
+ }
1972
+ const content = fs.readFileSync(absolute);
1973
+ const uploaded = await apiRequest(apiBase, `/${DOC_API.slice(1)}/upload`, {
1974
+ method: 'POST',
1975
+ body: {
1976
+ name,
1977
+ parent: folder,
1978
+ contentBase64: content.toString('base64'),
1979
+ },
1980
+ timeoutMs: 60_000,
1981
+ });
1982
+ return toolResult({
1983
+ ok: true,
1984
+ sourcePath: uploaded.path,
1985
+ originalPath: absolute,
1986
+ name,
1987
+ size: content.length,
1988
+ sha256: sha256(content),
1989
+ renamed: name !== path.basename(absolute),
1990
+ });
1991
+ }),
1992
+ );
1993
+
1994
+ server.registerTool(
1995
+ 'lantern_requirement_sources',
1996
+ {
1997
+ title: '可分析需求来源',
1998
+ description: '列出需求分析可选择的需求文档及格式支持情况。',
1999
+ annotations: { readOnlyHint: true },
2000
+ },
2001
+ protectedTool(async () => {
2002
+ const data = await apiRequest(apiBase, `/${REQ_API.slice(1)}/sources`);
2003
+ return toolResult(data);
2004
+ }),
2005
+ );
2006
+
2007
+ server.registerTool(
2008
+ 'lantern_requirement_context',
2009
+ {
2010
+ title: '需求拆解上下文',
2011
+ description:
2012
+ '读取需求源文、需求分析技能和原文结构技能。调用后应由客户端模型生成 outline 与 stories,再调用 lantern_requirement_analysis_save。',
2013
+ inputSchema: {
2014
+ sourcePath: z.string().optional().describe('需求文档库内相对路径'),
2015
+ analysisId: z.string().optional().describe('已有分析 ID,可替代 sourcePath'),
2016
+ maxChars: z.number().int().min(1000).max(120000).optional(),
2017
+ },
2018
+ annotations: { readOnlyHint: true },
2019
+ },
2020
+ protectedTool(async ({ sourcePath = '', analysisId = '', maxChars = DEFAULT_SOURCE_CHARS }) => {
2021
+ const analysis = await findAnalysis(apiBase, { analysisId, sourcePath });
2022
+ if (analysisId && !analysis) throw new BridgeError('未找到需求分析', 404);
2023
+ const resolvedPath = sourcePath || analysis?.sourcePath;
2024
+ if (!resolvedPath) throw new BridgeError('未找到需求分析或来源文档', 404);
2025
+ const [source, analysisSkill, outlineSkill] = await Promise.all([
2026
+ readRequirementSource(apiBase, resolvedPath),
2027
+ withAnalysisSkillContext(apiBase, '需求分析提示词.md'),
2028
+ withAnalysisSkillContext(apiBase, '原文结构提示词.md'),
2029
+ ]);
2030
+ const content = String(source.content || '');
2031
+ const limit = Math.max(1000, Math.min(Number(maxChars) || DEFAULT_SOURCE_CHARS, 120000));
2032
+ return toolResult({
2033
+ ok: true,
2034
+ sourcePath: resolvedPath,
2035
+ sourceTitle: path.basename(resolvedPath),
2036
+ sourceHash: sha256(content),
2037
+ sourceFormat: source.format || path.extname(resolvedPath).slice(1),
2038
+ sourceTruncated: content.length > limit,
2039
+ content: content.slice(0, limit),
2040
+ existingAnalysisId: analysis?.id || '',
2041
+ existingAnalysisRevision: analysis ? analysisRevision(analysis) : '',
2042
+ existingAnalysisUpdatedAt: analysis?.updatedAt || '',
2043
+ skills: {
2044
+ analysis: {
2045
+ id: analysisSkill.id,
2046
+ version: analysisSkill.version,
2047
+ instructions: analysisSkill.instructions,
2048
+ rules: analysisSkill.content,
2049
+ },
2050
+ outline: {
2051
+ id: outlineSkill.id,
2052
+ version: outlineSkill.version,
2053
+ instructions: outlineSkill.instructions,
2054
+ rules: outlineSkill.content,
2055
+ },
2056
+ },
2057
+ nextTool: 'lantern_requirement_analysis_save',
2058
+ outputContract: {
2059
+ outline: [{ id: 'RO-1', title: '来源条目标题', quote: '原文证据' }],
2060
+ stories: [
2061
+ {
2062
+ id: '可省略;新故事由 Lantern 分配',
2063
+ title: '用户故事标题',
2064
+ role: '角色',
2065
+ goal: '目标',
2066
+ value: '业务价值',
2067
+ sourceRefs: ['RO-1'],
2068
+ priority: 'P0|P1|P2',
2069
+ preconditions: ['前置条件'],
2070
+ mainFlow: [{ actor: '角色', action: '动作', result: '结果' }],
2071
+ altFlows: [{ name: '替代流程', trigger: '触发条件', steps: ['步骤'] }],
2072
+ exceptions: [{ scenario: '异常场景', expected: '预期' }],
2073
+ postconditions: ['后置条件'],
2074
+ acceptance: [{ given: '前提', when: '操作', then: '结果' }],
2075
+ dimensions: ['functional'],
2076
+ },
2077
+ ],
2078
+ },
2079
+ });
2080
+ }),
2081
+ );
2082
+
2083
+ server.registerTool(
2084
+ 'lantern_requirement_analysis_get',
2085
+ {
2086
+ title: '读取需求分析',
2087
+ description: '按 analysisId 或 sourcePath 读取当前空间的需求分析完整记录。',
2088
+ inputSchema: {
2089
+ analysisId: z.string().optional(),
2090
+ sourcePath: z.string().optional(),
2091
+ },
2092
+ annotations: { readOnlyHint: true },
2093
+ },
2094
+ protectedTool(async ({ analysisId = '', sourcePath = '' }) => {
2095
+ const analysis = await findAnalysis(apiBase, { analysisId, sourcePath });
2096
+ if (!analysis) throw new BridgeError('需求分析不存在', 404);
2097
+ return toolResult({
2098
+ ok: true,
2099
+ analysis,
2100
+ revision: analysisRevision(analysis),
2101
+ artifactUrl: artifactUrl(apiBase, analysis),
2102
+ });
2103
+ }),
2104
+ );
2105
+
2106
+ server.registerTool(
2107
+ 'lantern_requirement_analysis_list',
2108
+ {
2109
+ title: '需求分析列表',
2110
+ description: '列出当前空间已有需求分析,返回 ID、标题、来源、状态、故事数和 revision。',
2111
+ inputSchema: {
2112
+ query: z.string().optional().describe('按标题、来源路径或状态过滤'),
2113
+ },
2114
+ annotations: { readOnlyHint: true },
2115
+ },
2116
+ protectedTool(async ({ query = '' }) => {
2117
+ const needle = String(query).trim().toLowerCase();
2118
+ const docs = (await requirementDocs(apiBase)).filter((doc) => {
2119
+ if (!needle) return true;
2120
+ return [doc.id, doc.title, doc.sourceTitle, doc.sourcePath, doc.status]
2121
+ .join(' ')
2122
+ .toLowerCase()
2123
+ .includes(needle);
2124
+ });
2125
+ return toolResult({
2126
+ ok: true,
2127
+ count: docs.length,
2128
+ analyses: docs.map((doc) => ({
2129
+ id: doc.id,
2130
+ title: doc.title || '',
2131
+ sourceTitle: doc.sourceTitle || '',
2132
+ sourcePath: doc.sourcePath || '',
2133
+ status: doc.status || '',
2134
+ storyCount: Array.isArray(doc.stories) ? doc.stories.length : 0,
2135
+ outlineCount: Array.isArray(doc.outline) ? doc.outline.length : 0,
2136
+ testPointCount: Array.isArray(doc.testPoints?.points) ? doc.testPoints.points.length : 0,
2137
+ updatedAt: doc.updatedAt || '',
2138
+ revision: analysisRevision(doc),
2139
+ artifactUrl: artifactUrl(apiBase, doc),
2140
+ })),
2141
+ });
2142
+ }),
2143
+ );
2144
+
2145
+ server.registerTool(
2146
+ 'lantern_requirement_analysis_delete',
2147
+ {
2148
+ title: '删除需求分析',
2149
+ description:
2150
+ '批量删除需求分析记录。只删除分析数据,不删除需求源文或已存在的需求拆解 XMind 文件。',
2151
+ inputSchema: {
2152
+ analysisIds: z.array(z.string()).min(1),
2153
+ },
2154
+ annotations: { destructiveHint: true },
2155
+ },
2156
+ protectedTool(async ({ analysisIds }) =>
2157
+ toolResult(
2158
+ await apiRequest(apiBase, `/${REQ_API.slice(1)}/delete`, {
2159
+ method: 'POST',
2160
+ body: { ids: analysisIds },
2161
+ }),
2162
+ ),
2163
+ ),
2164
+ );
2165
+
2166
+ server.registerTool(
2167
+ 'lantern_requirement_analysis_save',
2168
+ {
2169
+ title: '保存需求拆解',
2170
+ description:
2171
+ '保存或更新需求原文结构和用户故事。故事 ID、白名单字段和测试点失效规则由 Lantern 服务端处理。',
2172
+ inputSchema: {
2173
+ analysisId: z.string().optional(),
2174
+ sourcePath: z.string().optional(),
2175
+ title: z.string().optional(),
2176
+ sourceTitle: z.string().optional(),
2177
+ sourceHash: z.string().optional(),
2178
+ expectedRevision: z
2179
+ .string()
2180
+ .optional()
2181
+ .describe('更新已有分析时必填;来自 analysis_get 或 requirement_context'),
2182
+ outline: z.array(z.record(z.string(), z.unknown())).optional(),
2183
+ stories: z.array(z.record(z.string(), z.unknown())).describe('用户故事数组'),
2184
+ replaceStories: z.boolean().optional(),
2185
+ summary: z.string().optional(),
2186
+ status: z.string().optional(),
2187
+ },
2188
+ annotations: { destructiveHint: true },
2189
+ },
2190
+ protectedTool(async (args) => {
2191
+ const existing = await findAnalysis(apiBase, args);
2192
+ if (args.analysisId && !existing) {
2193
+ throw new BridgeError(`需求分析不存在:${args.analysisId}`, 404);
2194
+ }
2195
+ if (existing) requireExpectedRevision(existing, args.expectedRevision);
2196
+ const body = {
2197
+ ...(existing?.id ? { id: existing.id } : {}),
2198
+ ...(args.expectedRevision ? { expectedRevision: args.expectedRevision } : {}),
2199
+ ...(args.sourcePath ? { sourcePath: args.sourcePath } : {}),
2200
+ ...(args.title ? { title: args.title } : {}),
2201
+ ...(args.sourceTitle ? { sourceTitle: args.sourceTitle } : {}),
2202
+ ...(args.sourceHash ? { sourceHash: args.sourceHash } : {}),
2203
+ ...(args.outline ? { outline: args.outline } : {}),
2204
+ stories: args.stories,
2205
+ replaceStories: args.replaceStories !== false,
2206
+ ...(args.summary ? { summary: args.summary } : {}),
2207
+ ...(args.status ? { status: args.status } : {}),
2208
+ };
2209
+ if (!existing && !body.sourcePath) {
2210
+ throw new BridgeError('新建需求分析需要 sourcePath');
2211
+ }
2212
+ if (!existing && !body.sourceHash) {
2213
+ throw new BridgeError('新建需求分析需要 sourceHash;请先调用 lantern_requirement_context');
2214
+ }
2215
+ const sourcePathToCheck = body.sourcePath || existing?.sourcePath || '';
2216
+ if (body.sourceHash && sourcePathToCheck) {
2217
+ const source = await readRequirementSource(apiBase, sourcePathToCheck);
2218
+ const currentHash = sha256(String(source.content || ''));
2219
+ if (body.sourceHash !== currentHash) {
2220
+ throw new BridgeError('来源文档已更新,请重新读取需求上下文后再保存', 409, {
2221
+ sourcePath: sourcePathToCheck,
2222
+ expectedSourceHash: body.sourceHash,
2223
+ currentSourceHash: currentHash,
2224
+ });
2225
+ }
2226
+ }
2227
+ const data = existing
2228
+ ? await apiRequest(apiBase, `/${REQ_API.slice(1)}`, { method: 'PUT', body })
2229
+ : await apiRequest(apiBase, `/${REQ_API.slice(1)}/create`, { method: 'POST', body });
2230
+ return toolResult(
2231
+ {
2232
+ ok: true,
2233
+ analysisId: data.doc.id,
2234
+ revision: data.revision || analysisRevision(data.doc),
2235
+ updatedAt: data.doc.updatedAt || '',
2236
+ storyCount: data.doc.stories?.length || 0,
2237
+ outlineCount: data.doc.outline?.length || 0,
2238
+ artifactUrl: artifactUrl(apiBase, data.doc),
2239
+ doc: data.doc,
2240
+ },
2241
+ `已保存 ${data.doc.stories?.length || 0} 条用户故事。`,
2242
+ );
2243
+ }),
2244
+ );
2245
+
2246
+ server.registerTool(
2247
+ 'lantern_requirement_story_patch',
2248
+ {
2249
+ title: '修改单个用户故事',
2250
+ description:
2251
+ '按 storyId 增量修改一条用户故事,其他故事保持不变。必须提供最新 expectedRevision,避免覆盖 Lantern 页面中的并发编辑。',
2252
+ inputSchema: {
2253
+ analysisId: z.string(),
2254
+ storyId: z.string(),
2255
+ expectedRevision: z.string().describe('来自 analysis_get 或 requirement_context'),
2256
+ patch: z.record(z.string(), z.unknown()).describe('要覆盖的故事字段;不能修改 id'),
2257
+ },
2258
+ annotations: { destructiveHint: true },
2259
+ },
2260
+ protectedTool(async ({ analysisId, storyId, expectedRevision, patch }) => {
2261
+ const analysis = await findAnalysis(apiBase, { analysisId });
2262
+ if (!analysis) throw new BridgeError('需求分析不存在', 404);
2263
+ requireExpectedRevision(analysis, expectedRevision);
2264
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {
2265
+ throw new BridgeError('patch 必须是对象');
2266
+ }
2267
+ if (Object.keys(patch).length === 0) throw new BridgeError('patch 不能为空');
2268
+ if ('id' in patch && patch.id !== storyId) {
2269
+ throw new BridgeError('不能通过 patch 修改 storyId');
2270
+ }
2271
+ const stories = Array.isArray(analysis.stories) ? analysis.stories : [];
2272
+ const index = stories.findIndex((story) => story.id === storyId);
2273
+ if (index < 0) throw new BridgeError(`用户故事不存在:${storyId}`, 404);
2274
+ const nextStory = { ...stories[index], ...patch, id: storyId };
2275
+ const nextStories = stories.map((story, i) => (i === index ? nextStory : story));
2276
+ const data = await apiRequest(apiBase, `/${REQ_API.slice(1)}`, {
2277
+ method: 'PUT',
2278
+ body: { id: analysisId, expectedRevision, stories: nextStories },
2279
+ });
2280
+ return toolResult({
2281
+ ok: true,
2282
+ analysisId,
2283
+ revision: data.revision || analysisRevision(data.doc),
2284
+ updatedAt: data.doc.updatedAt || '',
2285
+ story: data.doc.stories?.find((story) => story.id === storyId) || nextStory,
2286
+ testPointsNeedReview: Boolean(data.doc.testPoints?.points?.length),
2287
+ artifactUrl: artifactUrl(apiBase, data.doc),
2288
+ });
2289
+ }),
2290
+ );
2291
+
2292
+ server.registerTool(
2293
+ 'lantern_requirement_story_delete',
2294
+ {
2295
+ title: '删除单个用户故事',
2296
+ description:
2297
+ '按 storyId 删除一条用户故事,并移除引用该故事的测试点。必须提供最新 expectedRevision。',
2298
+ inputSchema: {
2299
+ analysisId: z.string(),
2300
+ storyId: z.string(),
2301
+ expectedRevision: z.string().describe('来自 analysis_get 或 requirement_context'),
2302
+ },
2303
+ annotations: { destructiveHint: true },
2304
+ },
2305
+ protectedTool(async ({ analysisId, storyId, expectedRevision }) => {
2306
+ const analysis = await findAnalysis(apiBase, { analysisId });
2307
+ if (!analysis) throw new BridgeError('需求分析不存在', 404);
2308
+ requireExpectedRevision(analysis, expectedRevision);
2309
+ const stories = Array.isArray(analysis.stories) ? analysis.stories : [];
2310
+ if (!stories.some((story) => story.id === storyId)) {
2311
+ throw new BridgeError(`用户故事不存在:${storyId}`, 404);
2312
+ }
2313
+ const nextStories = stories.filter((story) => story.id !== storyId);
2314
+ const points = Array.isArray(analysis.testPoints?.points) ? analysis.testPoints.points : [];
2315
+ const nextPoints = points.filter((point) => point.storyId !== storyId);
2316
+ const removedPointCount = points.length - nextPoints.length;
2317
+ const body = { id: analysisId, expectedRevision, stories: nextStories };
2318
+ if (removedPointCount) {
2319
+ body.testPoints =
2320
+ nextPoints.length || analysis.testPoints?.summary
2321
+ ? {
2322
+ ...analysis.testPoints,
2323
+ at: new Date().toISOString(),
2324
+ points: nextPoints,
2325
+ }
2326
+ : null;
2327
+ }
2328
+ const data = await apiRequest(apiBase, `/${REQ_API.slice(1)}`, {
2329
+ method: 'PUT',
2330
+ body,
2331
+ });
2332
+ return toolResult({
2333
+ ok: true,
2334
+ analysisId,
2335
+ deletedStoryId: storyId,
2336
+ removedPointCount,
2337
+ revision: data.revision || analysisRevision(data.doc),
2338
+ updatedAt: data.doc.updatedAt || '',
2339
+ storyCount: data.doc.stories?.length || 0,
2340
+ reviewNeedsRefresh: Boolean(data.doc.check),
2341
+ artifactUrl: artifactUrl(apiBase, data.doc),
2342
+ });
2343
+ }),
2344
+ );
2345
+
2346
+ server.registerTool(
2347
+ 'lantern_requirement_review_save',
2348
+ {
2349
+ title: '保存故事审查',
2350
+ description: '保存用户故事审查报告、待确认缺口和忽略项,不修改故事正文。',
2351
+ inputSchema: {
2352
+ analysisId: z.string(),
2353
+ expectedRevision: z.string().describe('来自 analysis_get'),
2354
+ check: z.record(z.string(), z.unknown()),
2355
+ ignoredGaps: z.array(z.record(z.string(), z.unknown())).optional(),
2356
+ status: z.string().optional(),
2357
+ },
2358
+ annotations: { destructiveHint: true },
2359
+ },
2360
+ protectedTool(async ({ analysisId, expectedRevision, check, ignoredGaps, status }) => {
2361
+ const analysis = await findAnalysis(apiBase, { analysisId });
2362
+ if (!analysis) throw new BridgeError('需求分析不存在', 404);
2363
+ requireExpectedRevision(analysis, expectedRevision);
2364
+ const data = await apiRequest(apiBase, `/${REQ_API.slice(1)}`, {
2365
+ method: 'PUT',
2366
+ body: {
2367
+ id: analysisId,
2368
+ expectedRevision,
2369
+ check,
2370
+ ...(ignoredGaps ? { ignoredGaps } : {}),
2371
+ ...(status ? { status } : {}),
2372
+ },
2373
+ });
2374
+ return toolResult({
2375
+ ok: true,
2376
+ analysisId,
2377
+ revision: data.revision || analysisRevision(data.doc),
2378
+ updatedAt: data.doc.updatedAt || '',
2379
+ gapCount: data.doc.check?.gaps?.length || 0,
2380
+ artifactUrl: artifactUrl(apiBase, data.doc),
2381
+ });
2382
+ }),
2383
+ );
2384
+
2385
+ server.registerTool(
2386
+ 'lantern_requirement_review_context',
2387
+ {
2388
+ title: '故事审查上下文',
2389
+ description:
2390
+ '读取最新用户故事、来源正文和 Lantern 故事审查技能。生成审查结果后调用 lantern_requirement_review_save。',
2391
+ inputSchema: {
2392
+ analysisId: z.string(),
2393
+ maxChars: z.number().int().min(1000).max(120000).optional(),
2394
+ },
2395
+ annotations: { readOnlyHint: true },
2396
+ },
2397
+ protectedTool(async ({ analysisId, maxChars = DEFAULT_SOURCE_CHARS }) => {
2398
+ const analysis = await findAnalysis(apiBase, { analysisId });
2399
+ if (!analysis) throw new BridgeError('需求分析不存在', 404);
2400
+ if (!analysis.stories?.length) throw new BridgeError('请先生成并保存用户故事');
2401
+ const [source, reviewSkill] = await Promise.all([
2402
+ readRequirementSource(apiBase, analysis.sourcePath),
2403
+ withAnalysisSkillContext(apiBase, '用户故事审查提示词.md'),
2404
+ ]);
2405
+ const content = String(source.content || '');
2406
+ const limit = Math.max(1000, Math.min(Number(maxChars) || DEFAULT_SOURCE_CHARS, 120000));
2407
+ return toolResult({
2408
+ ok: true,
2409
+ analysisId,
2410
+ revision: analysisRevision(analysis),
2411
+ updatedAt: analysis.updatedAt || '',
2412
+ sourcePath: analysis.sourcePath,
2413
+ sourceHash: sha256(content),
2414
+ sourceTruncated: content.length > limit,
2415
+ content: content.slice(0, limit),
2416
+ outline: analysis.outline || [],
2417
+ stories: analysis.stories,
2418
+ existingCheck: analysis.check || null,
2419
+ skill: {
2420
+ id: reviewSkill.id,
2421
+ version: reviewSkill.version,
2422
+ instructions: reviewSkill.instructions,
2423
+ rules: reviewSkill.content,
2424
+ },
2425
+ nextTool: 'lantern_requirement_review_save',
2426
+ outputContract: {
2427
+ check: {
2428
+ summary: '审查总体结论',
2429
+ coverage: { total: 0, covered: 0, rate: 0 },
2430
+ dimensions: [
2431
+ {
2432
+ key: 'functional',
2433
+ label: '功能',
2434
+ covered: true,
2435
+ stories: ['US-001'],
2436
+ },
2437
+ ],
2438
+ gaps: [
2439
+ {
2440
+ storyId: 'US-001',
2441
+ type: 'uncovered-outline|pending-confirm|missing-field|missing-scenario|missing-dimension|untestable-acceptance|conflict|over-split|other',
2442
+ severity: 'high|medium|low',
2443
+ title: '缺口标题',
2444
+ detail: '缺口说明',
2445
+ suggestion: '建议怎么补',
2446
+ origin: 'rule|model',
2447
+ selected: true,
2448
+ },
2449
+ ],
2450
+ },
2451
+ },
2452
+ });
2453
+ }),
2454
+ );
2455
+
2456
+ server.registerTool(
2457
+ 'lantern_testpoints_context',
2458
+ {
2459
+ title: '测试点生成上下文',
2460
+ description:
2461
+ '读取指定需求分析、用户故事和测试点技能。调用后生成 testPoints 对象并调用 lantern_testpoints_save。',
2462
+ inputSchema: {
2463
+ analysisId: z.string(),
2464
+ },
2465
+ annotations: { readOnlyHint: true },
2466
+ },
2467
+ protectedTool(async ({ analysisId }) => {
2468
+ const analysis = await findAnalysis(apiBase, { analysisId });
2469
+ if (!analysis) throw new BridgeError('需求分析不存在', 404);
2470
+ if (!analysis.stories?.length) throw new BridgeError('请先生成并保存用户故事');
2471
+ const skill = await withAnalysisSkillContext(apiBase, '测试点生成提示词.md');
2472
+ return toolResult({
2473
+ ok: true,
2474
+ analysisId,
2475
+ sourcePath: analysis.sourcePath,
2476
+ outline: analysis.outline || [],
2477
+ stories: analysis.stories,
2478
+ revision: analysisRevision(analysis),
2479
+ updatedAt: analysis.updatedAt || '',
2480
+ existingTestPoints: analysis.testPoints || null,
2481
+ skill: {
2482
+ id: skill.id,
2483
+ version: skill.version,
2484
+ instructions: skill.instructions,
2485
+ rules: skill.content,
2486
+ },
2487
+ nextTool: 'lantern_testpoints_save',
2488
+ outputContract: {
2489
+ summary: '测试点总体说明',
2490
+ points: [
2491
+ {
2492
+ storyId: 'US-001',
2493
+ dimension: 'functional|boundary|exception|business|nonfunctional',
2494
+ priority: 'P0|P1|P2|P3',
2495
+ title: '测试点',
2496
+ precondition: '前置条件',
2497
+ steps: ['步骤'],
2498
+ expected: '预期',
2499
+ supplemental: false,
2500
+ },
2501
+ ],
2502
+ },
2503
+ });
2504
+ }),
2505
+ );
2506
+
2507
+ server.registerTool(
2508
+ 'lantern_testpoints_save',
2509
+ {
2510
+ title: '保存测试点',
2511
+ description: '把测试点报告保存到指定需求分析;Lantern 会排序、重编号并做白名单归一化。',
2512
+ inputSchema: {
2513
+ analysisId: z.string(),
2514
+ expectedRevision: z.string().describe('来自 testpoints_context 或 analysis_get'),
2515
+ testPoints: z.record(z.string(), z.unknown()),
2516
+ },
2517
+ annotations: { destructiveHint: true },
2518
+ },
2519
+ protectedTool(async ({ analysisId, expectedRevision, testPoints }) => {
2520
+ const analysis = await findAnalysis(apiBase, { analysisId });
2521
+ if (!analysis) throw new BridgeError('需求分析不存在', 404);
2522
+ requireExpectedRevision(analysis, expectedRevision);
2523
+ const data = await apiRequest(apiBase, `/${REQ_API.slice(1)}`, {
2524
+ method: 'PUT',
2525
+ body: { id: analysisId, expectedRevision, testPoints },
2526
+ });
2527
+ return toolResult({
2528
+ ok: true,
2529
+ analysisId,
2530
+ revision: data.revision || analysisRevision(data.doc),
2531
+ updatedAt: data.doc.updatedAt || '',
2532
+ pointCount: data.doc.testPoints?.points?.length || 0,
2533
+ artifactUrl: artifactUrl(apiBase, data.doc),
2534
+ });
2535
+ }),
2536
+ );
2537
+
2538
+ server.registerTool(
2539
+ 'lantern_defect_templates',
2540
+ {
2541
+ title: '列出缺陷规则',
2542
+ description: '列出当前空间保存的缺陷规则及当前选中模板。',
2543
+ annotations: { readOnlyHint: true },
2544
+ },
2545
+ protectedTool(async () => toolResult(await apiRequest(apiBase, DEFECT_API + '/templates'))),
2546
+ );
2547
+ server.registerTool(
2548
+ 'lantern_defect_rule_inspect',
2549
+ {
2550
+ title: '识别缺陷目标字段',
2551
+ description:
2552
+ '只读检查腾讯文档缺陷目标或子表,返回可选子表和真实字段;其他平台可创建手动字段规则。',
2553
+ inputSchema: {
2554
+ url: z.string(),
2555
+ sheetId: z.string().optional(),
2556
+ },
2557
+ annotations: { readOnlyHint: true, openWorldHint: true },
2558
+ },
2559
+ protectedTool(async (args) =>
2560
+ toolResult(
2561
+ await apiRequest(apiBase, DEFECT_API + '/inspect', {
2562
+ method: 'POST',
2563
+ body: args,
2564
+ timeoutMs: 90_000,
2565
+ }),
2566
+ ),
2567
+ ),
2568
+ );
2569
+ server.registerTool(
2570
+ 'lantern_defect_rule_save',
2571
+ {
2572
+ title: '新建或修改缺陷规则',
2573
+ description:
2574
+ '保存缺陷规则的入口、字段映射、填写口径、默认值、必填状态和迭代配置。字段 ID 必须来自 inspect 或已有规则。',
2575
+ inputSchema: {
2576
+ id: z.string().optional().describe('为空时新建规则'),
2577
+ name: z.string().min(1),
2578
+ url: z.string().optional(),
2579
+ sheetId: z.string().optional(),
2580
+ template: z.string().optional(),
2581
+ mapping: z
2582
+ .array(
2583
+ z.object({
2584
+ id: z.string(),
2585
+ label: z.string(),
2586
+ required: z.boolean().optional(),
2587
+ source: z.enum(['remote', 'manual']).optional(),
2588
+ rule: z.string().optional(),
2589
+ kind: z
2590
+ .enum(['text', 'number', 'option', 'bool', 'reference', 'image', 'attachment'])
2591
+ .optional(),
2592
+ multiple: z.boolean().optional(),
2593
+ options: z.array(z.object({ id: z.string(), label: z.string() })).optional(),
2594
+ optionLabels: z.record(z.string(), z.string()).optional(),
2595
+ hiddenOptions: z.array(z.string()).optional(),
2596
+ defaultValue: z.unknown().optional(),
2597
+ }),
2598
+ )
2599
+ .min(1),
2600
+ iterations: z.array(z.string()).optional(),
2601
+ iteration: z.string().optional(),
2602
+ },
2603
+ annotations: { destructiveHint: true, openWorldHint: true },
2604
+ },
2605
+ protectedTool(async (args) =>
2606
+ toolResult(
2607
+ await apiRequest(apiBase, DEFECT_API + '/rules/save', {
2608
+ method: 'POST',
2609
+ body: args,
2610
+ timeoutMs: 90_000,
2611
+ }),
2612
+ ),
2613
+ ),
2614
+ );
2615
+ server.registerTool(
2616
+ 'lantern_defect_rule_delete',
2617
+ {
2618
+ title: '删除缺陷规则',
2619
+ description: '删除指定缺陷规则;若删除当前选中规则,Lantern 会自动切换到剩余第一条。',
2620
+ inputSchema: { id: z.string() },
2621
+ annotations: { destructiveHint: true },
2622
+ },
2623
+ protectedTool(async ({ id }) =>
2624
+ toolResult(
2625
+ await apiRequest(apiBase, DEFECT_API + '/rules/delete', {
2626
+ method: 'POST',
2627
+ body: { id },
2628
+ }),
2629
+ ),
2630
+ ),
2631
+ );
2632
+ server.registerTool(
2633
+ 'lantern_defect_drafts',
2634
+ {
2635
+ title: '列出缺陷草稿',
2636
+ description: '列出当前空间保存的缺陷草稿及提交状态,避免重复生成或遗漏待核验回执。',
2637
+ annotations: { readOnlyHint: true },
2638
+ },
2639
+ protectedTool(async () => toolResult(await apiRequest(apiBase, DEFECT_API + '/drafts'))),
2640
+ );
2641
+ server.registerTool(
2642
+ 'lantern_defect_template_select',
2643
+ {
2644
+ title: '选择缺陷规则',
2645
+ description: '按模板 ID 选择缺陷目标和规则。返回该模板最新上下文,切换后重新生成草稿。',
2646
+ inputSchema: { id: z.string() },
2647
+ annotations: { destructiveHint: false, openWorldHint: false },
2648
+ },
2649
+ protectedTool(async (args) =>
2650
+ toolResult(
2651
+ await apiRequest(apiBase, DEFECT_API + '/select-template', {
2652
+ method: 'POST',
2653
+ body: args,
2654
+ timeoutMs: 90_000,
2655
+ }),
2656
+ ),
2657
+ ),
2658
+ );
2659
+
2660
+ server.registerTool(
2661
+ 'lantern_defect_context',
2662
+ {
2663
+ title: '读取缺陷提交上下文',
2664
+ description:
2665
+ '读取当前空间已配置的缺陷目标、模板、所属迭代、字段、可用选项和字段默认值。发现未配置时请在 Lantern 的缺陷提交页面设置。',
2666
+ annotations: { readOnlyHint: true },
2667
+ },
2668
+ protectedTool(async () =>
2669
+ toolResult(await apiRequest(apiBase, DEFECT_API + '/context', { timeoutMs: 90_000 })),
2670
+ ),
2671
+ );
2672
+
2673
+ server.registerTool(
2674
+ 'lantern_defect_draft_save',
2675
+ {
2676
+ title: '保存缺陷草稿',
2677
+ description:
2678
+ '按上下文字段 ID 保存草稿,返回缺失项、预览和版本。未传入的字段会使用规则默认值;选项和关联值使用实际 ID,图片值使用 image ID 数组。',
2679
+ inputSchema: {
2680
+ contextRevision: z.string(),
2681
+ id: z.string().optional(),
2682
+ revision: z.string().optional(),
2683
+ values: z.record(
2684
+ z.string(),
2685
+ z.union([z.string(), z.number(), z.boolean(), z.array(z.string())]),
2686
+ ),
2687
+ },
2688
+ annotations: { destructiveHint: false, openWorldHint: false },
2689
+ },
2690
+ protectedTool(async (args) =>
2691
+ toolResult(
2692
+ await apiRequest(apiBase, DEFECT_API + '/draft', {
2693
+ method: 'POST',
2694
+ body: args,
2695
+ timeoutMs: 90_000,
2696
+ }),
2697
+ ),
2698
+ ),
2699
+ );
2700
+
2701
+ server.registerTool(
2702
+ 'lantern_defect_submit',
2703
+ {
2704
+ title: '提交已确认的缺陷',
2705
+ description:
2706
+ '用户明确要求最终提交(如「提个缺陷」「提交缺陷」)或确认草稿后调用。纯生成、预览草稿请求不得调用。使用保存草稿返回的 ID 和版本。',
2707
+ inputSchema: { id: z.string(), revision: z.string() },
2708
+ annotations: { destructiveHint: false, idempotentHint: true, openWorldHint: true },
2709
+ },
2710
+ protectedTool(async (args) =>
2711
+ toolResult(
2712
+ await apiRequest(apiBase, DEFECT_API + '/submit', {
2713
+ method: 'POST',
2714
+ body: args,
2715
+ timeoutMs: 110_000,
2716
+ }),
2717
+ ),
2718
+ ),
2719
+ );
2720
+
2721
+ server.registerTool(
2722
+ 'lantern_defect_receipt',
2723
+ {
2724
+ title: '核验缺陷提交回执',
2725
+ description: '按草稿 ID 查询状态。有远端记录 ID 时回读并更新本地回执。',
2726
+ inputSchema: { id: z.string() },
2727
+ annotations: { destructiveHint: false, idempotentHint: true, openWorldHint: true },
2728
+ },
2729
+ protectedTool(async ({ id }) =>
2730
+ toolResult(await apiRequest(apiBase, DEFECT_API + '/receipt?id=' + encodeURIComponent(id))),
2731
+ ),
2732
+ );
2733
+
2734
+ return server;
2735
+ }
2736
+
2737
+ /**
2738
+ * @param {{ dataRoot: string, url?: string, port?: number }} opts
2739
+ */
2740
+ export async function runLanternMcpServer(opts) {
2741
+ const lifecycle = await ensureLanternApi(opts);
2742
+ const packageJson = JSON.parse(
2743
+ fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'),
2744
+ );
2745
+ const server = createLanternMcpServer({
2746
+ apiBase: lifecycle.apiBase,
2747
+ version: String(packageJson.version || '0.0.0'),
2748
+ });
2749
+ const transport = new StdioServerTransport();
2750
+ let closed = false;
2751
+ const close = async () => {
2752
+ if (closed) return;
2753
+ closed = true;
2754
+ await server.close().catch(() => undefined);
2755
+ if (lifecycle.localServer) {
2756
+ await new Promise((resolve) => lifecycle.localServer.close(() => resolve(undefined)));
2757
+ }
2758
+ };
2759
+ process.once('SIGINT', () => void close().finally(() => process.exit(0)));
2760
+ process.once('SIGTERM', () => void close().finally(() => process.exit(0)));
2761
+ process.stdin.once('end', () => void close());
2762
+ await server.connect(transport);
2763
+ process.stderr.write(
2764
+ `Lantern MCP ready (api=${lifecycle.apiBase}, embeddedService=${Boolean(
2765
+ lifecycle.localServer,
2766
+ )})\n`,
2767
+ );
2768
+ }
2769
+
2770
+ export { ensureLanternApi, parseBridgeArgs };
2771
+
2772
+ const modulePath = fileURLToPath(import.meta.url);
2773
+ if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(modulePath)) {
2774
+ const options = parseBridgeArgs(process.argv.slice(2));
2775
+ runLanternMcpServer(options).catch((error) => {
2776
+ process.stderr.write(`Lantern MCP error: ${error instanceof Error ? error.message : error}\n`);
2777
+ process.exit(1);
2778
+ });
2779
+ }