docker-tiny-mcp 0.1.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.
Files changed (45) hide show
  1. docker_tiny_mcp/__init__.py +1 -0
  2. docker_tiny_mcp/__main__.py +280 -0
  3. docker_tiny_mcp/consent.py +252 -0
  4. docker_tiny_mcp/daemon.py +71 -0
  5. docker_tiny_mcp/errors.py +89 -0
  6. docker_tiny_mcp/events.py +51 -0
  7. docker_tiny_mcp/models.py +444 -0
  8. docker_tiny_mcp/prompts.py +58 -0
  9. docker_tiny_mcp/resources/__init__.py +15 -0
  10. docker_tiny_mcp/resources/containers.py +13 -0
  11. docker_tiny_mcp/resources/images.py +13 -0
  12. docker_tiny_mcp/resources/info.py +13 -0
  13. docker_tiny_mcp/resources/templates/__init__.py +11 -0
  14. docker_tiny_mcp/resources/templates/container.py +13 -0
  15. docker_tiny_mcp/resources/templates/logs.py +14 -0
  16. docker_tiny_mcp/safety.py +156 -0
  17. docker_tiny_mcp/server.py +115 -0
  18. docker_tiny_mcp/tools/__init__.py +57 -0
  19. docker_tiny_mcp/tools/container.py +104 -0
  20. docker_tiny_mcp/tools/containers.py +44 -0
  21. docker_tiny_mcp/tools/create.py +210 -0
  22. docker_tiny_mcp/tools/events.py +65 -0
  23. docker_tiny_mcp/tools/exec.py +99 -0
  24. docker_tiny_mcp/tools/images.py +71 -0
  25. docker_tiny_mcp/tools/info.py +51 -0
  26. docker_tiny_mcp/tools/logs.py +101 -0
  27. docker_tiny_mcp/tools/networks.py +59 -0
  28. docker_tiny_mcp/tools/prune.py +60 -0
  29. docker_tiny_mcp/tools/pull.py +36 -0
  30. docker_tiny_mcp/tools/read.py +69 -0
  31. docker_tiny_mcp/tools/remove.py +36 -0
  32. docker_tiny_mcp/tools/remove_image.py +37 -0
  33. docker_tiny_mcp/tools/restart.py +31 -0
  34. docker_tiny_mcp/tools/results.py +50 -0
  35. docker_tiny_mcp/tools/start.py +36 -0
  36. docker_tiny_mcp/tools/stats.py +124 -0
  37. docker_tiny_mcp/tools/stop.py +28 -0
  38. docker_tiny_mcp/tools/volumes.py +56 -0
  39. docker_tiny_mcp/tools/wait.py +57 -0
  40. docker_tiny_mcp/tools/write.py +76 -0
  41. docker_tiny_mcp-0.1.0.dist-info/METADATA +424 -0
  42. docker_tiny_mcp-0.1.0.dist-info/RECORD +45 -0
  43. docker_tiny_mcp-0.1.0.dist-info/WHEEL +4 -0
  44. docker_tiny_mcp-0.1.0.dist-info/entry_points.txt +3 -0
  45. docker_tiny_mcp-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1 @@
