molforge-studio 7.4.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. main.py +71 -0
  2. molforge/__init__.py +19 -0
  3. molforge/ai/__init__.py +15 -0
  4. molforge/ai/deepseek_harness.py +185 -0
  5. molforge/ai/mcp/desktop_client.py +38 -0
  6. molforge/ai/mcp/desktop_service.py +121 -0
  7. molforge/ai/mcp/mcp_server.py +780 -0
  8. molforge/ai/mcp_bridge.py +945 -0
  9. molforge/ai/observation.py +152 -0
  10. molforge/ai/tools.py +455 -0
  11. molforge/application/__init__.py +22 -0
  12. molforge/application/ai/__init__.py +1 -0
  13. molforge/application/ai/deepseek_client.py +293 -0
  14. molforge/application/ai/observation.py +161 -0
  15. molforge/application/ai/tools.py +200 -0
  16. molforge/application/ai_proposals.py +166 -0
  17. molforge/application/bio_selection.py +143 -0
  18. molforge/application/builtin_commands.py +1445 -0
  19. molforge/application/calculators/__init__.py +10 -0
  20. molforge/application/calculators/base.py +143 -0
  21. molforge/application/calculators/calchem_engine.py +67 -0
  22. molforge/application/calculators/calchem_subprocess_worker.py +109 -0
  23. molforge/application/calculators/gaussian_engine.py +59 -0
  24. molforge/application/calculators/gaussian_job_spec.py +240 -0
  25. molforge/application/calculators/orca_engine.py +92 -0
  26. molforge/application/calculators/qc_input_generator.py +300 -0
  27. molforge/application/calculators/registry.py +29 -0
  28. molforge/application/calculators/rest_engine.py +262 -0
  29. molforge/application/command_bus.py +139 -0
  30. molforge/application/commands.py +55 -0
  31. molforge/application/conformers.py +143 -0
  32. molforge/application/document_session.py +156 -0
  33. molforge/application/events.py +74 -0
  34. molforge/application/fragment_catalog.py +422 -0
  35. molforge/application/fragment_commands.py +268 -0
  36. molforge/application/geometry_commands.py +84 -0
  37. molforge/application/history.py +105 -0
  38. molforge/application/internal_coordinates.py +293 -0
  39. molforge/application/invalidation.py +1174 -0
  40. molforge/application/jobs.py +185 -0
  41. molforge/application/measurement.py +167 -0
  42. molforge/application/measurement_targets.py +264 -0
  43. molforge/application/modeling_commands.py +61 -0
  44. molforge/application/plugins.py +197 -0
  45. molforge/application/ports/editor2d.py +85 -0
  46. molforge/application/reaction.py +75 -0
  47. molforge/application/selection.py +164 -0
  48. molforge/application/selection_commands.py +31 -0
  49. molforge/application/trajectory.py +120 -0
  50. molforge/application/trajectory_analysis.py +231 -0
  51. molforge/application/workspace_registry.py +226 -0
  52. molforge/core/__init__.py +12 -0
  53. molforge/core/conformer.py +45 -0
  54. molforge/core/molecule.py +150 -0
  55. molforge/core/orbital.py +33 -0
  56. molforge/core/properties.py +43 -0
  57. molforge/domain/__init__.py +12 -0
  58. molforge/domain/biomolecule.py +99 -0
  59. molforge/domain/chemical_summary.py +129 -0
  60. molforge/domain/chemistry.py +13 -0
  61. molforge/domain/coordinate_store.py +164 -0
  62. molforge/domain/coordination.py +133 -0
  63. molforge/domain/custom_fragments.py +255 -0
  64. molforge/domain/document.py +469 -0
  65. molforge/domain/element_reference.json +598 -0
  66. molforge/domain/elements.py +188 -0
  67. molforge/domain/ids.py +58 -0
  68. molforge/domain/massive_system.py +246 -0
  69. molforge/domain/periodic.py +116 -0
  70. molforge/domain/provenance.py +115 -0
  71. molforge/domain/topology.py +364 -0
  72. molforge/infrastructure/__init__.py +23 -0
  73. molforge/infrastructure/hpc/cluster_config.py +122 -0
  74. molforge/infrastructure/hpc/remote_executor.py +212 -0
  75. molforge/infrastructure/hpc/slurm_generator.py +93 -0
  76. molforge/io/__init__.py +35 -0
  77. molforge/io/calchem_bridge.py +407 -0
  78. molforge/io/calculators.py +893 -0
  79. molforge/io/cclib_adapter.py +422 -0
  80. molforge/io/conformers.py +183 -0
  81. molforge/io/cube_reader.py +215 -0
  82. molforge/io/custom_fragments.py +79 -0
  83. molforge/io/format_matrix.py +157 -0
  84. molforge/io/gemmi_adapter.py +150 -0
  85. molforge/io/history_skill.py +46 -0
  86. molforge/io/mdanalysis_adapter.py +155 -0
  87. molforge/io/mforge_storage.py +261 -0
  88. molforge/io/multiwfn_driver.py +614 -0
  89. molforge/io/openbabel_adapter.py +265 -0
  90. molforge/io/openbabel_handler.py +33 -0
  91. molforge/io/rdkit_adapter.py +1865 -0
  92. molforge/io/readers/__init__.py +10 -0
  93. molforge/io/readers/cube_reader.py +71 -0
  94. molforge/io/readers/gjf_reader.py +110 -0
  95. molforge/io/readers/glog_reader.py +45 -0
  96. molforge/io/readers/mol2_reader.py +36 -0
  97. molforge/io/readers/mol_reader.py +56 -0
  98. molforge/io/readers/pdb_reader.py +39 -0
  99. molforge/io/readers/smi_reader.py +40 -0
  100. molforge/io/readers/xyz_reader.py +47 -0
  101. molforge/io/registry.py +128 -0
  102. molforge/io/writers/__init__.py +7 -0
  103. molforge/io/writers/gjf_writer.py +68 -0
  104. molforge/io/writers/pdb_writer.py +37 -0
  105. molforge/io/writers/png_writer.py +31 -0
  106. molforge/io/writers/svg_writer.py +111 -0
  107. molforge/io/writers/xyz_writer.py +39 -0
  108. molforge/rendering/__init__.py +21 -0
  109. molforge/rendering/benchmark.py +121 -0
  110. molforge/rendering/bridge.py +60 -0
  111. molforge/rendering/contracts.py +119 -0
  112. molforge/rendering/glyph_scene.py +279 -0
  113. molforge/rendering/ketcher_bridge.py +131 -0
  114. molforge/rendering/ketcher_id_mapping.py +110 -0
  115. molforge/rendering/materials.py +127 -0
  116. molforge/rendering/molstar_backend.py +245 -0
  117. molforge/rendering/native_labels.py +134 -0
  118. molforge/rendering/orbitals.py +139 -0
  119. molforge/rendering/vtk_backend.py +2294 -0
  120. molforge/runtime.py +29 -0
  121. molforge/server/__init__.py +1 -0
  122. molforge/server/api_bridge.py +947 -0
  123. molforge/ui/__init__.py +1 -0
  124. molforge/ui/assets/caffeine_2d.svg +150 -0
  125. molforge/ui/assets/caffeine_3d_preview.svg +209 -0
  126. molforge/ui/assets/caffeine_preview.json +302 -0
  127. molforge/ui/assets/icons/atom.svg +1 -0
  128. molforge/ui/assets/icons/bond.svg +1 -0
  129. molforge/ui/assets/icons/cleanup.svg +1 -0
  130. molforge/ui/assets/icons/export.svg +1 -0
  131. molforge/ui/assets/icons/fragments.svg +1 -0
  132. molforge/ui/assets/icons/history.svg +1 -0
  133. molforge/ui/assets/icons/jobs.svg +1 -0
  134. molforge/ui/assets/icons/measure.svg +1 -0
  135. molforge/ui/assets/icons/molecules.svg +1 -0
  136. molforge/ui/assets/icons/overview.svg +1 -0
  137. molforge/ui/assets/icons/ring.svg +1 -0
  138. molforge/ui/assets/icons/search.svg +1 -0
  139. molforge/ui/assets/icons/select.svg +1 -0
  140. molforge/ui/assets/icons/settings.svg +1 -0
  141. molforge/ui/assets/icons/templates.svg +1 -0
  142. molforge/ui/assets/molforge_logo.ico +0 -0
  143. molforge/ui/assets/molforge_logo.png +0 -0
  144. molforge/ui/atom_labels.py +92 -0
  145. molforge/ui/bio_structure_dialog.py +57 -0
  146. molforge/ui/conformer_dialog.py +151 -0
  147. molforge/ui/dialogs/__init__.py +2 -0
  148. molforge/ui/dialogs/aim_qtaim_dialog.py +533 -0
  149. molforge/ui/dialogs/calchem_orbitals_dialog.py +287 -0
  150. molforge/ui/dialogs/element_fragments.py +130 -0
  151. molforge/ui/dialogs/gaussian_calculation_setup.py +308 -0
  152. molforge/ui/dialogs/hpc_job_dialog.py +427 -0
  153. molforge/ui/dialogs/vibrational_spectrum_dialog.py +381 -0
  154. molforge/ui/editor2d_widget.py +1803 -0
  155. molforge/ui/element_picker.py +218 -0
  156. molforge/ui/gmv_window_manager.py +65 -0
  157. molforge/ui/gromacs_job_dialog.py +47 -0
  158. molforge/ui/hotkeys.py +107 -0
  159. molforge/ui/i18n.py +237 -0
  160. molforge/ui/live_llm_dialog.py +135 -0
  161. molforge/ui/llm_config_dialog.py +103 -0
  162. molforge/ui/modeling_actions.py +176 -0
  163. molforge/ui/molstar_widget.py +98 -0
  164. molforge/ui/molstar_window.py +85 -0
  165. molforge/ui/panels.py +2966 -0
  166. molforge/ui/qc_result_dialog.py +1924 -0
  167. molforge/ui/render3d_widget.py +1579 -0
  168. molforge/ui/scrolling.py +52 -0
  169. molforge/ui/settings_panel.py +330 -0
  170. molforge/ui/shells/__init__.py +4 -0
  171. molforge/ui/shells/base_shell.py +72 -0
  172. molforge/ui/shells/document_tabs.py +715 -0
  173. molforge/ui/shells/studio_2d.py +339 -0
  174. molforge/ui/shells/studio_3d.py +401 -0
  175. molforge/ui/shells/studio_split.py +370 -0
  176. molforge/ui/shells/workflow_inputs.py +698 -0
  177. molforge/ui/theme.py +719 -0
  178. molforge/ui/trajectory_window.py +333 -0
  179. molforge/ui/views.py +892 -0
  180. molforge/ui/vtk_multiview_widget.py +141 -0
  181. molforge/ui/welcome_window.py +223 -0
  182. molforge/ui/window.py +3320 -0
  183. molforge/workflows/__init__.py +25 -0
  184. molforge/workflows/assets/OSC_MD_workflows/templates/01-MD/delete_solvent.py +216 -0
  185. molforge/workflows/assets/OSC_MD_workflows/templates/02-RDF/extract_atoms.py +60 -0
  186. molforge/workflows/assets/OSC_MD_workflows/templates/02-RDF/extract_atoms_example.py +22 -0
  187. molforge/workflows/assets/OSC_MD_workflows/templates/03-/342/225/244/320/225/342/225/250/342/226/221/342/225/250/320/246/342/225/244/320/227/342/225/250/342/225/226/342/225/250/342/224/220/342/225/244/320/225/342/225/250/320/247/342/225/250/342/226/221/342/225/244/320/224/321/202/320/245/320/254/342/225/250/320/265/analysis_mol.py +244 -0
  188. molforge/workflows/assets/OSC_MD_workflows/templates/04-/342/225/244/320/224/321/202/320/245/320/241/342/225/250/320/254/342/225/244/320/227/321/202/320/245/320/247/321/202/320/244/320/264/342/225/244/320/225/342/225/250/342/224/220/342/225/250/320/246/342/225/244/320/225/321/202/320/245/320/241/342/225/250/342/225/242/rms_roughness.py +33 -0
  189. molforge/workflows/assets/OSC_MD_workflows/templates/04-/342/225/244/320/224/321/202/320/245/320/241/342/225/250/320/254/342/225/244/320/227/321/202/320/245/320/247/321/202/320/244/320/264/342/225/244/320/225/342/225/250/342/224/220/342/225/250/320/246/342/225/244/320/225/321/202/320/245/320/241/342/225/250/342/225/242/xpm_2.py +117 -0
  190. molforge/workflows/assets/OSC_MD_workflows/templates/09-/342/225/244/320/231/342/225/250/320/240/342/225/250/320/277/342/225/244/320/227/342/225/250/320/256/342/225/250/320/247/marcus_rate.py +60 -0
  191. molforge/workflows/assets/esp-surface-analysis/scripts/compute_descriptors.py +134 -0
  192. molforge/workflows/assets/esp-surface-analysis/scripts/parse_surfanalysis.py +58 -0
  193. molforge/workflows/assets/esp-surface-analysis/scripts/plot_esp_hist.py +115 -0
  194. molforge/workflows/assets/homo-lumo-plot/extract_orb_energy.py +57 -0
  195. molforge/workflows/assets/homo-lumo-plot/make_level_plot.py +76 -0
  196. molforge/workflows/assets/homo-lumo-plot/run_pipeline.py +84 -0
  197. molforge/workflows/assets/osc-energy-level-diagram/scripts/extract_levels.py +60 -0
  198. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_editable_pptx.py +122 -0
  199. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_energy_table.py +66 -0
  200. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_level_lines_diagram.py +148 -0
  201. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_rectangle_diagram.py +148 -0
  202. molforge/workflows/assets/osc-energy-level-diagram/scripts/verify_from_log.py +45 -0
  203. molforge/workflows/dipole_analysis.py +32 -0
  204. molforge/workflows/esp_surface.py +36 -0
  205. molforge/workflows/gromacs_submit.py +167 -0
  206. molforge/workflows/homo_lumo_plot.py +59 -0
  207. molforge/workflows/igmh_interaction.py +111 -0
  208. molforge/workflows/md_rdf_analysis.py +134 -0
  209. molforge/workflows/md_studio.py +255 -0
  210. molforge/workflows/osc_energy_diagram.py +24 -0
  211. molforge/workflows/planarity_analysis.py +66 -0
  212. molforge/workflows/reorganization_energy.py +166 -0
  213. molforge/workflows/scientific_workflows.py +650 -0
  214. molforge_studio-7.4.3.dist-info/METADATA +215 -0
  215. molforge_studio-7.4.3.dist-info/RECORD +219 -0
  216. molforge_studio-7.4.3.dist-info/WHEEL +5 -0
  217. molforge_studio-7.4.3.dist-info/entry_points.txt +3 -0
  218. molforge_studio-7.4.3.dist-info/licenses/LICENSE +93 -0
  219. molforge_studio-7.4.3.dist-info/top_level.txt +2 -0
