pymol-hyperpowers 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,306 @@
1
+ """Command line: serve MCP over stdio (the default), manage the ~/.pymolrc.py block, list sessions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import ast
7
+ import os
8
+ import stat
9
+ import sys
10
+ import tempfile
11
+ from collections.abc import Sequence
12
+ from pathlib import Path
13
+
14
+ from pymol_hyperpowers import __version__, claims, registry
15
+ from pymol_hyperpowers.app import build_server
16
+ from pymol_hyperpowers.selection import NO_SESSIONS, describe
17
+
18
+ # The block points into one installation, so install-plugin rewrites it on every run instead of
19
+ # appending another copy; these markers find it.
20
+ BLOCK_START = "# >>> pymol-hyperpowers >>>"
21
+ BLOCK_END = "# <<< pymol-hyperpowers <<<"
22
+ MODULE_NAME = "pymol_hyperpowers_plugin"
23
+ LOAD_CALL = "_pymol_hp_load"
24
+ NEW_RC_MODE = 0o644
25
+
26
+
27
+ class InstallError(Exception):
28
+ """install-plugin or uninstall-plugin cannot proceed safely; the message says why."""
29
+
30
+
31
+ def default_pymolrc() -> Path:
32
+ """``~/.pymolrc.py``, which PyMOL runs at startup alongside any other ``~/.pymolrc*`` file."""
33
+ return Path.home() / ".pymolrc.py"
34
+
35
+
36
+ def plugin_path() -> Path:
37
+ """The plugin file PyMOL runs, inside this installation."""
38
+ return Path(__file__).with_name("plugin.py").resolve()
39
+
40
+
41
+ def rc_block(plugin: Path) -> str:
42
+ """The rc-file block that loads ``plugin`` when PyMOL starts.
43
+
44
+ PyMOL runs ``~/.pymolrc.py`` inside the ``pymol`` package's namespace, so the block imports the
45
+ plugin as its own module instead of running it there. The module goes into ``sys.modules`` before
46
+ it executes because dataclasses look their module up while being defined. The version check uses
47
+ only old syntax, so an older PyMOL prints why instead of failing to parse the plugin.
48
+ """
49
+ lines = [
50
+ BLOCK_START,
51
+ "# Written by `pymol-hyperpowers install-plugin`, which rewrites this block when re-run.",
52
+ f"def {LOAD_CALL}(path):",
53
+ " import sys",
54
+ " if sys.version_info < (3, 10):",
55
+ " print('pymol-hyperpowers: not loaded; it needs Python 3.10 or newer, and PyMOL runs '",
56
+ " + sys.version.split()[0] + '.')",
57
+ " return",
58
+ " import importlib.util",
59
+ " import traceback",
60
+ " try:",
61
+ f" spec = importlib.util.spec_from_file_location({MODULE_NAME!r}, path)",
62
+ " module = importlib.util.module_from_spec(spec)",
63
+ " sys.modules[spec.name] = module",
64
+ " spec.loader.exec_module(module)",
65
+ " module.main()",
66
+ " except Exception:",
67
+ f" sys.modules.pop({MODULE_NAME!r}, None)",
68
+ " traceback.print_exc()",
69
+ " print('pymol-hyperpowers: the plugin failed to load; the traceback above says why.')",
70
+ # repr: the path becomes a string literal, and a quote or backslash in it must not break the file.
71
+ f"{LOAD_CALL}({str(plugin)!r})",
72
+ f"del {LOAD_CALL}",
73
+ BLOCK_END,
74
+ ]
75
+ return "\n".join(lines) + "\n"
76
+
77
+
78
+ def write_text_atomically(path: Path, text: str) -> None:
79
+ """Replace the contents of ``path`` in one step, so a crash leaves either the old file or the new one.
80
+
81
+ A symlinked rc file (from a dotfiles checkout, say) stays a symlink: the file it points to is
82
+ replaced, and keeps its permission bits.
83
+ """
84
+ target = path.resolve()
85
+ target.parent.mkdir(parents=True, exist_ok=True)
86
+ mode = stat.S_IMODE(target.stat().st_mode) if target.exists() else NEW_RC_MODE
87
+ handle, temp_name = tempfile.mkstemp(dir=target.parent, prefix=f".{target.name}.", suffix=".tmp")
88
+ temp = Path(temp_name)
89
+ try:
90
+ with os.fdopen(handle, "w", encoding="utf-8", newline="") as out:
91
+ out.write(text)
92
+ out.flush()
93
+ os.fsync(out.fileno())
94
+ temp.chmod(mode)
95
+ temp.replace(target)
96
+ except BaseException:
97
+ temp.unlink(missing_ok=True)
98
+ raise
99
+
100
+
101
+ def block_span(text: str) -> tuple[int, int] | None:
102
+ """Where the managed block sits in ``text``: its start-marker line through its end-marker line.
103
+
104
+ A marker counts only as a whole line, so marker text inside a string or a longer comment is
105
+ ordinary content. The span includes the end-marker line's own ending (``\\n`` or ``\\r\\n``).
106
+
107
+ :returns: ``(start, stop)`` offsets, or None when ``text`` has no marker line.
108
+ :raises InstallError: When the marker lines are not exactly one start line followed by one end line.
109
+ """
110
+ starts: list[int] = []
111
+ ends: list[int] = []
112
+ end_lines: list[int] = []
113
+ offset = 0
114
+ for line in text.split("\n"):
115
+ # Offsets are taken before the "\r" is stripped so a CRLF ending stays inside the span.
116
+ stop = offset + len(line) + 1
117
+ content = line.removesuffix("\r")
118
+ if content == BLOCK_START:
119
+ starts.append(offset)
120
+ elif content == BLOCK_END:
121
+ end_lines.append(offset)
122
+ ends.append(min(stop, len(text)))
123
+ offset = stop
124
+ if not starts and not ends:
125
+ return None
126
+ if len(starts) != 1 or len(ends) != 1 or end_lines[0] < starts[0]:
127
+ raise InstallError(
128
+ f"the file needs exactly one {BLOCK_START!r} line followed by one {BLOCK_END!r} line, "
129
+ "and does not have that; fix the file by hand, then re-run."
130
+ )
131
+ return starts[0], ends[0]
132
+
133
+
134
+ def read_rc(rc: Path) -> str:
135
+ """Read ``rc`` without translating line endings, so that rewriting it keeps every byte outside the block.
136
+
137
+ :raises InstallError: When the file is not valid UTF-8; no other encoding is guessed.
138
+ :raises OSError: When the file cannot be read.
139
+ """
140
+ try:
141
+ with rc.open(encoding="utf-8", newline="") as handle:
142
+ return handle.read()
143
+ except UnicodeDecodeError as e:
144
+ raise InstallError(f"{rc} is not valid UTF-8 ({e.reason}); nothing was changed.") from e
145
+
146
+
147
+ def install_plugin(rc: Path, plugin: Path) -> str:
148
+ """Write or rewrite the block in ``rc`` so PyMOL loads ``plugin`` at startup.
149
+
150
+ :returns: What was done, for the terminal.
151
+ :raises InstallError: When the plugin file is missing, or the rc file's block is malformed or it is not UTF-8.
152
+ :raises OSError: When the rc file cannot be read or written.
153
+ """
154
+ if not plugin.is_file():
155
+ raise InstallError(f"no plugin file at {plugin}; the installation is incomplete.")
156
+ existing = read_rc(rc) if rc.exists() else ""
157
+ block = rc_block(plugin)
158
+ span = block_span(existing)
159
+ if span is None:
160
+ if existing and not existing.endswith("\n"):
161
+ existing += "\n"
162
+ text = existing + "\n" + block if existing else block
163
+ verb = "Added"
164
+ else:
165
+ start, stop = span
166
+ text = existing[:start] + block + existing[stop:]
167
+ verb = "Rewrote"
168
+ write_text_atomically(rc, text)
169
+ return (
170
+ f"{verb} the pymol-hyperpowers block in {rc}. At startup PyMOL loads:\n"
171
+ f" {plugin}\n"
172
+ "Restart PyMOL; its console then names the session, for example:\n"
173
+ ' pymol-hyperpowers: this session is "Franklin" (127.0.0.1:50123)\n'
174
+ "Re-run this command if that path changes, for example after moving the checkout."
175
+ )
176
+
177
+
178
+ def recorded_plugin(block: str) -> Path | None:
179
+ """The plugin path a block written by :func:`rc_block` loads, or None when the block names none."""
180
+ for line in block.splitlines():
181
+ if line.startswith(f"{LOAD_CALL}(") and line.endswith(")"):
182
+ try:
183
+ value = ast.literal_eval(line[len(LOAD_CALL) + 1 : -1])
184
+ except (ValueError, SyntaxError):
185
+ return None
186
+ return Path(value) if isinstance(value, str) else None
187
+ return None
188
+
189
+
190
+ def repair_plugin_block(rc: Path, plugin: Path) -> str | None:
191
+ """Point the block in ``rc`` at ``plugin`` when the plugin file it loads no longer exists.
192
+
193
+ The block names a file inside one installation, and that path includes the Python minor
194
+ version, so reinstalling the tool on another Python leaves PyMOL loading a file that is gone.
195
+ A block whose file still exists is left alone: it may name a checkout on purpose.
196
+
197
+ :returns: What was done, for the server's stderr, or None when nothing changed.
198
+ :raises InstallError: When the rc file's block is malformed or it is not UTF-8.
199
+ :raises OSError: When the rc file cannot be read or written.
200
+ """
201
+ if not rc.exists():
202
+ return None
203
+ existing = read_rc(rc)
204
+ span = block_span(existing)
205
+ if span is None:
206
+ return None
207
+ start, stop = span
208
+ recorded = recorded_plugin(existing[start:stop])
209
+ if recorded is None or recorded.exists():
210
+ return None
211
+ write_text_atomically(rc, existing[:start] + rc_block(plugin) + existing[stop:])
212
+ return (
213
+ f"pymol-hyperpowers: the plugin file {rc} loaded is gone ({recorded}); "
214
+ f"it now loads {plugin}. Restart PyMOL to load it."
215
+ )
216
+
217
+
218
+ def repair_default_block() -> None:
219
+ """Repair the default rc file's block at server startup, reporting on stderr and never failing."""
220
+ try:
221
+ message = repair_plugin_block(default_pymolrc(), plugin_path())
222
+ except (InstallError, OSError) as e:
223
+ message = f"pymol-hyperpowers: could not check the plugin block in {default_pymolrc()}: {e}"
224
+ if message:
225
+ print(message, file=sys.stderr)
226
+
227
+
228
+ def uninstall_plugin(rc: Path) -> str:
229
+ """Remove the block from ``rc``, and the blank line install-plugin put before it.
230
+
231
+ :returns: What was done, for the terminal.
232
+ :raises InstallError: When the rc file's block is malformed or it is not UTF-8.
233
+ :raises OSError: When the rc file cannot be read or written.
234
+ """
235
+ if not rc.exists():
236
+ return f"Nothing to remove: {rc} does not exist."
237
+ existing = read_rc(rc)
238
+ span = block_span(existing)
239
+ if span is None:
240
+ return f"Nothing to remove: {rc} has no pymol-hyperpowers block."
241
+ start, stop = span
242
+ before = existing[:start]
243
+ if before.endswith("\n\n"):
244
+ before = before[:-1]
245
+ write_text_atomically(rc, before + existing[stop:])
246
+ return f"Removed the pymol-hyperpowers block from {rc}; the rest of the file is unchanged."
247
+
248
+
249
+ def print_sessions() -> int:
250
+ """Print the live sessions, newest first, one per line, with who uses each and their PIDs."""
251
+ sessions = registry.list_sessions()
252
+ if not sessions:
253
+ print(NO_SESSIONS)
254
+ usage = claims.read_users(claims.SERVER_ID)
255
+ for session in sessions:
256
+ users = [] if usage is None else usage.get(session.session_id, [])
257
+ print(describe(session, users, pid=True))
258
+ if usage is None and sessions:
259
+ # None means unknown, not free: the lines above cannot claim a session is unused.
260
+ print("Could not read which conversations use these sessions.")
261
+ return 0
262
+
263
+
264
+ def build_parser() -> argparse.ArgumentParser:
265
+ """The argument parser; no command means ``serve``."""
266
+ parser = argparse.ArgumentParser(
267
+ prog="pymol-hyperpowers",
268
+ description="MCP server for PyMOL. With no command it serves MCP over stdio, the way MCP clients start it.",
269
+ )
270
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
271
+ commands = parser.add_subparsers(dest="command", metavar="command")
272
+ commands.add_parser("serve", help="serve MCP over stdio (the default)")
273
+ rc_help = "the rc file to edit (default: ~/.pymolrc.py)"
274
+ install = commands.add_parser("install-plugin", help="load the plugin from ~/.pymolrc.py when PyMOL starts")
275
+ install.add_argument("--pymolrc", type=Path, help=rc_help)
276
+ uninstall = commands.add_parser("uninstall-plugin", help="remove the block install-plugin wrote")
277
+ uninstall.add_argument("--pymolrc", type=Path, help=rc_help)
278
+ commands.add_parser("plugin-path", help="print the path of the plugin file PyMOL runs")
279
+ commands.add_parser("sessions", help="list the PyMOL sessions running the plugin, newest first")
280
+ return parser
281
+
282
+
283
+ def main(argv: Sequence[str] | None = None) -> int:
284
+ """Run one command.
285
+
286
+ :returns: The process exit status.
287
+ """
288
+ args = build_parser().parse_args(argv)
289
+ command = args.command or "serve"
290
+ if command == "serve":
291
+ repair_default_block()
292
+ build_server().run()
293
+ return 0
294
+ if command == "plugin-path":
295
+ print(plugin_path())
296
+ return 0
297
+ if command == "sessions":
298
+ return print_sessions()
299
+ rc = (args.pymolrc or default_pymolrc()).expanduser()
300
+ try:
301
+ message = install_plugin(rc, plugin_path()) if command == "install-plugin" else uninstall_plugin(rc)
302
+ except (InstallError, OSError) as e:
303
+ print(f"pymol-hyperpowers: {e}", file=sys.stderr)
304
+ return 1
305
+ print(message)
306
+ return 0