1
+ """An MCP server for Docker."""
@@ -0,0 +1,280 @@
1
+ """HTTP and stdio entry points.
2
+
3
+ Settings precedence: the command line, the DOCKER_TINY_MCP_* environment, then
4
+ the config file.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import logging
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import cast
14
+
15
+ import argclass
16
+ from aiodocker import Docker
17
+ from aiohttp import web
18
+ from aiohttp_tiny_mcp import Endpoint, Principal, Registry, run_stdio
19
+ from aiohttp_tiny_mcp.auth import Authorization, TokenVerifier
20
+ from aiohttp_tiny_mcp.auth.jwt import HMACJWTVerifier
21
+ from aiohttp_tiny_mcp.console import Console
22
+ from aiohttp_tiny_mcp.storage.sqlite import SqliteHub, SqliteSessionStore, SqliteStorage
23
+
24
+ from .consent import LEVELS, Policy
25
+ from .events import watch
26
+ from .server import build
27
+
28
+ log = logging.getLogger("docker_tiny_mcp")
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class QueryToken(Authorization):
33
+ """Bearer authentication that also reads the `token` query argument.
34
+
35
+ A client that cannot send a header sends the token in the URL instead. The
36
+ URL is then a credential: it reaches browser history, the client's saved
37
+ settings and every log that keeps the query. The header wins where both
38
+ are present.
39
+ """
40
+
41
+ query: bool = False
42
+
43
+ async def authenticate(self, request: web.Request) -> Principal:
44
+ if self.query and "Authorization" not in request.headers:
45
+ supplied = request.query.get("token", "")
46
+ if supplied:
47
+ return await self.principal(f"Bearer {supplied}")
48
+ return await super().authenticate(request)
49
+
50
+
51
+ class JWT(argclass.Group):
52
+ """HS256 JWT authentication with a pre-shared key."""
53
+
54
+ psk: str = argclass.Secret(
55
+ default="",
56
+ help=(
57
+ "Pre-shared key, at least 32 bytes. Prefer the config file or the "
58
+ "environment variable: another user on this machine can read a command line."
59
+ ),
60
+ )
61
+ audience: str = argclass.Argument(
62
+ default="",
63
+ help=(
64
+ "Public URL of this endpoint. A token must name it in 'aud', and it is "
65
+ "published as the protected resource. Required with a pre-shared key."
66
+ ),
67
+ )
68
+ issuer: str = argclass.Argument(
69
+ default="",
70
+ help="Required 'iss' claim. Empty accepts a token from any issuer.",
71
+ )
72
+ query_token: bool = argclass.Argument(
73
+ default=False,
74
+ action=argclass.Actions.STORE_TRUE,
75
+ help=(
76
+ "Also accept the token as the 'token' query argument, for a client "
77
+ "that sends no header. The access log masks that argument; the URL "
78
+ "still reaches browser history and client settings."
79
+ ),
80
+ )
81
+
82
+
83
+ class Parser(argclass.Parser):
84
+ """docker-tiny-mcp -- an MCP server for Docker."""
85
+
86
+ state: Path = argclass.Argument(
87
+ default=Path("docker-tiny-mcp.sqlite3"),
88
+ help="SQLite file holding sessions and events. Several workers may share one.",
89
+ )
90
+ docker_url: str = argclass.Argument(
91
+ default="",
92
+ help="Where the daemon is. Empty means the usual socket for this machine.",
93
+ )
94
+ unprivileged: bool = argclass.Argument(
95
+ default=False,
96
+ help="Forbid host mounts and privileged container access; allow named local volumes.",
97
+ )
98
+ network: str = argclass.Argument(
99
+ default="",
100
+ help="Fix the container network and disable network management tools.",
101
+ )
102
+ stdio: bool = argclass.Argument(
103
+ default=False,
104
+ help="Talk over standard input and output instead of listening on a port.",
105
+ )
106
+ jwt = JWT(
107
+ title="JWT authentication",
108
+ description="Verify an HS256 JWT on every HTTP request. Without a key, nothing is asked.",
109
+ )
110
+ host: str = argclass.Argument(default="127.0.0.1", help="Address to listen on.")
111
+ port: int = argclass.Argument(default=8080, help="Port to listen on.")
112
+ path: str = argclass.Argument(default="/mcp", help="Path to mount the endpoint at.")
113
+ console: str = argclass.Argument(
114
+ default="/console",
115
+ help="Path to mount the web console at. Empty turns it off.",
116
+ )
117
+ allowed_origin: frozenset[str] = argclass.Argument(
118
+ default=[],
119
+ nargs=argclass.Nargs.ZERO_OR_MORE,
120
+ type=str,
121
+ converter=frozenset,
122
+ help=(
123
+ "Browser origins to accept. Any Origin not listed is refused. The "
124
+ "environment variable and the config file hold a Python list, such "
125
+ 'as ["https://docker.example.com"].'
126
+ ),
127
+ )
128
+ confirm: str = argclass.Argument(
129
+ default="destructive",
130
+ choices=LEVELS,
131
+ help=(
132
+ "What to ask a person about. 'destructive' asks only before what "
133
+ "cannot be undone; 'never' asks nothing, for a host that already "
134
+ "asks its own permission; 'changes' asks before anything that "
135
+ "changes anything."
136
+ ),
137
+ )
138
+ session_ttl: int = argclass.Argument(default=3600, help="Seconds a session lives without use.")
139
+ generate_config = argclass.Argument(
140
+ action=argclass.GenerateConfigAction,
141
+ generator=argclass.INIConfigGenerator,
142
+ metavar="FILE",
143
+ help=(
144
+ "Write every setting and its default to a config file, then exit. "
145
+ "'-' writes to standard output."
146
+ ),
147
+ )
148
+ log_level: str = argclass.Argument(
149
+ default="info",
150
+ choices=("debug", "info", "warning", "error"),
151
+ help="How much this server writes to its own log.",
152
+ )
153
+
154
+
155
+ def authentication(parser: Parser) -> Authorization | None:
156
+ """Build the Bearer policy from the pre-shared key, or nothing without a key.
157
+
158
+ The audience is the endpoint's public URL. It is what a token must name, and
159
+ what the endpoint publishes as its protected resource.
160
+ """
161
+ key = str(parser.jwt.psk)
162
+ if not key:
163
+ return None
164
+ if not parser.jwt.audience:
165
+ raise SystemExit("--jwt-audience is required with a pre-shared key")
166
+ verifier = HMACJWTVerifier(key, issuer=parser.jwt.issuer, audience=parser.jwt.audience)
167
+ # aiohttp-tiny-mcp 0.8.2 names the verifier parameter `credentials`, so the
168
+ # class does not satisfy that release's own `TokenVerifier` protocol. Drop
169
+ # the cast after the next release.
170
+ return QueryToken(
171
+ cast(TokenVerifier, verifier), resource=parser.jwt.audience, query=parser.jwt.query_token
172
+ )
173
+
174
+
175
+ def assemble(parser: Parser) -> tuple[Registry, SqliteStorage, Docker]:
176
+ """Build the server from settings, independently of command-line parsing."""
177
+ storage = SqliteStorage(parser.state)
178
+ client = Docker(url=parser.docker_url) if parser.docker_url else Docker()
179
+ registry = Registry(
180
+ "docker",
181
+ "0.1.0",
182
+ hub=SqliteHub(storage),
183
+ session_store=SqliteSessionStore(storage),
184
+ session_ttl_seconds=parser.session_ttl,
185
+ auth=authentication(parser),
186
+ )
187
+ return (
188
+ build(
189
+ registry,
190
+ client,
191
+ Policy(parser.confirm),
192
+ unprivileged=parser.unprivileged,
193
+ network=parser.network,
194
+ ),
195
+ storage,
196
+ client,
197
+ )
198
+
199
+
200
+ async def background(registry: Registry, storage: SqliteStorage, client: Docker):
201
+ """Manage background tasks for the application lifetime.
202
+
203
+ `sweeping` removes expired sessions and stale events. One file means
204
+ workers on one machine, and a few of them deleting the same rows costs
205
+ little.
206
+ """
207
+ tasks = [
208
+ asyncio.ensure_future(storage.sweeping()),
209
+ asyncio.ensure_future(watch(registry, client)),
210
+ ]
211
+ return tasks
212
+
213
+
214
+ async def serve(parser: Parser) -> None:
215
+ registry, storage, client = assemble(parser)
216
+ endpoint = Endpoint(
217
+ registry,
218
+ # A set, because the published Endpoint signature names `set[str]`.
219
+ allowed_origins=set(parser.allowed_origin) or None,
220
+ # Behind a reverse proxy, uncomment this and let the proxy check Origin.
221
+ # trust_proxy_origin_validation=True,
222
+ )
223
+ app = endpoint.app(parser.path)
224
+ if parser.console:
225
+ Console(
226
+ parser.path,
227
+ title="Docker",
228
+ description=(
229
+ "Inspect and control the Docker daemon this server is pointed "
230
+ "at. Anything that removes, writes or creates asks first."
231
+ ),
232
+ ).setup(app, parser.console)
233
+
234
+ async def start(_: web.Application):
235
+ tasks = await background(registry, storage, client)
236
+ yield
237
+ for task in tasks:
238
+ task.cancel()
239
+ await asyncio.gather(*tasks, return_exceptions=True)
240
+ await client.close()
241
+ await storage.close()
242
+
243
+ app.cleanup_ctx.append(start)
244
+ log.info("listening on http://%s:%s%s", parser.host, parser.port, parser.path)
245
+ if parser.console:
246
+ log.info("console on http://%s:%s%s", parser.host, parser.port, parser.console)
247
+ await web._run_app(app, host=parser.host, port=parser.port, print=None)
248
+
249
+
250
+ async def stdio(parser: Parser) -> None:
251
+ registry, storage, client = assemble(parser)
252
+ if registry.auth is not None:
253
+ # One process, one caller, no HTTP request to carry a token.
254
+ log.warning("the pre-shared key authenticates HTTP requests only; stdio ignores it")
255
+ tasks = await background(registry, storage, client)
256
+ try:
257
+ await run_stdio(registry)
258
+ finally:
259
+ for task in tasks:
260
+ task.cancel()
261
+ await asyncio.gather(*tasks, return_exceptions=True)
262
+ await client.close()
263
+ await storage.close()
264
+
265
+
266
+ def main() -> None:
267
+ parser = Parser(
268
+ auto_env_var_prefix="DOCKER_TINY_MCP_",
269
+ # A later file overrides an earlier one, and a missing file is skipped:
270
+ # the machine's file, then this user's, then this directory's.
271
+ config_files=["/etc/docker/mcp.ini", "~/.config/docker/mcp.ini", ".docker-tiny-mcp.ini"],
272
+ config_argument="--config",
273
+ )
274
+ parser.parse_args()
275
+ logging.basicConfig(level=parser.log_level.upper(), stream=None)
276
+ asyncio.run(stdio(parser) if parser.stdio else serve(parser))
277
+
278
+
279
+ if __name__ == "__main__":
280
+ main()
@@ -0,0 +1,252 @@
1
+ """Confirmation policy and remembered permissions.
2
+
3
+ Check the deployment policy, read-only command allowlist, and saved grants before asking. The
4
+ default confirms destructive actions; `never` disables confirmation and `changes` confirms all
5
+ changes. Grants use shared session storage.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ from typing import Any
12
+
13
+ from aiohttp_tiny_mcp import Exchange, elicit
14
+ from aiohttp_tiny_mcp.storage.namespaces import scoped
15
+ from aiohttp_tiny_mcp.storage.sessions import DATA_KEY, Session
16
+
17
+ CONSENT_KEY = "consent"
18
+
19
+ DESTROYS = frozenset({"exec", "prune", "remove", "remove_image"})
20
+
21
+ LEVELS = ("never", "destructive", "changes")
22
+
23
+ CALLER_PREFIX = "consent-"
24
+
25
+ CONFIRM: dict[str, Any] = {
26
+ "type": "object",
27
+ "properties": {"confirmed": {"type": "boolean", "description": "Say yes to go ahead."}},
28
+ "required": ["confirmed"],
29
+ }
30
+
31
+ REMEMBER: dict[str, Any] = {
32
+ "type": "string",
33
+ "enum": ["once", "this", "any"],
34
+ "enumNames": [
35
+ "Ask me again next time",
36
+ "Do not ask again for this one",
37
+ "Do not ask again for anything like it",
38
+ ],
39
+ "default": "once",
40
+ "description": "How long this answer holds.",
41
+ }
42
+
43
+
44
+ class Policy:
45
+ """Deployment-wide confirmation policy injected into handlers."""
46
+
47
+ def __init__(self, level: str = "destructive") -> None:
48
+ if level not in LEVELS:
49
+ raise ValueError(f"confirm must be one of {', '.join(LEVELS)}, not {level!r}")
50
+ self.level = level
51
+
52
+ def asks(self, action: str) -> bool:
53
+ if self.level == "never":
54
+ return False
55
+ if self.level == "changes":
56
+ return True
57
+ return action in DESTROYS
58
+
59
+
60
+ def question(text: str, *, keepable: bool) -> Any:
61
+ """Build a confirmation form, including remembrance only when it can be persisted."""
62
+ schema = {**CONFIRM, "properties": dict(CONFIRM["properties"])}
63
+ if keepable:
64
+ schema["properties"]["remember"] = REMEMBER
65
+ return elicit(text, schema)
66
+
67
+
68
+ READING = frozenset(
69
+ {
70
+ "arp",
71
+ "basename",
72
+ "cat",
73
+ "cksum",
74
+ "cut",
75
+ "date",
76
+ "df",
77
+ "dirname",
78
+ "dmesg",
79
+ "du",
80
+ "echo",
81
+ "egrep",
82
+ "env",
83
+ "false",
84
+ "fgrep",
85
+ "file",
86
+ "find",
87
+ "free",
88
+ "getent",
89
+ "grep",
90
+ "head",
91
+ "hostname",
92
+ "id",
93
+ "ifconfig",
94
+ "ip",
95
+ "locale",
96
+ "ls",
97
+ "lscpu",
98
+ "lsof",
99
+ "md5sum",
100
+ "mount",
101
+ "nl",
102
+ "nproc",
103
+ "netstat",
104
+ "printenv",
105
+ "printf",
106
+ "ps",
107
+ "pwd",
108
+ "readlink",
109
+ "sha1sum",
110
+ "sha256sum",
111
+ "sort",
112
+ "ss",
113
+ "stat",
114
+ "strings",
115
+ "tail",
116
+ "top",
117
+ "true",
118
+ "uname",
119
+ "uniq",
120
+ "uptime",
121
+ "wc",
122
+ "which",
123
+ "whoami",
124
+ }
125
+ )
126
+
127
+ WRITING_ARGUMENTS: dict[str, frozenset[str]] = {
128
+ "find": frozenset(
129
+ {
130
+ "-delete",
131
+ "-exec",
132
+ "-execdir",
133
+ "-fls",
134
+ "-fprint",
135
+ "-fprint0",
136
+ "-fprintf",
137
+ "-ok",
138
+ "-okdir",
139
+ }
140
+ ),
141
+ }
142
+
143
+
144
+ def only_reads(command: list[str]) -> bool:
145
+ """Check the command allowlist and reject arguments with side effects. Unlisted commands
146
+ require confirmation.
147
+ """
148
+ if not command:
149
+ return False
150
+ program = command[0].rsplit("/", 1)[-1]
151
+ if program not in READING:
152
+ return False
153
+ forbidden = WRITING_ARGUMENTS.get(program, frozenset())
154
+ return not any(argument in forbidden for argument in command[1:])
155
+
156
+
157
+ def scope(action: str, target: str) -> str:
158
+ """The permission one answer grants, as one string."""
159
+ return f"{action}:{target}"
160
+
161
+
162
+ def caller(ex: Exchange) -> str | None:
163
+ """Derive a stable permission handle from self-declared client identity on revisions without
164
+ sessions.
165
+
166
+ This is not authentication: endpoint callers can already invoke tools and answer their own
167
+ confirmations. Grants expire with the session.
168
+ """
169
+ info = getattr(ex, "client_info", None)
170
+ said = f"{getattr(info, 'name', '')}/{getattr(info, 'version', '')}".strip("/")
171
+ if not said:
172
+ return None
173
+ return CALLER_PREFIX + hashlib.sha256(said.encode()).hexdigest()[:32]
174
+
175
+
176
+ async def remembering(ex: Exchange) -> Session | None:
177
+ """Use the protocol session or a caller-derived session in the shared store."""
178
+ session = getattr(ex, "session", None)
179
+ if session is not None:
180
+ return session
181
+ access = getattr(ex, "sessions", None)
182
+ handle = caller(ex)
183
+ if access is None or handle is None:
184
+ return None
185
+ found = await access.use(handle)
186
+ if found is None:
187
+ await access.store.create(scoped(handle), {DATA_KEY: {}}, ttl_seconds=access.ttl_seconds)
188
+ found = await access.use(handle)
189
+ return found
190
+
191
+
192
+ async def granted(ex: Exchange, action: str, target: str) -> bool:
193
+ """Whether this caller already allowed this, and said not to ask again."""
194
+ session = await remembering(ex)
195
+ if session is None:
196
+ return False
197
+ allowed = session.get(CONSENT_KEY) or []
198
+ return scope(action, target) in allowed or scope(action, "*") in allowed
199
+
200
+
201
+ async def keep(ex: Exchange, action: str, target: str, remember: str) -> None:
202
+ """Write down what may now be done without asking again."""
203
+ if remember not in ("this", "any"):
204
+ return
205
+ session = await remembering(ex)
206
+ if session is None:
207
+ return
208
+ wanted = scope(action, target if remember == "this" else "*")
209
+ allowed = list(session.get(CONSENT_KEY) or [])
210
+ if wanted not in allowed:
211
+ await session.set(CONSENT_KEY, [*allowed, wanted])
212
+
213
+
214
+ def refusal(ex: Exchange, key: str = "confirm") -> str:
215
+ """Distinguish an explicit decline from a cancelled confirmation."""
216
+ action = ex.action(key)
217
+ return action.value if action is not None else "unanswered"
218
+
219
+
220
+ async def confirm(ex: Exchange, policy: Policy, action: str, target: str, text: str) -> bool:
221
+ """Apply policy and remembered grants before asking. An accepted form with confirmed=false is
222
+ still a refusal.
223
+ """
224
+ if not policy.asks(action):
225
+ return True
226
+ if await granted(ex, action, target):
227
+ return True
228
+ keepable = await remembering(ex) is not None
229
+ answer = await ex.ask("confirm", question(text, keepable=keepable))
230
+ if not (answer.accepted and answer.get("confirmed")):
231
+ return False
232
+ await keep(ex, action, target, str(answer.get("remember") or "once"))
233
+ return True
234
+
235
+
236
+ __all__ = [
237
+ "CONFIRM",
238
+ "CONSENT_KEY",
239
+ "DESTROYS",
240
+ "LEVELS",
241
+ "Policy",
242
+ "READING",
243
+ "REMEMBER",
244
+ "caller",
245
+ "confirm",
246
+ "granted",
247
+ "keep",
248
+ "only_reads",
249
+ "question",
250
+ "refusal",
251
+ "remembering",
252
+ ]
@@ -0,0 +1,71 @@
1
+ """Shared Docker lookups over an application-owned aiodocker client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timezone
6
+ from typing import Any
7
+
8
+ from aiodocker import Docker
9
+ from aiodocker.containers import DockerContainer
10
+ from aiodocker.exceptions import DockerError
11
+
12
+ from docker_tiny_mcp.errors import NotFound, clear
13
+ from docker_tiny_mcp.models import short
14
+
15
+
16
+ def name_of(raw: Any) -> str:
17
+ names = raw.get("Names") or []
18
+ if names:
19
+ return str(names[0]).lstrip("/")
20
+ return short(str(raw.get("Id", "")))
21
+
22
+
23
+ def when(value: Any) -> str | None:
24
+ """Normalize ISO timestamps and epoch seconds to ISO-8601."""
25
+ if isinstance(value, (int, float)):
26
+ return datetime.fromtimestamp(value, tz=timezone.utc).isoformat()
27
+ text = str(value or "")
28
+ if not text or text.startswith("0001-01-01"):
29
+ return None
30
+ return text
31
+
32
+
33
+ async def containers(client: Docker, *, all: bool = False) -> list[dict[str, Any]]:
34
+ """Extract list response dictionaries from aiodocker container objects."""
35
+ async with clear("listing containers"):
36
+ found = await client.containers.list(all=all)
37
+ return [dict(item._container) for item in found]
38
+
39
+
40
+ async def find(client: Docker, reference: str) -> DockerContainer:
41
+ """Resolve container names or id prefixes, with partial-name fallback. Reject ambiguous
42
+ matches.
43
+ """
44
+ try:
45
+ return await client.containers.get(reference)
46
+ except DockerError:
47
+ pass
48
+ wanted = reference.lstrip("/").lower()
49
+ matches = []
50
+ for raw in await containers(client, all=True):
51
+ identity = str(raw.get("Id", "")).lower()
52
+ names = [str(name).lstrip("/").lower() for name in raw.get("Names") or []]
53
+ if identity.startswith(wanted) or any(wanted in name for name in names):
54
+ matches.append(raw)
55
+ if not matches:
56
+ raise NotFound(f"no container matches {reference!r}")
57
+ if len(matches) > 1:
58
+ named = ", ".join(name_of(raw) for raw in matches[:5])
59
+ raise NotFound(f"{reference!r} matches several containers: {named}")
60
+ return client.containers.container(str(matches[0]["Id"]))
61
+
62
+
63
+ async def state_of(container: DockerContainer) -> dict[str, Any]:
64
+ async with clear("reading the container"):
65
+ raw = await container.show()
66
+ return dict(raw.get("State") or {})
67
+
68
+
69
+ async def images(client: Docker) -> list[dict[str, Any]]:
70
+ async with clear("listing images"):
71
+ return [dict(item) for item in await client.images.list()]
@@ -0,0 +1,89 @@
1
+ """Translate Docker failures into actionable tool errors."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import AsyncIterator
7
+ from contextlib import asynccontextmanager
8
+
9
+ from aiodocker.exceptions import DockerError
10
+
11
+ STOPPED = "is not running"
12
+
13
+
14
+ class Trouble(Exception):
15
+ """Base error; subclasses name the failure in tool results."""
16
+
17
+
18
+ class NotFound(Trouble, LookupError):
19
+ """No container, image, network or volume matches."""
20
+
21
+
22
+ class NotRunning(Trouble):
23
+ """The container exists but is stopped, and the action needs it running."""
24
+
25
+
26
+ class Conflict(Trouble):
27
+ """The daemon refused: a name is taken, or something is still in use."""
28
+
29
+
30
+ class Unreachable(Trouble):
31
+ """The daemon did not answer. Nothing was done."""
32
+
33
+
34
+ class Timeout(Trouble):
35
+ """The work outlasted the time it was given. It may still be running."""
36
+
37
+
38
+ class Refused(Trouble):
39
+ """A person was asked and said no, or was not asked at all."""
40
+
41
+
42
+ LONG_ID = re.compile(r"\b[0-9a-f]{32,64}\b")
43
+
44
+
45
+ def said(error: DockerError) -> str:
46
+ """The daemon's own sentence, with its full ids cut to the twelve
47
+ characters its own output uses."""
48
+ text = str(error.message or "").strip().rstrip(".")
49
+ return LONG_ID.sub(lambda found: found.group(0)[:12], text)
50
+
51
+
52
+ @asynccontextmanager
53
+ async def clear(doing: str, *, subject: str = "") -> AsyncIterator[None]:
54
+ """Translate Docker errors. doing is a present-participle action; subject identifies its
55
+ target.
56
+ """
57
+ about = f" {subject}" if subject else ""
58
+ try:
59
+ yield
60
+ except DockerError as error:
61
+ if error.status == 404:
62
+ said_plainly = f"{subject} was not found" if subject else f"not found: {said(error)}"
63
+ raise NotFound(said_plainly) from error
64
+ if error.status == 409 and STOPPED in said(error):
65
+ raise NotRunning(
66
+ f"{subject or 'the container'} is stopped. Start it first, then try {doing} again."
67
+ ) from error
68
+ if error.status == 409:
69
+ raise Conflict(f"the daemon refused{about}: {said(error)}") from error
70
+ if error.status in (502, 503, 504):
71
+ raise Unreachable(f"the daemon is not answering while {doing}") from error
72
+ raise Trouble(f"{doing}{about} failed: {said(error)}") from error
73
+ except OSError as error:
74
+ raise Unreachable(
75
+ f"cannot reach the Docker daemon while {doing}: {error}. "
76
+ "Check that it runs, and that this server may read its socket."
77
+ ) from error
78
+
79
+
80
+ __all__ = [
81
+ "Conflict",
82
+ "NotFound",
83
+ "NotRunning",
84
+ "Refused",
85
+ "Timeout",
86
+ "Trouble",
87
+ "Unreachable",
88
+ "clear",
89
+ ]