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
@@ -0,0 +1,780 @@
1
+ """
2
+ molforge/ai/mcp/mcp_server.py - 工业标准 Model Context Protocol (MCP) 服务端
3
+ ========================================================================
4
+ 遵循 Anthropic / Open Protocol 标准 (JSON-RPC 2.0 stdio):
5
+ - 允许外部 AI Agent (Claude 3.7/3.5, Gemini 2.0, DeepSeek R1, GPT-4o, Cursor, Antigravity)
6
+ 作为智能大脑直接通过 MCP 协议感知并控制 MolForge!
7
+ - 导出四大核心能力:
8
+ 1. Tools: 分子几何感知、原子编辑(加/删/连键)、精确内坐标微调、CalChem 原生量化计算、Linux Slurm HPC 任务打包
9
+ 2. Resources: 当前活动分子结构 (molecule://active/json, molecule://active/xyz)
10
+ 3. Prompts: 预置化学家专家提示词 (DFT计算向导、构象搜索、机理推导)
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import sys
17
+ from typing import Any, Callable, Dict, List, Optional
18
+ import numpy as np
19
+
20
+ # 强制 UTF-8 标准输入输出 (MCP 工业协议规范强制要求)
21
+ if hasattr(sys.stdout, "reconfigure"):
22
+ try:
23
+ sys.stdout.reconfigure(encoding="utf-8")
24
+ sys.stderr.reconfigure(encoding="utf-8")
25
+ sys.stdin.reconfigure(encoding="utf-8")
26
+ except Exception:
27
+ pass
28
+
29
+ from ... import __version__
30
+ MCP_PROTOCOL_VERSION = "2024-11-05"
31
+
32
+
33
+ class MolForgeMCPServer:
34
+ """基于标准 JSON-RPC 2.0 的 MolForge MCP 服务端。"""
35
+
36
+ def __init__(self, document=None, command_bus=None):
37
+ self.document = document
38
+ self.command_bus = command_bus
39
+ self._tools: Dict[str, Callable[[Dict[str, Any]], Dict[str, Any]]] = {}
40
+ self._register_default_tools()
41
+
42
+ def set_context(self, document, command_bus=None):
43
+ self.document = document
44
+ self.command_bus = command_bus
45
+
46
+ def _aid_at_1based(self, idx: int):
47
+ if not self.document:
48
+ return None
49
+ atoms = list(self.document.topology.atom_ids)
50
+ return next((aid for aid in atoms if aid.value + 1 == idx), None)
51
+
52
+ def _register_default_tools(self) -> None:
53
+ self._tools["get_molecule_info"] = self._tool_get_molecule_info
54
+ self._tools["add_atom"] = self._tool_add_atom
55
+ self._tools["delete_atom"] = self._tool_delete_atom
56
+ self._tools["add_bond"] = self._tool_add_bond
57
+ self._tools["modify_internal_coordinate"] = self._tool_modify_internal_coordinate
58
+ self._tools["run_calchem_scf"] = self._tool_run_calchem_scf
59
+ self._tools["run_calchem_opt"] = self._tool_run_calchem_opt
60
+ self._tools["generate_hpc_slurm_script"] = self._tool_generate_hpc_slurm_script
61
+ self._tools["run_planarity"] = self._tool_run_planarity
62
+ self._tools["run_rest_scf"] = self._tool_run_rest_scf
63
+ self._tools["build_from_smiles"] = self._tool_build_from_smiles
64
+ self._tools["add_ring"] = self._tool_add_ring
65
+ self._tools["change_element"] = self._tool_change_element
66
+ self._tools["change_bond_order"] = self._tool_change_bond_order
67
+ self._tools["clean_geometry_3d"] = self._tool_clean_geometry_3d
68
+ self._tools["set_atom_charge"] = self._tool_set_atom_charge
69
+ self._tools["undo_last"] = self._tool_undo_last
70
+ self._tools["redo_last"] = self._tool_redo_last
71
+
72
+ def get_tool_definitions(self) -> List[Dict[str, Any]]:
73
+ return [
74
+ {
75
+ "name": "get_molecule_info",
76
+ "description": "获取 MolForge 当前活动分子的完整化学信息(化学式、原子序数、3D 坐标、点群、电荷与自旋)。",
77
+ "inputSchema": {
78
+ "type": "object",
79
+ "properties": {},
80
+ },
81
+ },
82
+ {
83
+ "name": "add_atom",
84
+ "description": "在指定已有原子附近添加一个新原子,或在指定 3D 坐标处添加原子(通过命令总线执行,支持可撤销)。",
85
+ "inputSchema": {
86
+ "type": "object",
87
+ "properties": {
88
+ "near_atom": {"type": "integer", "description": "参考原子的 1-based 序号", "minimum": 1},
89
+ "atomic_num": {"type": "integer", "description": "新原子的原子序数 (1~118)", "minimum": 1, "maximum": 118},
90
+ "x": {"type": "number", "description": "可选绝对 X 坐标 (Å)"},
91
+ "y": {"type": "number", "description": "可选绝对 Y 坐标 (Å)"},
92
+ "z": {"type": "number", "description": "可选绝对 Z 坐标 (Å)"},
93
+ },
94
+ "required": ["atomic_num"],
95
+ },
96
+ },
97
+ {
98
+ "name": "delete_atom",
99
+ "description": "删除指定 1-based 序号的原子及其相关化学键(通过命令总线执行,支持可撤销)。",
100
+ "inputSchema": {
101
+ "type": "object",
102
+ "properties": {
103
+ "atom_index": {"type": "integer", "description": "要删除原子的 1-based 序号", "minimum": 1},
104
+ },
105
+ "required": ["atom_index"],
106
+ },
107
+ },
108
+ {
109
+ "name": "add_bond",
110
+ "description": "在两个已有原子之间添加化学键(通过命令总线执行,支持可撤销)。",
111
+ "inputSchema": {
112
+ "type": "object",
113
+ "properties": {
114
+ "atom_a": {"type": "integer", "description": "第一个原子 1-based 序号", "minimum": 1},
115
+ "atom_b": {"type": "integer", "description": "第二个原子 1-based 序号", "minimum": 1},
116
+ },
117
+ "required": ["atom_a", "atom_b"],
118
+ },
119
+ },
120
+ {
121
+ "name": "modify_internal_coordinate",
122
+ "description": "严格保序精确修改分子的内坐标(键长/键角/二面角),自动联动旋转连通子图刚体几何,保持其他键长不变(可撤销)。",
123
+ "inputSchema": {
124
+ "type": "object",
125
+ "properties": {
126
+ "coord_type": {
127
+ "type": "string",
128
+ "enum": ["bond_length", "bond_angle", "dihedral"],
129
+ "description": "内坐标类型",
130
+ },
131
+ "atoms": {
132
+ "type": "array",
133
+ "items": {"type": "integer"},
134
+ "description": "原子编号列表 (1-based序号)。键长需2个,键角需3个(中间为顶点),二面角需4个。",
135
+ },
136
+ "target_value": {
137
+ "type": "number",
138
+ "description": "目标数值(键长单位为 Å,键角/二面角单位为度 °)",
139
+ },
140
+ },
141
+ "required": ["coord_type", "atoms", "target_value"],
142
+ },
143
+ },
144
+ {
145
+ "name": "run_calchem_scf",
146
+ "description": "调用 CalChem 纯 Rust 内核秒级执行从头算 RHF 自洽场计算,获取精确总能量、HOMO/LUMO 能级、能隙与偶极矩。",
147
+ "inputSchema": {
148
+ "type": "object",
149
+ "properties": {
150
+ "basis": {
151
+ "type": "string",
152
+ "enum": ["sto-3g", "6-31g", "6-31g(d)", "6-31g(d,p)", "lanl2dz"],
153
+ "default": "sto-3g",
154
+ "description": "量化计算基组",
155
+ },
156
+ },
157
+ },
158
+ },
159
+ {
160
+ "name": "run_calchem_opt",
161
+ "description": "调用 CalChem 纯 Rust BFGS 算法执行高精度 3D 几何构象优化,并自动通过命令总线回填更新视口(支持可撤销)。",
162
+ "inputSchema": {
163
+ "type": "object",
164
+ "properties": {
165
+ "basis": {"type": "string", "default": "sto-3g"},
166
+ "max_steps": {"type": "integer", "default": 50},
167
+ },
168
+ },
169
+ },
170
+ {
171
+ "name": "generate_hpc_slurm_script",
172
+ "description": "为当前分子生成可直接提交至远程 Linux 超算集群运行的 Slurm 批处理计算脚本 (Gaussian/ORCA/GROMACS/CalChem)。",
173
+ "inputSchema": {
174
+ "type": "object",
175
+ "properties": {
176
+ "engine": {"type": "string", "enum": ["g16", "orca", "gromacs", "xtb", "calchem"]},
177
+ "job_name": {"type": "string", "default": "chem_calc"},
178
+ "n_cores": {"type": "integer", "default": 16},
179
+ "memory_mb": {"type": "integer", "default": 32000},
180
+ "walltime": {"type": "string", "default": "24:00:00"},
181
+ },
182
+ "required": ["engine"],
183
+ },
184
+ },
185
+ {
186
+ "name": "run_planarity",
187
+ "description": "对当前分子计算重原子最佳拟合平面的平面度 RMSD(MPP)与最大离面距离。",
188
+ "inputSchema": {
189
+ "type": "object",
190
+ "properties": {},
191
+ },
192
+ },
193
+ {
194
+ "name": "run_rest_scf",
195
+ "description": "在 WSL2 环境中调用复旦大学 REST (Rust-based Electronic Structure Toolkit) 原生执行真实 DFT/双杂化 SCF 计算,获取总能量、Mulliken 电荷与轨道能隙。",
196
+ "inputSchema": {
197
+ "type": "object",
198
+ "properties": {
199
+ "xc": {
200
+ "type": "string",
201
+ "enum": ["b3lyp", "hf", "pbe0", "wb97xd", "cam-b3lyp", "xyg3", "xygjos", "r-xdh7"],
202
+ "default": "b3lyp",
203
+ "description": "交换相关泛函或双杂化方法",
204
+ },
205
+ "basis": {
206
+ "type": "string",
207
+ "enum": ["STO-3G", "def2-SVP", "def2-TZVP", "6-31G*", "cc-pVDZ"],
208
+ "default": "def2-SVP",
209
+ "description": "基组名称",
210
+ },
211
+ },
212
+ },
213
+ },
214
+ {
215
+ "name": "build_from_smiles",
216
+ "description": "根据 SMILES 字符串一键生成带 3D 构象的分子或片段,追加到当前画布(通过命令总线执行,支持可撤销)。",
217
+ "inputSchema": {
218
+ "type": "object",
219
+ "properties": {
220
+ "smiles": {"type": "string", "description": "有效 SMILES,如 c1ccccc1、CC(=O)O、O"},
221
+ "name": {"type": "string", "description": "可选分子名称"},
222
+ },
223
+ "required": ["smiles"],
224
+ },
225
+ },
226
+ {
227
+ "name": "add_ring",
228
+ "description": "在画布中添加环系(苯环、噻吩、吡啶、环己烷等),可选接枝到已有原子上(可撤销)。",
229
+ "inputSchema": {
230
+ "type": "object",
231
+ "properties": {
232
+ "size": {"type": "integer", "default": 6, "minimum": 3, "maximum": 12},
233
+ "aromatic": {"type": "boolean", "default": True},
234
+ "attach_to": {"type": "integer", "description": "可选接枝锚点原子的 1-based 序号", "minimum": 1},
235
+ },
236
+ },
237
+ },
238
+ {
239
+ "name": "change_element",
240
+ "description": "将指定原子替换为新元素(如将 C 替换为 N/O/S/F 等,可撤销)。",
241
+ "inputSchema": {
242
+ "type": "object",
243
+ "properties": {
244
+ "atom_index": {"type": "integer", "description": "原子 1-based 序号", "minimum": 1},
245
+ "new_atomic_num": {"type": "integer", "description": "新原子序数 (1~118)", "minimum": 1, "maximum": 118},
246
+ },
247
+ "required": ["atom_index", "new_atomic_num"],
248
+ },
249
+ },
250
+ {
251
+ "name": "change_bond_order",
252
+ "description": "修改两个原子之间的键级(1=单键, 2=双键, 3=三键, 4=芳香键),若尚未成键则自动新建(可撤销)。",
253
+ "inputSchema": {
254
+ "type": "object",
255
+ "properties": {
256
+ "atom_a": {"type": "integer", "minimum": 1},
257
+ "atom_b": {"type": "integer", "minimum": 1},
258
+ "order": {"type": "integer", "enum": [1, 2, 3, 4], "default": 2},
259
+ },
260
+ "required": ["atom_a", "atom_b", "order"],
261
+ },
262
+ },
263
+ {
264
+ "name": "clean_geometry_3d",
265
+ "description": "执行 3D 分子力场几何弛豫优化 (MMFF94/UFF),使新搭建或修改后的分子构型合理(可撤销)。",
266
+ "inputSchema": {"type": "object", "properties": {}},
267
+ },
268
+ {
269
+ "name": "set_atom_charge",
270
+ "description": "设置指定原子的形式电荷(可撤销)。",
271
+ "inputSchema": {
272
+ "type": "object",
273
+ "properties": {
274
+ "atom_index": {"type": "integer", "minimum": 1},
275
+ "formal_charge": {"type": "integer", "minimum": -4, "maximum": 4},
276
+ },
277
+ "required": ["atom_index", "formal_charge"],
278
+ },
279
+ },
280
+ {
281
+ "name": "undo_last",
282
+ "description": "撤销上一步分子编辑操作。",
283
+ "inputSchema": {"type": "object", "properties": {}},
284
+ },
285
+ {
286
+ "name": "redo_last",
287
+ "description": "重做上一步被撤销的分子编辑操作。",
288
+ "inputSchema": {"type": "object", "properties": {}},
289
+ },
290
+ ]
291
+
292
+ # ---------- 具体工具逻辑实现 ----------
293
+ def _tool_get_molecule_info(self, args: Dict[str, Any]) -> Dict[str, Any]:
294
+ if not self.document:
295
+ return {"error": "当前未加载分子文档"}
296
+ doc = self.document
297
+ atom_ids = list(doc.topology.atom_ids)
298
+ atoms = []
299
+ for aid in atom_ids:
300
+ a = doc.topology.get_atom(aid)
301
+ pos = doc.get_atom_3d_pos(aid) if doc.has_3d else None
302
+ atoms.append({
303
+ "index": aid.value + 1,
304
+ "atomic_num": a.atomic_num,
305
+ "symbol": getattr(a, "symbol", "X"),
306
+ "xyz": pos.tolist() if pos is not None else None,
307
+ })
308
+ return {
309
+ "name": doc.name,
310
+ "num_atoms": doc.num_atoms,
311
+ "num_bonds": doc.topology.num_bonds,
312
+ "has_3d": doc.has_3d,
313
+ "formula": doc.formula if hasattr(doc, "formula") else "",
314
+ "atoms": atoms,
315
+ }
316
+
317
+ def _tool_add_atom(self, args: Dict[str, Any]) -> Dict[str, Any]:
318
+ if not self.document:
319
+ return {"error": "未找到当前分子"}
320
+ from ...application.builtin_commands import AddAtomCommand
321
+ near_atom = args.get("near_atom")
322
+ aid = self._aid_at_1based(near_atom) if near_atom is not None else None
323
+ if near_atom is not None and aid is None:
324
+ return {"error": f"参考原子 #{near_atom} 越界", "success": False}
325
+ x = args.get("x")
326
+ y = args.get("y")
327
+ z = args.get("z")
328
+ bus = self.command_bus
329
+ if not bus:
330
+ from ...application.command_bus import CommandBus
331
+ bus = CommandBus(self.document)
332
+ res = bus.execute(AddAtomCommand(
333
+ atomic_num=args.get("atomic_num", 6),
334
+ x=x, y=y, z=z,
335
+ bond_to=aid,
336
+ ))
337
+ if not getattr(res, "success", True):
338
+ return {"error": getattr(res, "message", "添加原子失败"), "success": False}
339
+ return {
340
+ "success": True,
341
+ "message": getattr(res, "message", ""),
342
+ "num_atoms": self.document.num_atoms,
343
+ }
344
+
345
+ def _tool_delete_atom(self, args: Dict[str, Any]) -> Dict[str, Any]:
346
+ if not self.document:
347
+ return {"error": "未找到当前分子"}
348
+ from ...application.builtin_commands import DeleteAtomCommand
349
+ aid = self._aid_at_1based(args["atom_index"])
350
+ if aid is None:
351
+ return {"error": f"原子 #{args['atom_index']} 越界"}
352
+ bus = self.command_bus
353
+ if not bus:
354
+ from ...application.command_bus import CommandBus
355
+ bus = CommandBus(self.document)
356
+ res = bus.execute(DeleteAtomCommand(aid))
357
+ return {
358
+ "success": getattr(res, "success", True),
359
+ "message": getattr(res, "message", ""),
360
+ "num_atoms": self.document.num_atoms,
361
+ }
362
+
363
+ def _tool_add_bond(self, args: Dict[str, Any]) -> Dict[str, Any]:
364
+ if not self.document:
365
+ return {"error": "未找到当前分子"}
366
+ from ...application.builtin_commands import AddBondCommand
367
+ a = self._aid_at_1based(args["atom_a"])
368
+ b = self._aid_at_1based(args["atom_b"])
369
+ if a is None or b is None:
370
+ return {"error": "成键原子编号越界"}
371
+ bus = self.command_bus
372
+ if not bus:
373
+ from ...application.command_bus import CommandBus
374
+ bus = CommandBus(self.document)
375
+ res = bus.execute(AddBondCommand(a, b, order=1))
376
+ return {
377
+ "success": getattr(res, "success", True),
378
+ "message": getattr(res, "message", ""),
379
+ "num_bonds": self.document.topology.num_bonds,
380
+ }
381
+
382
+ def _ensure_bus(self):
383
+ if self.command_bus is not None:
384
+ return self.command_bus
385
+ from ...application.command_bus import CommandBus
386
+ return CommandBus(self.document)
387
+
388
+ def _tool_build_from_smiles(self, args: Dict[str, Any]) -> Dict[str, Any]:
389
+ if not self.document:
390
+ return {"error": "未找到当前分子"}
391
+ smiles = str(args.get("smiles", "")).strip()
392
+ if not smiles:
393
+ return {"error": "SMILES 不能为空"}
394
+ from ...io.rdkit_adapter import create_molecule_from_smiles
395
+ from ...application.builtin_commands import AppendMoleculeCommand
396
+ sub_doc = create_molecule_from_smiles(smiles, name=str(args.get("name") or smiles))
397
+ res = self._ensure_bus().execute(AppendMoleculeCommand(sub_doc))
398
+ return {"success": getattr(res, "success", True), "message": getattr(res, "message", ""), "num_atoms": self.document.num_atoms, "num_bonds": self.document.topology.num_bonds}
399
+
400
+ def _tool_add_ring(self, args: Dict[str, Any]) -> Dict[str, Any]:
401
+ if not self.document:
402
+ return {"error": "未找到当前分子"}
403
+ from ...application.builtin_commands import AddRingCommand
404
+ attach_idx = args.get("attach_to")
405
+ attach_aid = self._aid_at_1based(int(attach_idx)) if attach_idx else None
406
+ if attach_idx and attach_aid is None:
407
+ return {"error": f"接枝原子 #{attach_idx} 越界"}
408
+ res = self._ensure_bus().execute(AddRingCommand(
409
+ size=int(args.get("size", 6)),
410
+ aromatic=bool(args.get("aromatic", True)),
411
+ attach_to=attach_aid,
412
+ ))
413
+ return {"success": getattr(res, "success", True), "message": getattr(res, "message", ""), "num_atoms": self.document.num_atoms}
414
+
415
+ def _tool_change_element(self, args: Dict[str, Any]) -> Dict[str, Any]:
416
+ if not self.document:
417
+ return {"error": "未找到当前分子"}
418
+ from ...application.builtin_commands import ChangeElementCommand
419
+ aid = self._aid_at_1based(int(args["atom_index"]))
420
+ if aid is None:
421
+ return {"error": f"原子 #{args['atom_index']} 越界"}
422
+ res = self._ensure_bus().execute(ChangeElementCommand(aid, int(args["new_atomic_num"])))
423
+ return {"success": getattr(res, "success", True), "message": getattr(res, "message", "")}
424
+
425
+ def _tool_change_bond_order(self, args: Dict[str, Any]) -> Dict[str, Any]:
426
+ if not self.document:
427
+ return {"error": "未找到当前分子"}
428
+ from ...application.builtin_commands import ChangeBondOrderCommand, AddBondCommand
429
+ a = self._aid_at_1based(int(args["atom_a"]))
430
+ b = self._aid_at_1based(int(args["atom_b"]))
431
+ if a is None or b is None:
432
+ return {"error": "原子编号越界"}
433
+ order = int(args.get("order", 2))
434
+ bid = self.document.topology.bond_between(a, b)
435
+ cmd = ChangeBondOrderCommand(bid, order) if bid is not None else AddBondCommand(a, b, order=order)
436
+ res = self._ensure_bus().execute(cmd)
437
+ return {"success": getattr(res, "success", True), "message": getattr(res, "message", "")}
438
+
439
+ def _tool_clean_geometry_3d(self, args: Dict[str, Any]) -> Dict[str, Any]:
440
+ if not self.document:
441
+ return {"error": "未找到当前分子"}
442
+ from ...application.builtin_commands import CleanGeometry3DCommand
443
+ res = self._ensure_bus().execute(CleanGeometry3DCommand())
444
+ return {"success": getattr(res, "success", True), "message": getattr(res, "message", "")}
445
+
446
+ def _tool_set_atom_charge(self, args: Dict[str, Any]) -> Dict[str, Any]:
447
+ if not self.document:
448
+ return {"error": "未找到当前分子"}
449
+ from ...application.builtin_commands import ChangeAtomStyleCommand
450
+ aid = self._aid_at_1based(int(args["atom_index"]))
451
+ if aid is None:
452
+ return {"error": f"原子 #{args['atom_index']} 越界"}
453
+ res = self._ensure_bus().execute(ChangeAtomStyleCommand([aid], formal_charge=int(args["formal_charge"])))
454
+ return {"success": getattr(res, "success", True), "message": getattr(res, "message", "")}
455
+
456
+ def _tool_undo_last(self, args: Dict[str, Any]) -> Dict[str, Any]:
457
+ res = self._ensure_bus().undo()
458
+ return {"success": getattr(res, "success", True), "message": getattr(res, "message", ""), "num_atoms": self.document.num_atoms if self.document else 0}
459
+
460
+ def _tool_redo_last(self, args: Dict[str, Any]) -> Dict[str, Any]:
461
+ res = self._ensure_bus().redo()
462
+ return {"success": getattr(res, "success", True), "message": getattr(res, "message", ""), "num_atoms": self.document.num_atoms if self.document else 0}
463
+
464
+ def _tool_run_calchem_scf(self, args: Dict[str, Any]) -> Dict[str, Any]:
465
+ if not self.document:
466
+ return {"error": "未找到当前分子"}
467
+ from ...io.calchem_bridge import run_calchem_single_point
468
+ basis = args.get("basis", "sto-3g")
469
+ res = run_calchem_single_point(self.document, basis=basis)
470
+ if not res.get("success"):
471
+ return {"error": res.get("error", "计算失败")}
472
+ return {
473
+ "converged": res["converged"],
474
+ "total_energy_hartree": res["total_energy_hartree"],
475
+ "homo_energy_hartree": res["homo_energy_hartree"],
476
+ "lumo_energy_hartree": res["lumo_energy_hartree"],
477
+ "gap_ev": res["gap_ev"],
478
+ "dipole_debye": res["dipole_debye"],
479
+ }
480
+
481
+ def _tool_run_calchem_opt(self, args: Dict[str, Any]) -> Dict[str, Any]:
482
+ if not self.document:
483
+ return {"error": "未找到当前分子"}
484
+ from ...io.calchem_bridge import run_calchem_optimization
485
+ basis = args.get("basis", "sto-3g")
486
+ max_steps = args.get("max_steps", 50)
487
+ res = run_calchem_optimization(self.document, basis=basis, max_steps=max_steps)
488
+ if not res.get("success"):
489
+ return {"error": res.get("error", "优化失败")}
490
+ if self.command_bus and "command" in res:
491
+ self.command_bus.execute(res["command"])
492
+ return {
493
+ "converged": res["converged"],
494
+ "steps": res["steps"],
495
+ "final_energy_hartree": res["energy_hartree"],
496
+ "applied_to_viewport": bool(self.command_bus),
497
+ }
498
+
499
+ def _tool_modify_internal_coordinate(self, args: Dict[str, Any]) -> Dict[str, Any]:
500
+ if not self.document:
501
+ return {"error": "未找到当前分子"}
502
+ from ...domain.ids import AtomId
503
+ ctype = args["coord_type"]
504
+ atoms = [AtomId(x - 1) for x in args["atoms"]]
505
+ val = float(args["target_value"])
506
+
507
+ if ctype == "bond_length" and len(atoms) == 2:
508
+ from ...application.builtin_commands import ModifyBondLength3DCommand
509
+ bid = self.document.topology.bond_between(atoms[0], atoms[1])
510
+ if bid is None:
511
+ return {"error": f"原子 #{args['atoms'][0]} 与 #{args['atoms'][1]} 之间不存在化学键"}
512
+ cmd = ModifyBondLength3DCommand(bid, val)
513
+ elif ctype == "bond_angle" and len(atoms) == 3:
514
+ from ...application.internal_coordinates import ModifyAngle3DCommand
515
+ cmd = ModifyAngle3DCommand(atoms[0], atoms[1], atoms[2], val)
516
+ elif ctype == "dihedral" and len(atoms) == 4:
517
+ from ...application.internal_coordinates import ModifyDihedral3DCommand
518
+ cmd = ModifyDihedral3DCommand(atoms[0], atoms[1], atoms[2], atoms[3], val)
519
+ else:
520
+ return {"error": f"不合法的内坐标修改参数 (type={ctype}, atoms={args['atoms']})"}
521
+
522
+ bus = self.command_bus
523
+ if not bus:
524
+ from ...application.command_bus import CommandBus
525
+ bus = CommandBus(self.document)
526
+ r = bus.execute(cmd)
527
+ return {"success": r.success, "message": r.message}
528
+
529
+ def _tool_generate_hpc_slurm_script(self, args: Dict[str, Any]) -> Dict[str, Any]:
530
+ from ...infrastructure.hpc.slurm_generator import SlurmScriptGenerator, JobSpec
531
+ from ...infrastructure.hpc.cluster_config import ClusterProfile
532
+ eng = args["engine"]
533
+ job = JobSpec(
534
+ job_name=args.get("job_name", "chem_job"),
535
+ engine=eng,
536
+ input_file=f"input.{'gjf' if eng == 'g16' else 'inp'}",
537
+ output_file=f"output.{'log' if eng == 'g16' else 'out'}",
538
+ n_cores=args.get("n_cores", 16),
539
+ memory_mb=args.get("memory_mb", 32000),
540
+ walltime=args.get("walltime", "24:00:00"),
541
+ )
542
+ script = SlurmScriptGenerator.generate(job, ClusterProfile())
543
+ return {"engine": eng, "slurm_script": script}
544
+
545
+ def _tool_run_planarity(self, args: Dict[str, Any]) -> Dict[str, Any]:
546
+ if not self.document:
547
+ return {"error": "未找到当前分子"}
548
+ from ...application.calculators.qc_input_generator import export_document_to_xyz
549
+ from ...workflows.planarity_analysis import run_planarity_workflow
550
+ import tempfile, os
551
+ tmp = os.path.join(tempfile.gettempdir(), "molforge_mcp_plane.xyz")
552
+ export_document_to_xyz(self.document, tmp)
553
+ out = run_planarity_workflow(tmp, tempfile.gettempdir())
554
+ summary_path = os.path.join(str(out), "planarity.json")
555
+ with open(summary_path, encoding="utf-8") as fh:
556
+ return json.load(fh)
557
+
558
+ def _tool_run_rest_scf(self, args: Dict[str, Any]) -> Dict[str, Any]:
559
+ if not self.document:
560
+ return {"error": "未找到当前分子"}
561
+ from ...application.calculators.rest_engine import RestEngine
562
+ engine = RestEngine()
563
+ if not engine.probe():
564
+ return {"error": "未检测到本地 WSL2 REST 虚拟环境 (/home/administrator/miniforge3/envs/rest-py311/bin/rest)"}
565
+ xc = args.get("xc", "b3lyp")
566
+ basis = args.get("basis", "def2-SVP")
567
+ res = engine.run_calculation(self.document, xc=xc, basis=basis)
568
+ if not res.get("ok"):
569
+ return {"error": "REST 计算未正常收敛或执行失败", "details": res}
570
+ return res
571
+
572
+ # ---------- JSON-RPC 2.0 协议主分发器 ----------
573
+ def handle_request(self, req: Dict[str, Any]) -> Dict[str, Any]:
574
+ req_id = req.get("id")
575
+ method = req.get("method", "")
576
+ params = req.get("params", {})
577
+
578
+ if method == "initialize":
579
+ return {
580
+ "jsonrpc": "2.0",
581
+ "id": req_id,
582
+ "result": {
583
+ "protocolVersion": MCP_PROTOCOL_VERSION,
584
+ "serverInfo": {"name": "molforge-mcp-server", "version": __version__},
585
+ "capabilities": {
586
+ "tools": {"listChanged": False},
587
+ "resources": {"subscribe": False, "listChanged": False},
588
+ "prompts": {"listChanged": False},
589
+ },
590
+ },
591
+ }
592
+ elif method == "tools/list":
593
+ return {
594
+ "jsonrpc": "2.0",
595
+ "id": req_id,
596
+ "result": {"tools": self.get_tool_definitions()},
597
+ }
598
+ elif method == "tools/call":
599
+ name = params.get("name")
600
+ arguments = params.get("arguments", {})
601
+ if name in self._tools:
602
+ try:
603
+ res = self._tools[name](arguments)
604
+ is_err = bool(res.get("error"))
605
+ return {
606
+ "jsonrpc": "2.0",
607
+ "id": req_id,
608
+ "result": {
609
+ "isError": is_err,
610
+ "content": [
611
+ {"type": "text", "text": json.dumps(res, ensure_ascii=False, indent=2)}
612
+ ],
613
+ },
614
+ }
615
+ except Exception as e:
616
+ return {
617
+ "jsonrpc": "2.0",
618
+ "id": req_id,
619
+ "result": {
620
+ "isError": True,
621
+ "content": [{"type": "text", "text": f"Tool execution failed: {str(e)}"}],
622
+ },
623
+ }
624
+ return {
625
+ "jsonrpc": "2.0",
626
+ "id": req_id,
627
+ "error": {"code": -32601, "message": f"Method/Tool '{name}' not found"},
628
+ }
629
+ elif method == "resources/list":
630
+ return {
631
+ "jsonrpc": "2.0",
632
+ "id": req_id,
633
+ "result": {
634
+ "resources": [
635
+ {
636
+ "uri": "molecule://active/json",
637
+ "name": "Current Active Molecule JSON",
638
+ "mimeType": "application/json",
639
+ },
640
+ {
641
+ "uri": "molecule://active/xyz",
642
+ "name": "Current Active Molecule XYZ",
643
+ "mimeType": "chemical/x-xyz",
644
+ },
645
+ ]
646
+ },
647
+ }
648
+ elif method == "resources/read":
649
+ uri = params.get("uri", "")
650
+ if not self.document:
651
+ return {
652
+ "jsonrpc": "2.0",
653
+ "id": req_id,
654
+ "error": {"code": -32602, "message": "No active molecule loaded"},
655
+ }
656
+ if uri == "molecule://active/json":
657
+ from ...io.mforge_storage import serialize_document_to_dict
658
+ return {
659
+ "jsonrpc": "2.0",
660
+ "id": req_id,
661
+ "result": {
662
+ "contents": [
663
+ {
664
+ "uri": uri,
665
+ "mimeType": "application/json",
666
+ "text": json.dumps(serialize_document_to_dict(self.document), ensure_ascii=False, indent=2),
667
+ }
668
+ ]
669
+ },
670
+ }
671
+ elif uri == "molecule://active/xyz":
672
+ from ...application.calculators.qc_input_generator import extract_xyz_lines
673
+ lines = extract_xyz_lines(self.document)
674
+ xyz_text = f"{self.document.num_atoms}\n{self.document.name}\n" + "\n".join(lines) + "\n"
675
+ return {
676
+ "jsonrpc": "2.0",
677
+ "id": req_id,
678
+ "result": {
679
+ "contents": [
680
+ {
681
+ "uri": uri,
682
+ "mimeType": "chemical/x-xyz",
683
+ "text": xyz_text,
684
+ }
685
+ ]
686
+ },
687
+ }
688
+ return {
689
+ "jsonrpc": "2.0",
690
+ "id": req_id,
691
+ "error": {"code": -32602, "message": f"Resource URI '{uri}' not found"},
692
+ }
693
+ elif method == "prompts/list":
694
+ return {
695
+ "jsonrpc": "2.0",
696
+ "id": req_id,
697
+ "result": {
698
+ "prompts": [
699
+ {
700
+ "name": "dft_optimization_guide",
701
+ "description": "量子化学 DFT 几何构型优化向导提示词",
702
+ },
703
+ {
704
+ "name": "conformer_search_advisor",
705
+ "description": "分子柔性构象搜索与低能构象聚类向导",
706
+ },
707
+ ]
708
+ },
709
+ }
710
+ elif method == "prompts/get":
711
+ pname = params.get("name", "")
712
+ if pname == "dft_optimization_guide":
713
+ return {
714
+ "jsonrpc": "2.0",
715
+ "id": req_id,
716
+ "result": {
717
+ "description": "量子化学 DFT 几何构型优化向导",
718
+ "messages": [
719
+ {
720
+ "role": "user",
721
+ "content": {
722
+ "type": "text",
723
+ "text": "你是一位资深计算化学家。请检查当前分子的 3D 构象合理性,建议合适的 DFT 泛函与基组(如 B3LYP-D3BJ/def2-SVP),并通过 modify_internal_coordinate 或 run_calchem_opt 协助用户完成预优化。",
724
+ },
725
+ }
726
+ ],
727
+ },
728
+ }
729
+ return {
730
+ "jsonrpc": "2.0",
731
+ "id": req_id,
732
+ "error": {"code": -32602, "message": f"Prompt '{pname}' not found"},
733
+ }
734
+
735
+ return {
736
+ "jsonrpc": "2.0",
737
+ "id": req_id,
738
+ "error": {"code": -32601, "message": f"Unsupported MCP method: {method}"},
739
+ }
740
+
741
+ def run_stdio_loop(self) -> None:
742
+ """从标准输入读取 JSON-RPC 消息并写入标准输出。"""
743
+ for line in sys.stdin:
744
+ line = line.strip()
745
+ if not line:
746
+ continue
747
+ try:
748
+ req = json.loads(line)
749
+ resp = self.handle_request(req)
750
+ sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
751
+ sys.stdout.flush()
752
+ except Exception as e:
753
+ err_resp = {
754
+ "jsonrpc": "2.0",
755
+ "id": None,
756
+ "error": {"code": -32700, "message": f"Parse error: {str(e)}"},
757
+ }
758
+ sys.stdout.write(json.dumps(err_resp) + "\n")
759
+ sys.stdout.flush()
760
+
761
+
762
+ if __name__ == "__main__":
763
+ import argparse
764
+ parser = argparse.ArgumentParser(description="MolForge MCP JSON-RPC stdio server")
765
+ parser.add_argument("--desktop", action="store_true", help="转发到已启动的 MolForge 桌面 MCP 服务")
766
+ parser.add_argument("--connection", help="desktop.json 路径;默认使用 MOLFORGE_DATA_DIR/mcp/desktop.json")
767
+ args = parser.parse_args()
768
+ if args.desktop:
769
+ from .desktop_client import run_desktop_stdio_loop
770
+ from ...runtime import data_dir
771
+ run_desktop_stdio_loop(args.connection or (data_dir() / "mcp" / "desktop.json"))
772
+ else:
773
+ from ...io.rdkit_adapter import create_sample_molecule
774
+ from ...application.command_bus import CommandBus
775
+ print("MolForge MCP standalone mode: using a separate sample molecule, not the desktop document.", file=sys.stderr)
776
+ doc = create_sample_molecule("咖啡因")
777
+ bus = CommandBus(doc)
778
+ server = MolForgeMCPServer(doc, bus)
779
+ server.run_stdio_loop()
780
+