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,5 @@
1
+ """MCP server and PyMOL plugin that let agents control any open PyMOL session."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ __version__ = version("pymol-hyperpowers")
@@ -0,0 +1,129 @@
1
+ """The MCP server: its instructions, the tool context, and plugin errors as tool errors."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ from mcp.server.mcpserver import Context, MCPServer
9
+ from mcp.server.mcpserver.exceptions import ToolError
10
+ from mcp_types import CallToolResult, InputRequiredResult
11
+
12
+ from pymol_hyperpowers import __version__
13
+ from pymol_hyperpowers.client import ClientPool, PluginError, SessionClient, SessionGoneError, TransportError
14
+ from pymol_hyperpowers.selection import Selection, SelectionError
15
+ from pymol_hyperpowers.tools import align, escape, geometry, images, io, query, session, view
16
+
17
+ INSTRUCTIONS = """\
18
+ pymol-hyperpowers controls the PyMOL sessions open on this computer. Each session runs the \
19
+ pymol-hyperpowers plugin and is named after a scientist, such as Franklin or Pauling.
20
+
21
+ Choosing a session: with one session open, tools use it. With several open, tools ask you to \
22
+ choose: call list_sessions (newest first, with each session's objects and the other conversations \
23
+ using it) and select one with use_session. A session another conversation is using is not \
24
+ selected automatically: call use_session to share it once the user agrees, or pick another \
25
+ session. Ask the user when it is unclear which PyMOL they mean.
26
+
27
+ Choosing a tool: prefer a dedicated tool, which returns typed data. Use do for anything else in \
28
+ PyMOL's command language, including display, colouring, labels, settings, scenes and movies. Use \
29
+ run, which executes arbitrary Python inside PyMOL, only when neither works.
30
+
31
+ Reading results: do stops at the first line PyMOL rejects and names it. Read the warnings do \
32
+ returns: PyMOL reports a selection that matched nothing as a warning, not an error.
33
+ """
34
+
35
+
36
+ def surface_plugin_error(error: PluginError) -> str:
37
+ """A plugin error as tool-error text: type and message, then PyMOL's output, then the traceback."""
38
+ parts = [f"{error.error_type}: {error.message}"]
39
+ if error.stdout.strip():
40
+ parts.append(f"--- PyMOL output ---\n{error.stdout.rstrip()}")
41
+ if error.traceback_text.strip():
42
+ parts.append(f"--- traceback ---\n{error.traceback_text.rstrip()}")
43
+ return "\n\n".join(parts)
44
+
45
+
46
+ def client_name(context: object) -> str | None:
47
+ """The MCP client's name (``client_info.name``) from a tool call's context, or None.
48
+
49
+ The SDK passes request context to tools only through a Context parameter, which no tool takes,
50
+ so the server reads it here; any missing piece means unknown.
51
+ """
52
+ try:
53
+ name = context.session.client_params.client_info.name # type: ignore[attr-defined]
54
+ except Exception: # noqa: BLE001 - no request context, no client params, or another SDK shape
55
+ return None
56
+ return name if isinstance(name, str) and name else None
57
+
58
+
59
+ class ToolContext:
60
+ """What every tool works through: the session selection and one client per session."""
61
+
62
+ def __init__(self, selection: Selection | None = None, pool: ClientPool | None = None) -> None:
63
+ self.selection = selection if selection is not None else Selection()
64
+ self.pool = pool if pool is not None else ClientPool()
65
+
66
+ def record_client(self, name: str | None) -> None:
67
+ """Record the MCP client's name for this server's claims; the first name stays."""
68
+ self.selection.set_client(name)
69
+
70
+ def run[T](self, action: Callable[[SessionClient], T]) -> T:
71
+ """Run ``action`` against the session this call works with, read once when the call starts.
72
+
73
+ The claim's last activity is refreshed before and after, so a call that hangs shows when it began.
74
+
75
+ :raises ToolError: For every failure, with text the agent can act on.
76
+ """
77
+ try:
78
+ address = self.selection.resolve()
79
+ except SelectionError as e:
80
+ raise ToolError(str(e)) from e
81
+ client = self.pool.get(address)
82
+ self.selection.touch(address)
83
+ try:
84
+ return action(client)
85
+ except SessionGoneError as e:
86
+ self.pool.discard(address.session_id)
87
+ raise ToolError(self.selection.lost(address, str(e))) from e
88
+ except PluginError as e:
89
+ raise ToolError(surface_plugin_error(e)) from e
90
+ except TransportError as e:
91
+ raise ToolError(str(e)) from e
92
+ finally:
93
+ self.selection.touch(address)
94
+
95
+
96
+ class PymolServer(MCPServer[Any]):
97
+ """The MCP server, recording the client's name from each tool call before running the tool."""
98
+
99
+ def __init__(self, ctx: ToolContext, *args: Any, **kwargs: Any) -> None: # noqa: ANN401 - MCPServer's own signature
100
+ super().__init__(*args, **kwargs)
101
+ self._ctx = ctx
102
+
103
+ async def call_tool(
104
+ self, name: str, arguments: dict[str, Any], context: Context[Any, Any] | None = None
105
+ ) -> CallToolResult | InputRequiredResult:
106
+ """Record the client's name, then call the tool as ``MCPServer`` does."""
107
+ self._ctx.record_client(client_name(context))
108
+ return await super().call_tool(name, arguments, context)
109
+
110
+
111
+ def build_server(context: ToolContext | None = None) -> MCPServer[Any]:
112
+ """Register every tool on a new server, not yet running.
113
+
114
+ :param context: Defaults to a new ``ToolContext`` reading the registry this process sees.
115
+ """
116
+ ctx = context if context is not None else ToolContext()
117
+ server: MCPServer[Any] = PymolServer(ctx, "pymol", instructions=INSTRUCTIONS, version=__version__)
118
+ for register in (
119
+ session.register,
120
+ escape.register,
121
+ query.register,
122
+ geometry.register,
123
+ align.register,
124
+ view.register,
125
+ io.register,
126
+ images.register,
127
+ ):
128
+ register(server, ctx)
129
+ return server