main.py ADDED
@@ -0,0 +1,71 @@
1
+ """
2
+ MolForge v7.0 - AI-Native 分子工作台主入口
3
+ ==========================================
4
+ 直接运行 `python main.py`(支持 `--mode welcome|split|2d|3d|legacy`)或双击 `run_molforge.bat` 启动。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import sys
9
+ from molforge.runtime import configure_runtime
10
+ configure_runtime()
11
+ from molforge import __version__
12
+ from PyQt6.QtCore import Qt
13
+ from PyQt6.QtWidgets import QApplication
14
+
15
+ try:
16
+ QApplication.setHighDpiScaleFactorRoundingPolicy(
17
+ Qt.HighDpiScaleFactorRoundingPolicy.PassThrough
18
+ )
19
+ except Exception:
20
+ pass
21
+
22
+ from molforge.ui.theme import STYLE, load_saved_typography, load_saved_theme, apply_global_typography
23
+ from molforge.ui.window import MolForgeWindow
24
+ from molforge.ui.welcome_window import AppController, WelcomeWindow
25
+
26
+
27
+ def run_application(argv: list[str] | None = None, default_mode: str = "welcome") -> int:
28
+ args = list(sys.argv if argv is None else argv)
29
+ app = QApplication.instance() or QApplication(args)
30
+ app.setApplicationName("MolForge")
31
+ app.setApplicationVersion(__version__)
32
+ try:
33
+ family, size = load_saved_typography()
34
+ theme_name, accent = load_saved_theme()
35
+ apply_global_typography(family, size, theme_name=theme_name, accent=accent)
36
+ except Exception:
37
+ try:
38
+ from PyQt6.QtGui import QFont
39
+ app_font = QFont("Microsoft YaHei UI", 10)
40
+ app_font.setStyleStrategy(QFont.StyleStrategy.PreferAntialias)
41
+ app.setFont(app_font)
42
+ except Exception:
43
+ pass
44
+ app.setStyleSheet(STYLE)
45
+
46
+ mode = default_mode
47
+ for i, a in enumerate(args):
48
+ if a == "--mode" and i + 1 < len(args):
49
+ mode = args[i + 1].strip().lower()
50
+ elif a == "--welcome":
51
+ mode = "welcome"
52
+
53
+ ctrl = AppController.instance()
54
+ if mode == "welcome":
55
+ ctrl.show_welcome()
56
+ elif mode in ("2d", "3d", "split"):
57
+ ctrl.launch_system(mode) # type: ignore[arg-type]
58
+ else:
59
+ window = MolForgeWindow()
60
+ window.show()
61
+ ctrl.active_windows.append(window)
62
+
63
+ return app.exec()
64
+
65
+
66
+ def main():
67
+ sys.exit(run_application(sys.argv, default_mode="welcome"))
68
+
69
+
70
+ if __name__ == "__main__":
71
+ main()
molforge/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ """
2
+ MolForge - 分子编辑器包
3
+ =====================
4
+ 一个给计算化学研究生用的轻量分子编辑器,基于 PyQt6 + RDKit。
5
+ """
6
+
7
+ import sys, os
8
+
9
+ # 保护 Windows Python 3.13 下 platform / numpy.testing 的 WMI COM 崩溃
10
+ if sys.platform == "win32":
11
+ try:
12
+ import platform
13
+ _wv = sys.getwindowsversion()
14
+ platform._wmi_query = lambda *a, **kw: (f"{_wv.major}.{_wv.minor}.{_wv.build}", 1, "Multiprocessor Free", 0, 0)
15
+ except Exception:
16
+ pass
17
+
18
+ __version__ = "7.4.3"
19
+ __app_name__ = "MolForge"
@@ -0,0 +1,15 @@
1
+ """
2
+ ai/ - LLM 操作层
3
+ =================
4
+ AIContext 持有当前分子,通过工具操作它。
5
+ LLM 通过 function calling / MCP 调用 AIContext 的方法。
6
+ """
7
+
8
+ __all__ = ["AIContext"]
9
+
10
+
11
+ def __getattr__(name: str):
12
+ if name == "AIContext":
13
+ from .tools import AIContext
14
+ return AIContext
15
+ raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
@@ -0,0 +1,185 @@
1
+ """
2
+ ai/deepseek_harness.py - MolForge <-> DeepSeek Harness 深度联动桥接器
3
+ ==================================================================
4
+ 功能:
5
+ 1. 自动探测本机 DeepSeek Harness 可执行程序 (E:\\DeepseekHarness\\DeepSeek Harness.exe 等)
6
+ 2. 将 MolForge 全部 18 项分子搭建/精细编辑/量化计算 MCP 工具及使用规范自动写入
7
+ ~/.dsh/skills/molforge-workbench/SKILL.md,让 DeepSeek Harness Agent 彻底掌握本软件
8
+ 3. 生成带有 MolForge 专属图标 (molforge_logo.ico) 的启动快捷方式与 MCP 配置文件,
9
+ 实现在 MolForge AI 面板中一键启动 DeepSeek Harness 并联动当前活动分子
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import subprocess
16
+ import sys
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from ..runtime import data_dir
21
+
22
+ _REPO_ROOT = Path(__file__).resolve().parents[2]
23
+ _ICON_ICO = _REPO_ROOT / "molforge" / "ui" / "assets" / "molforge_logo.ico"
24
+ _ICON_PNG = _REPO_ROOT / "molforge" / "ui" / "assets" / "molforge_logo.png"
25
+
26
+ _DSH_CANDIDATES = (
27
+ Path(r"E:\DeepseekHarness\DeepSeek Harness.exe"),
28
+ Path(r"D:\DeepseekHarness\DeepSeek Harness.exe"),
29
+ Path.home() / "AppData" / "Local" / "Programs" / "deepseek-harness" / "DeepSeek Harness.exe",
30
+ )
31
+
32
+
33
+ def find_deepseek_harness_exe() -> Path | None:
34
+ env_p = os.environ.get("MOLFORGE_DSH_EXE", "").strip()
35
+ if env_p and Path(env_p).is_file():
36
+ return Path(env_p)
37
+ for cand in _DSH_CANDIDATES:
38
+ if cand.is_file():
39
+ return cand
40
+ return None
41
+
42
+
43
+ def get_custom_icon_path() -> Path | None:
44
+ if _ICON_ICO.is_file():
45
+ return _ICON_ICO
46
+ if _ICON_PNG.is_file():
47
+ return _ICON_PNG
48
+ return None
49
+
50
+
51
+ def build_molforge_skill_markdown(python_exe: str, repo_root: Path, mcp_conn_path: Path) -> str:
52
+ return f"""---
53
+ name: molforge-workbench
54
+ description: 控制正在运行的 MolForge 分子工作台,实时读取、搭建、精细修改当前活动分子并执行量子化学/几何优化计算。
55
+ ---
56
+
57
+ # MolForge 分子工作台联动指南 (Desktop MCP)
58
+
59
+ 当用户通过 **MolForge** 启动 DeepSeek Harness 时,MolForge 已在后台开启了**活动文档桌面 MCP 桥接服务**。你可以通过 stdio MCP 服务实时操作用户当前正在编辑的分子标签页(所有修改均走 `CommandBus`,支持视口实时刷新与 `Ctrl+Z` 撤销)。
60
+
61
+ ## 1. MCP 服务启动方式
62
+ - **Python**: `{python_exe}`
63
+ - **参数**: `["-m", "molforge.ai.mcp.mcp_server"]`
64
+ - **工作目录**: `{repo_root}`
65
+ - **环境变量**: `PYTHONPATH={repo_root}`, `MOLFORGE_DATA_DIR={data_dir()}`
66
+ - **桌面连接凭证**: `{mcp_conn_path}`(自动读取当前活动文档的本机端口与 Token)
67
+
68
+ ## 2. 可用分子搭建与精细编辑工具(共 18 项)
69
+ - **结构读取**: `get_molecule_info`(化学式、原子坐标、点群、电荷、自旋)
70
+ - **从头搭建 / 拼接**:
71
+ - `build_from_smiles(smiles, name)`:根据 SMILES 一键生成 3D 构象并加入画布
72
+ - `add_ring(size, aromatic, attach_to)`:添加苯环/杂环/脂环,支持接枝到指定 1-based 原子
73
+ - `add_atom(atomic_num, near_atom, x, y, z)`:在指定原子旁或绝对坐标添加原子
74
+ - `add_bond(atom_a, atom_b)`:在两原子间成键
75
+ - **精细改分子**:
76
+ - `change_element(atom_index, new_atomic_num)`:替换原子元素(如 C -> N/O/S/F)
77
+ - `change_bond_order(atom_a, atom_b, order)`:修改键级(1单 / 2双 / 3三 / 4芳香)
78
+ - `modify_internal_coordinate(coord_type, atoms, target_value)`:精确修改键长 (Å)、键角 (°)、二面角 (°) 并刚体联动旋转子图
79
+ - `set_atom_charge(atom_index, formal_charge)`:设置形式电荷
80
+ - `delete_atom(atom_index)`:删除原子及相连键
81
+ - `clean_geometry_3d()`:执行 MMFF94/UFF 3D 力场几何弛豫
82
+ - `undo_last()` / `redo_last()`:撤销或重做上一步操作
83
+ - **量化与结构分析**:
84
+ - `run_calchem_scf(basis)` / `run_calchem_opt(basis, max_steps)`:CalChem Rust 内核秒级 RHF 与 BFGS 优化
85
+ - `run_rest_scf(xc, basis)`:WSL2 复旦 REST 双杂化/DFT 计算
86
+ - `run_planarity()`:计算重原子最佳拟合平面度 (MPP)
87
+ - `generate_hpc_slurm_script(engine, job_name, n_cores, memory_mb, walltime)`:生成超算 Slurm 脚本
88
+ """
89
+
90
+
91
+ def prepare_deepseek_harness_bundle(dsh_home: Path | None = None) -> dict[str, Any]:
92
+ """同步 MolForge Skill、MCP 配置 JSON 与带 MolForge 专属图标的启动快捷方式。"""
93
+ exe = find_deepseek_harness_exe()
94
+ home = dsh_home or (Path.home() / ".dsh")
95
+ skill_dir = home / "skills" / "molforge-workbench"
96
+ skill_dir.mkdir(parents=True, exist_ok=True)
97
+
98
+ python_exe = sys.executable
99
+ conn_path = data_dir() / "mcp" / "desktop.json"
100
+ skill_path = skill_dir / "SKILL.md"
101
+ skill_path.write_text(build_molforge_skill_markdown(python_exe, _REPO_ROOT, conn_path), encoding="utf-8")
102
+
103
+ out_dir = data_dir() / "deepseek_harness"
104
+ out_dir.mkdir(parents=True, exist_ok=True)
105
+ mcp_cfg = {
106
+ "mcpServers": {
107
+ "molforge": {
108
+ "command": python_exe,
109
+ "args": ["-m", "molforge.ai.mcp.mcp_server"],
110
+ "cwd": str(_REPO_ROOT),
111
+ "env": {
112
+ "PYTHONPATH": str(_REPO_ROOT),
113
+ "MOLFORGE_DATA_DIR": str(data_dir()),
114
+ },
115
+ }
116
+ }
117
+ }
118
+ cfg_path = out_dir / "molforge_mcp_config.json"
119
+ cfg_path.write_text(json.dumps(mcp_cfg, ensure_ascii=False, indent=2), encoding="utf-8")
120
+
121
+ lnk_path = out_dir / "MolForge_DeepSeek_Harness.lnk"
122
+ icon_path = get_custom_icon_path()
123
+ if sys.platform == "win32" and exe is not None:
124
+ _create_windows_shortcut(lnk_path, exe, _REPO_ROOT, icon_path)
125
+
126
+ return {
127
+ "exe": str(exe) if exe else None,
128
+ "skill_path": str(skill_path),
129
+ "mcp_config_path": str(cfg_path),
130
+ "shortcut_path": str(lnk_path) if lnk_path.is_file() else None,
131
+ "icon_path": str(icon_path) if icon_path else None,
132
+ }
133
+
134
+
135
+ def _create_windows_shortcut(lnk_path: Path, target_exe: Path, work_dir: Path, icon_path: Path | None) -> None:
136
+ def _ps_quote(val: str) -> str:
137
+ return "'" + val.replace("'", "''") + "'"
138
+
139
+ icon_line = f"$s.IconLocation = {_ps_quote(str(icon_path))}" if icon_path and icon_path.suffix.lower() == ".ico" else ""
140
+ script = "\n".join([
141
+ "$ws = New-Object -ComObject WScript.Shell",
142
+ f"$s = $ws.CreateShortcut({_ps_quote(str(lnk_path))})",
143
+ f"$s.TargetPath = {_ps_quote(str(target_exe))}",
144
+ f"$s.WorkingDirectory = {_ps_quote(str(work_dir))}",
145
+ "$s.Description = 'MolForge x DeepSeek Harness AI Workbench'",
146
+ icon_line,
147
+ "$s.Save()",
148
+ ])
149
+ subprocess.run(
150
+ ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script],
151
+ capture_output=True,
152
+ text=True,
153
+ timeout=10,
154
+ check=False,
155
+ )
156
+
157
+
158
+ def launch_deepseek_harness(desktop_mcp_service=None) -> dict[str, Any]:
159
+ """确保桌面 MCP 监听开启、写入联动 Skill 与专属图标快捷方式,并拉起 DeepSeek Harness。"""
160
+ mcp_info = None
161
+ if desktop_mcp_service is not None:
162
+ mcp_info = desktop_mcp_service.start()
163
+
164
+ bundle = prepare_deepseek_harness_bundle()
165
+ exe = bundle.get("exe")
166
+ if not exe:
167
+ return {
168
+ "ok": False,
169
+ "error": "未找到 DeepSeek Harness(请确认已安装至 E:\\DeepseekHarness\\DeepSeek Harness.exe 或设置 MOLFORGE_DSH_EXE)。",
170
+ **bundle,
171
+ "mcp": mcp_info,
172
+ }
173
+
174
+ lnk = bundle.get("shortcut_path")
175
+ if sys.platform == "win32" and lnk and Path(lnk).is_file():
176
+ os.startfile(lnk)
177
+ else:
178
+ subprocess.Popen([exe, str(_REPO_ROOT)], cwd=str(_REPO_ROOT))
179
+
180
+ return {
181
+ "ok": True,
182
+ "launched": lnk or exe,
183
+ "mcp": mcp_info,
184
+ **bundle,
185
+ }
@@ -0,0 +1,38 @@
1
+ """Stdio-to-desktop MCP forwarding with explicit local authentication."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import socket
6
+ import sys
7
+ from pathlib import Path
8
+
9
+
10
+ def request_via_desktop(connection_path: str | Path, request: dict, timeout: float = 30.0) -> dict:
11
+ path = Path(connection_path)
12
+ connection = json.loads(path.read_text(encoding="utf-8"))
13
+ if not connection.get("active") or connection.get("protocol") != "molforge-desktop-mcp-v1":
14
+ raise RuntimeError("桌面 MCP 服务未启动,请先在 MolForge 工具菜单中启动")
15
+ envelope = {"token": connection["token"], "request": request}
16
+ with socket.create_connection((connection["host"], int(connection["port"])), timeout=timeout) as client:
17
+ client.settimeout(timeout)
18
+ client.sendall(json.dumps(envelope, ensure_ascii=False).encode("utf-8") + b"\n")
19
+ reader = client.makefile("rb")
20
+ line = reader.readline(8 * 1024 * 1024 + 1)
21
+ if not line or len(line) > 8 * 1024 * 1024:
22
+ raise RuntimeError("桌面 MCP 返回为空或消息过大")
23
+ return json.loads(line.decode("utf-8"))
24
+
25
+
26
+ def run_desktop_stdio_loop(connection_path: str | Path):
27
+ for line in sys.stdin:
28
+ if not line.strip():
29
+ continue
30
+ request_id = None
31
+ try:
32
+ request = json.loads(line)
33
+ request_id = request.get("id")
34
+ response = request_via_desktop(connection_path, request)
35
+ except Exception as exc:
36
+ response = {"jsonrpc": "2.0", "id": request_id, "error": {"code": -32000, "message": str(exc)}}
37
+ sys.stdout.write(json.dumps(response, ensure_ascii=False) + "\n")
38
+ sys.stdout.flush()
@@ -0,0 +1,121 @@
1
+ """Authenticated localhost MCP service running in the desktop's Qt main thread."""
2
+ from __future__ import annotations
3
+
4
+ import hmac
5
+ import json
6
+ import secrets
7
+ from pathlib import Path
8
+
9
+ from PyQt6.QtCore import QObject
10
+ from PyQt6.QtNetwork import QHostAddress, QTcpServer, QTcpSocket
11
+
12
+ from ...runtime import data_dir
13
+ from .mcp_server import MolForgeMCPServer
14
+
15
+
16
+ class DesktopMCPService(QObject):
17
+ """Expose the *current* desktop document to local MCP clients.
18
+
19
+ Every request constructs a lightweight protocol handler around the latest
20
+ document/command-bus references. QTcpServer delivers requests on the GUI
21
+ thread, so command listeners and VTK updates never run on a socket worker.
22
+ """
23
+
24
+ MAX_MESSAGE_BYTES = 8 * 1024 * 1024
25
+
26
+ def __init__(self, document_provider, command_bus_provider, connection_path=None, parent=None):
27
+ super().__init__(parent)
28
+ self._document_provider = document_provider
29
+ self._command_bus_provider = command_bus_provider
30
+ self.connection_path = Path(connection_path) if connection_path else data_dir() / "mcp" / "desktop.json"
31
+ self._tcp = QTcpServer(self)
32
+ self._tcp.newConnection.connect(self._accept_connections)
33
+ self._clients: set[QTcpSocket] = set()
34
+ self._buffers: dict[QTcpSocket, bytes] = {}
35
+ self._token = ""
36
+
37
+ @property
38
+ def is_active(self) -> bool:
39
+ return self._tcp.isListening()
40
+
41
+ @property
42
+ def port(self) -> int:
43
+ return int(self._tcp.serverPort())
44
+
45
+ def start(self) -> dict:
46
+ if self.is_active:
47
+ return self.connection_info(include_token=True)
48
+ self._token = secrets.token_urlsafe(32)
49
+ if not self._tcp.listen(QHostAddress.SpecialAddress.LocalHost, 0):
50
+ raise RuntimeError(f"无法监听本机 MCP 端口: {self._tcp.errorString()}")
51
+ self._write_connection_file(active=True)
52
+ return self.connection_info(include_token=True)
53
+
54
+ def stop(self):
55
+ for client in list(self._clients):
56
+ client.disconnectFromHost()
57
+ client.close()
58
+ self._clients.clear()
59
+ self._buffers.clear()
60
+ self._tcp.close()
61
+ self._write_connection_file(active=False)
62
+
63
+ def connection_info(self, include_token: bool = False) -> dict:
64
+ info = {
65
+ "active": self.is_active,
66
+ "protocol": "molforge-desktop-mcp-v1",
67
+ "host": "127.0.0.1",
68
+ "port": self.port,
69
+ }
70
+ if include_token:
71
+ info["token"] = self._token
72
+ return info
73
+
74
+ def _write_connection_file(self, active: bool):
75
+ self.connection_path.parent.mkdir(parents=True, exist_ok=True)
76
+ payload = self.connection_info(include_token=active)
77
+ temporary = self.connection_path.with_suffix(".tmp")
78
+ temporary.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
79
+ temporary.replace(self.connection_path)
80
+
81
+ def _accept_connections(self):
82
+ while self._tcp.hasPendingConnections():
83
+ client = self._tcp.nextPendingConnection()
84
+ self._clients.add(client)
85
+ self._buffers[client] = b""
86
+ client.readyRead.connect(lambda c=client: self._read_client(c))
87
+ client.disconnected.connect(lambda c=client: self._discard_client(c))
88
+
89
+ def _discard_client(self, client):
90
+ self._clients.discard(client)
91
+ self._buffers.pop(client, None)
92
+ client.deleteLater()
93
+
94
+ def _send(self, client, response):
95
+ payload = (json.dumps(response, ensure_ascii=False) + "\n").encode("utf-8")
96
+ client.write(payload)
97
+ client.flush()
98
+
99
+ def _read_client(self, client):
100
+ self._buffers[client] = self._buffers.get(client, b"") + bytes(client.readAll())
101
+ if len(self._buffers[client]) > self.MAX_MESSAGE_BYTES:
102
+ self._send(client, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "MCP message too large"}})
103
+ client.disconnectFromHost()
104
+ return
105
+ while b"\n" in self._buffers.get(client, b""):
106
+ raw, self._buffers[client] = self._buffers[client].split(b"\n", 1)
107
+ request_id = None
108
+ try:
109
+ envelope = json.loads(raw.decode("utf-8"))
110
+ token = str(envelope.get("token", ""))
111
+ if not hmac.compare_digest(token, self._token):
112
+ raise PermissionError("invalid desktop MCP token")
113
+ request = envelope.get("request")
114
+ if not isinstance(request, dict):
115
+ raise ValueError("missing JSON-RPC request")
116
+ request_id = request.get("id")
117
+ handler = MolForgeMCPServer(self._document_provider(), self._command_bus_provider())
118
+ response = handler.handle_request(request)
119
+ except Exception as exc:
120
+ response = {"jsonrpc": "2.0", "id": request_id, "error": {"code": -32600, "message": str(exc)}}
121
+ self._send(client, response)