qodalis-cli-server-plugin-docker 1.0.0b39__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,246 @@
1
+ """The exec WebSocket (``/ws/v1/qcli/docker/exec?host=&container=&cmd=&user=&cols=&rows=&ticket=``, also
2
+ ``/ws/qcli/docker/exec``): an interactive session with a TTY. The messages are those of ``/ws/v1/qcli/shell``: the client
3
+ sends ``{"type": "stdin", "data"}`` and ``{"type": "resize", "cols", "rows"}``; the server ``{"type": "ready", "shell", "os"}``,
4
+ ``{"type": "stdout", "data"}``, ``{"type": "exit", "code"}`` and ``{"type": "error", "message"}``.
5
+
6
+ A browser cannot read the status of a refused upgrade, so once the caller is signed in (the server closes the socket with
7
+ 4401 otherwise, as for the shell socket) and has ``docker:exec`` (4403 ``forbidden``) every refusal (an unknown host or
8
+ container, a hidden or protected container, read-only mode, a container that is not running, an unreachable engine) is one
9
+ ``{"type": "error", "message"}`` with the REST error's text, then a normal close (1000). Closing the socket ends the session."""
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import codecs
15
+ import json
16
+ from typing import Any, Callable, Optional
17
+
18
+ from starlette.websockets import WebSocket, WebSocketDisconnect
19
+
20
+ from qodalis_cli_server_abstractions import split_shell_words
21
+
22
+ from .controller import DOCKER_EXEC, caller_from_auth, scope_auth
23
+ from .service import DockerService
24
+
25
+ EXEC_SOCKET_PATH = "/ws/v1/qcli/docker/exec"
26
+ EXEC_SOCKET_PATH_UNVERSIONED = "/ws/qcli/docker/exec"
27
+
28
+
29
+ UNSUPERVISED_TEXT = "the exec session cannot be supervised on this server (update the users plugin)"
30
+ #: Frames of the client waiting to be written to the exec: more make the reader stop taking frames.
31
+ INBOX_FRAMES = 256
32
+
33
+
34
+ async def _watch_access(websocket: WebSocket, users: Any, auth: Any, interval: Optional[float], on_end: Callable[[], None]) -> None:
35
+ """Closes the socket (4401) when the session ended or its user lost ``docker:exec``; checks on every change of
36
+ sessions, users and groups and every ``interval`` seconds."""
37
+ seconds = interval if interval is not None else getattr(users, "external_socket_check_interval", 30.0)
38
+ seconds = min(max(float(seconds), 0.01), 60.0)
39
+ loop = asyncio.get_running_loop()
40
+ changed = asyncio.Event()
41
+
42
+ def listener() -> None:
43
+ try:
44
+ loop.call_soon_threadsafe(changed.set)
45
+ except RuntimeError:
46
+ pass # loop closed
47
+
48
+ add, remove = getattr(users, "add_change_listener", None), getattr(users, "remove_change_listener", None)
49
+ if callable(add):
50
+ add(listener)
51
+ try:
52
+ while True:
53
+ try:
54
+ await asyncio.wait_for(changed.wait(), seconds)
55
+ except (asyncio.TimeoutError, TimeoutError):
56
+ pass
57
+ changed.clear()
58
+ try:
59
+ state = await users.socket_access_state(auth, DOCKER_EXEC)
60
+ except Exception: # noqa: BLE001 - a failing check ends the session like the shell socket's
61
+ state = False
62
+ if state is True:
63
+ continue
64
+ on_end() # the whole session ends: the exec stream, the pumps and the socket
65
+ try:
66
+ await websocket.close(code=4401, reason=state if isinstance(state, str) else SESSION_ENDED)
67
+ except Exception: # noqa: BLE001 - already gone
68
+ pass
69
+ return
70
+ finally:
71
+ if callable(remove):
72
+ remove(listener)
73
+
74
+
75
+ def _dimension(value: Any, fallback: int) -> int:
76
+ try:
77
+ n = float(value)
78
+ except (TypeError, ValueError):
79
+ return fallback
80
+ return int(n) if n.is_integer() and 1 <= n <= 1000 else fallback
81
+
82
+
83
+ PERMISSION_REMOVED = "permission removed"
84
+ SESSION_ENDED = "session ended"
85
+
86
+
87
+ def create_exec_handler(
88
+ service: DockerService, access: Optional[Callable[[], Any]] = None, check_interval: Optional[float] = None,
89
+ ) -> Any:
90
+ """The handler of the exec WebSocket (``await handler(websocket)``).
91
+
92
+ ``access()`` returns the auth plugin of a protected server (``socket_access_state``/``add_change_listener``), if any:
93
+ an open session ends with close 4401 ``permission removed`` when its user loses ``docker:exec`` and 4401
94
+ ``session ended`` when the session ends (logout, revoke, expiry, user disabled or deleted), re-checked on every change
95
+ and every ``check_interval`` seconds (default 30, at most 60), like the server's shell socket."""
96
+
97
+ async def handler(websocket: WebSocket) -> None:
98
+ await websocket.accept()
99
+ auth = scope_auth(websocket)
100
+ if auth is not None:
101
+ can = getattr(auth, "can", None)
102
+ if callable(can) and not can(DOCKER_EXEC):
103
+ await websocket.close(code=4403, reason="forbidden")
104
+ return
105
+
106
+ monitor: Optional["asyncio.Future[None]"] = None
107
+ users = access() if (access is not None and auth is not None) else None
108
+ # a signed-in session that cannot be supervised would outlive its sign-out: refused (fail closed)
109
+ unsupervised = auth is not None and not (users is not None and callable(getattr(users, "socket_access_state", None)))
110
+ state: dict[str, Any] = {"closed": False, "upgrade": None}
111
+ # the reader's queue is bounded: while the container does not read, no more frames are taken
112
+ inbox: "asyncio.Queue[Optional[dict[str, Any]]]" = asyncio.Queue(maxsize=INBOX_FRAMES)
113
+
114
+ def end_session() -> None:
115
+ """Ends everything of the session: no more frames, the pumps wake, the exec stream closes."""
116
+ state["closed"] = True
117
+ try:
118
+ inbox.put_nowait(None)
119
+ except asyncio.QueueFull:
120
+ pass
121
+ if state["upgrade"] is not None:
122
+ state["upgrade"].close()
123
+
124
+ if not unsupervised and users is not None:
125
+ monitor = asyncio.ensure_future(_watch_access(websocket, users, auth, check_interval, end_session))
126
+
127
+ async def send(message: dict[str, Any]) -> None:
128
+ try:
129
+ await websocket.send_text(json.dumps(message, ensure_ascii=False))
130
+ except Exception: # noqa: BLE001 - the client is gone
131
+ pass
132
+
133
+ async def refuse(text: str) -> None:
134
+ await send({"type": "error", "message": text})
135
+ try:
136
+ await websocket.close(code=1000, reason="error")
137
+ except Exception: # noqa: BLE001
138
+ pass
139
+
140
+ # The reader comes first: a client that leaves while the session starts must not leave the exec attached
141
+
142
+ async def read_client() -> None:
143
+ while True:
144
+ try:
145
+ raw = await websocket.receive_text()
146
+ except (WebSocketDisconnect, RuntimeError):
147
+ end_session()
148
+ return
149
+ try:
150
+ message = json.loads(raw)
151
+ except ValueError:
152
+ continue
153
+ if isinstance(message, dict):
154
+ await inbox.put(message)
155
+
156
+ reader = asyncio.ensure_future(read_client())
157
+ upgrade: Optional[Any] = None
158
+ try:
159
+ caller = caller_from_auth(auth)
160
+ try:
161
+ service.assert_same_site(caller, websocket.headers.get("origin"), websocket.headers.get("host"))
162
+ except Exception as err: # noqa: BLE001 - a foreign page cannot drive the plugin
163
+ await websocket.close(code=4403, reason=getattr(err, "message", None) or service.CROSS_SITE_TEXT)
164
+ return
165
+ try:
166
+ service.assert_caller(caller)
167
+ except Exception: # noqa: BLE001 - the sign-in rule
168
+ await websocket.close(code=4401, reason="login required")
169
+ return
170
+ if unsupervised:
171
+ return await refuse(UNSUPERVISED_TEXT)
172
+ params = websocket.query_params
173
+ container = params.get("container")
174
+ if not container:
175
+ return await refuse("container is required")
176
+ try:
177
+ cmd = params.get("cmd")
178
+ session = await service.prepare_exec_session(
179
+ params.get("host") or None, container, command=split_shell_words(cmd) if cmd else None, user=params.get("user") or None, caller=caller,
180
+ )
181
+ except Exception as err: # noqa: BLE001 - every refusal is the REST error's text
182
+ return await refuse(getattr(err, "message", None) or str(err))
183
+ if state["closed"]:
184
+ return
185
+ try:
186
+ started, resize, exit_code = await service.start_exec_session(
187
+ session, cols=_dimension(params.get("cols"), 80), rows=_dimension(params.get("rows"), 24), caller=caller,
188
+ )
189
+ except Exception as err: # noqa: BLE001
190
+ return await refuse(getattr(err, "message", None) or str(err))
191
+ upgrade = started
192
+ state["upgrade"] = started
193
+ if state["closed"]:
194
+ return
195
+
196
+ await send({"type": "ready", "shell": session["command"][0] if params.get("cmd") else "sh", "os": "linux"})
197
+ decoder = codecs.getincrementaldecoder("utf-8")("replace")
198
+
199
+ async def pump_engine() -> None:
200
+ while True:
201
+ data = await started.read()
202
+ if not data:
203
+ return
204
+ text = decoder.decode(data)
205
+ if text:
206
+ await send({"type": "stdout", "data": text})
207
+
208
+ async def pump_client() -> None:
209
+ while True:
210
+ if state["closed"] and inbox.empty():
211
+ return
212
+ message = await inbox.get()
213
+ if message is None or state["closed"]:
214
+ return
215
+ if message.get("type") == "stdin" and isinstance(message.get("data"), str):
216
+ started.write(message["data"].encode("utf-8"))
217
+ await started.drain()
218
+ elif message.get("type") == "resize":
219
+ await resize(_dimension(message.get("cols"), 80), _dimension(message.get("rows"), 24))
220
+
221
+ engine_task = asyncio.ensure_future(pump_engine())
222
+ client_task = asyncio.ensure_future(pump_client())
223
+ try:
224
+ await asyncio.wait({engine_task, client_task}, return_when=asyncio.FIRST_COMPLETED)
225
+ finally:
226
+ for task in (engine_task, client_task):
227
+ if not task.done():
228
+ task.cancel()
229
+ started.close()
230
+ await asyncio.gather(engine_task, client_task, return_exceptions=True)
231
+ if not state["closed"]:
232
+ # The exit message carries the exec's real exit code (read once the engine reports it finished)
233
+ await send({"type": "exit", "code": await exit_code()})
234
+ try:
235
+ await websocket.close(code=1000, reason="exit")
236
+ except Exception: # noqa: BLE001
237
+ pass
238
+ finally:
239
+ if upgrade is not None:
240
+ upgrade.close()
241
+ reader.cancel()
242
+ if monitor is not None:
243
+ monitor.cancel()
244
+ await asyncio.gather(reader, *([monitor] if monitor is not None else []), return_exceptions=True)
245
+
246
+ return handler
@@ -0,0 +1,149 @@
1
+ """MCP tools of the Docker plugin (``docker_*``), registered on the server's MCP tool registry when the plugin is mounted:
2
+ ``docker_list_containers``, ``docker_inspect_container``, ``docker_logs``, ``docker_stats``, ``docker_list_images``,
3
+ ``docker_list_stacks``, ``docker_system_info`` (``docker:read``), ``docker_start``, ``docker_stop``, ``docker_restart``
4
+ (``docker:manage``) and ``docker_exec`` (``docker:exec``). No remove or prune tools. Imported lazily (needs ``qodalis_cli``)."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ from typing import Any, Awaitable, Callable, Optional
10
+
11
+ from qodalis_cli.mcp import McpCallContext, McpTool, McpToolResult, object_schema
12
+
13
+ from .controller import DOCKER_EXEC, DOCKER_MANAGE, DOCKER_READ, caller_from_auth
14
+ from .service import DockerService
15
+
16
+ READ_ONLY = {"readOnlyHint": True}
17
+ DESTRUCTIVE = {"destructiveHint": True}
18
+ _HOST = {"host": {"type": "string", "description": "The Docker host (default: local)"}}
19
+ _CONTAINER = {"container": {"type": "string", "description": "A container name, id or id prefix"}}
20
+
21
+ Handler = Callable[[dict[str, Any], McpCallContext], Awaitable[McpToolResult]]
22
+
23
+
24
+ def _json(value: dict[str, Any], text: Optional[str] = None) -> McpToolResult:
25
+ return McpToolResult(text=text if text is not None else json.dumps(value, indent=2, ensure_ascii=False), structured=value, is_error=False)
26
+
27
+
28
+ def _optional(value: Any) -> Optional[str]:
29
+ return value if isinstance(value, str) and value else None
30
+
31
+
32
+ def _guarded(fn: Handler, service: DockerService) -> Handler:
33
+ async def call(args: dict[str, Any], context: McpCallContext) -> McpToolResult:
34
+ try:
35
+ service.assert_caller(caller_from_auth(context.auth))
36
+ return await fn(args, context)
37
+ except Exception as exc: # noqa: BLE001 - the tool's error
38
+ return McpToolResult.error(getattr(exc, "message", None) or str(exc))
39
+
40
+ return call
41
+
42
+
43
+ class DockerMcpToolProvider:
44
+ """The ``docker_*`` tools (the REST shapes as JSON)."""
45
+
46
+ name = "docker"
47
+
48
+ def __init__(self, service: DockerService) -> None:
49
+ self.service = service
50
+
51
+ def get_tools(self, context: McpCallContext) -> list[McpTool]:
52
+ s = self.service
53
+
54
+ def lifecycle(action: str, text: str) -> McpTool:
55
+ async def run(args: dict[str, Any], ctx: McpCallContext) -> McpToolResult:
56
+ result = await s.container_action(_optional(args.get("host")), str(args.get("container")), action, caller_from_auth(ctx.auth))
57
+ return _json(dict(result), f"{action}: {result['container']['name']} is {result['container']['state']}")
58
+
59
+ return McpTool(f"docker_{action}", text, object_schema({**_CONTAINER, **_HOST}, ["container"]), _guarded(run, s), [DOCKER_MANAGE])
60
+
61
+ async def list_containers(args: dict[str, Any], _: McpCallContext) -> McpToolResult:
62
+ return _json(dict(await s.list_containers(_optional(args.get("host")), all=args.get("all") is not False, stack=_optional(args.get("stack")))))
63
+
64
+ async def inspect(args: dict[str, Any], _: McpCallContext) -> McpToolResult:
65
+ return _json(dict(await s.get_container(_optional(args.get("host")), str(args.get("container")))))
66
+
67
+ async def logs(args: dict[str, Any], _: McpCallContext) -> McpToolResult:
68
+ tail = args.get("tail")
69
+ result = await s.logs(_optional(args.get("host")), str(args.get("container")), tail=tail if isinstance(tail, int) and not isinstance(tail, bool) else None,
70
+ since=_optional(args.get("since")), timestamps=True)
71
+ text = "\n".join(
72
+ f"{line.get('time', '')} {'[stderr] ' if line['stream'] == 'stderr' else ''}{line['text']}".strip() for line in result["lines"]
73
+ ) or "No log lines"
74
+ return _json(dict(result), text)
75
+
76
+ async def stats(args: dict[str, Any], _: McpCallContext) -> McpToolResult:
77
+ containers = args.get("containers")
78
+ return _json(dict(await s.stats(_optional(args.get("host")), [str(c) for c in containers] if isinstance(containers, list) else None)))
79
+
80
+ async def images(args: dict[str, Any], _: McpCallContext) -> McpToolResult:
81
+ return _json(dict(await s.images(_optional(args.get("host")))))
82
+
83
+ async def stacks(args: dict[str, Any], _: McpCallContext) -> McpToolResult:
84
+ return _json(dict(await s.stacks(_optional(args.get("host")))))
85
+
86
+ async def system_info(args: dict[str, Any], _: McpCallContext) -> McpToolResult:
87
+ return _json(dict(await s.info(_optional(args.get("host")))))
88
+
89
+ async def run_exec(args: dict[str, Any], ctx: McpCallContext) -> McpToolResult:
90
+ timeout = args.get("timeoutSeconds")
91
+ result = await s.exec(
92
+ _optional(args.get("host")), str(args.get("container")),
93
+ {"command": args.get("command"), "user": _optional(args.get("user")), "workdir": _optional(args.get("workdir")),
94
+ "timeoutSeconds": timeout if isinstance(timeout, (int, float)) and not isinstance(timeout, bool) else None},
95
+ caller_from_auth(ctx.auth),
96
+ )
97
+ text = f"exit code {result['exitCode']}\n{result['stdout']}" + (f"\n[stderr]\n{result['stderr']}" if result["stderr"] else "")
98
+ return McpToolResult(text=text, structured=dict(result), is_error=result["exitCode"] != 0)
99
+
100
+ return [
101
+ McpTool(
102
+ "docker_list_containers", "The containers of a Docker host (all by default, or only the running ones), optionally of one compose stack",
103
+ object_schema({"all": {"type": "boolean", "description": "Include stopped containers (default true)", "default": True},
104
+ "stack": {"type": "string", "description": "Only this compose stack"}, **_HOST}),
105
+ _guarded(list_containers, s), [DOCKER_READ], dict(READ_ONLY),
106
+ ),
107
+ McpTool(
108
+ "docker_inspect_container", "A container in detail: command, environment (secret-looking values masked), mounts, networks, restart policy, exit code",
109
+ object_schema({**_CONTAINER, **_HOST}, ["container"]), _guarded(inspect, s), [DOCKER_READ], dict(READ_ONLY),
110
+ ),
111
+ McpTool(
112
+ "docker_logs", "The last lines of a container's log, oldest first",
113
+ object_schema({**_CONTAINER, "tail": {"type": "integer", "description": "How many lines (1-2000, default 100)", "default": 100},
114
+ "since": {"type": "string", "description": "Only lines after this ISO 8601 time"}, **_HOST}, ["container"]),
115
+ _guarded(logs, s), [DOCKER_READ], dict(READ_ONLY),
116
+ ),
117
+ McpTool(
118
+ "docker_stats", "CPU, memory, network and block I/O of the running containers (or of the given ones)",
119
+ object_schema({"containers": {"type": "array", "items": {"type": "string"}, "description": "Container names or ids (default: every running container)"}, **_HOST}),
120
+ _guarded(stats, s), [DOCKER_READ], dict(READ_ONLY),
121
+ ),
122
+ McpTool(
123
+ "docker_list_images", "The images of a Docker host: tags, size, containers using them, dangling or not",
124
+ object_schema({**_HOST}), _guarded(images, s), [DOCKER_READ], dict(READ_ONLY),
125
+ ),
126
+ McpTool(
127
+ "docker_list_stacks", "The compose stacks of a Docker host (grouped by the compose project label) with their state",
128
+ object_schema({**_HOST}), _guarded(stacks, s), [DOCKER_READ], dict(READ_ONLY),
129
+ ),
130
+ McpTool(
131
+ "docker_system_info", "The Docker engine: version, OS, CPUs, memory, storage driver and the container and image counts",
132
+ object_schema({**_HOST}), _guarded(system_info, s), [DOCKER_READ], dict(READ_ONLY),
133
+ ),
134
+ lifecycle("start", "Start a container (nothing happens when it is running)"),
135
+ lifecycle("stop", "Stop a container (nothing happens when it is stopped)"),
136
+ lifecycle("restart", "Restart a container"),
137
+ McpTool(
138
+ "docker_exec", "Run a command inside a running container and return its output and exit code (not interactive; each stream is capped at 1 MB)",
139
+ object_schema({
140
+ **_CONTAINER,
141
+ "command": {"type": "array", "items": {"type": "string"}, "description": 'The command and its arguments, e.g. ["ls", "-la", "/app"]'},
142
+ "user": {"type": "string", "description": "Run as this user"},
143
+ "workdir": {"type": "string", "description": "Working directory"},
144
+ "timeoutSeconds": {"type": "integer", "description": "Give up after this many seconds (1-300, default 30)", "default": 30},
145
+ **_HOST,
146
+ }, ["container", "command"]),
147
+ _guarded(run_exec, s), [DOCKER_EXEC], dict(DESTRUCTIVE),
148
+ ),
149
+ ]
@@ -0,0 +1,36 @@
1
+ """The Docker plugin's entry point (``qodalis_cli.plugins``, ``builder.add_plugin``): containers, images, compose stacks,
2
+ volumes and networks of Docker hosts (the Engine API), in the Console's Docker page, the terminal (``docker``), over MCP and
3
+ at ``/api/v1/qcli/docker``, with an interactive exec WebSocket. The settings (config provider ``docker``) are read on every
4
+ call; without an ``endpoint`` the plugin is ``needs-configuration``: the socket is root-equivalent, so the host says which
5
+ one to use."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from qodalis_cli_server_abstractions import CliPluginEntryInfo
12
+
13
+ from .builder import CliDockerBuilder
14
+ from .settings import docker_settings, read_docker_settings
15
+
16
+ #: The plugin, for ``builder.add_plugin`` (the marketplace's record says it for an installed copy).
17
+ plugin = CliPluginEntryInfo(id="docker", package="qodalis-cli-server-plugin-docker", title="Docker", icon="🐳")
18
+
19
+
20
+ def settings() -> list[Any]:
21
+ """Its settings (code options of the same keys are their defaults)."""
22
+ return docker_settings()
23
+
24
+
25
+ async def create_plugin(context: Any) -> Any:
26
+ provider = await context.settings(title="Docker", description="The Docker hosts the plugin manages", settings=settings())
27
+
28
+ def current() -> Any:
29
+ return read_docker_settings(lambda key: provider.value("settings", key))
30
+
31
+ if not current().endpoint:
32
+ return context.needs_configuration(provider.missing_required())
33
+ builder = CliDockerBuilder().set_settings(current).set_audit(context.audit).set_logger(context.logger)
34
+ if getattr(context, "event_bus", None) is not None:
35
+ builder.set_event_bus(context.event_bus)
36
+ return builder.build()