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,65 @@
1
+ """What the daemon did lately, rather than what is true now.
2
+
3
+ No amount of reading the current state says when a container last restarted.
4
+ The daemon keeps that, and `docker.history` asks for it with an `until`, which
5
+ is what makes the read finish instead of following what happens next.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import time
11
+ from typing import Any
12
+
13
+ from aiodocker import Docker
14
+ from aiodocker.jsonstream import json_stream_list
15
+
16
+ from docker_tiny_mcp import daemon
17
+ from docker_tiny_mcp.errors import clear
18
+ from docker_tiny_mcp.models import Event, EventFilter, Events, short
19
+
20
+
21
+ def event_of(raw: dict[str, Any]) -> Event:
22
+ actor = raw.get("Actor") or {}
23
+ attributes = actor.get("Attributes") or {}
24
+ exit_code = attributes.get("exitCode")
25
+ at = raw.get("time")
26
+ return Event(
27
+ at=daemon.when(at) or "",
28
+ kind=str(raw.get("Type", "")),
29
+ action=str(raw.get("Action", "")),
30
+ subject=str(attributes.get("name") or short(str(actor.get("ID", "")))),
31
+ exit_code=int(exit_code) if exit_code not in (None, "") else None,
32
+ )
33
+
34
+
35
+ def epoch() -> float:
36
+ """Now, in the seconds the daemon's event filters count in."""
37
+ return time.time()
38
+
39
+
40
+ async def history(client: Docker, since: float, until: float) -> list[dict[str, Any]]:
41
+ """Read recorded events. `until` bounds the read; without it the daemon holds the connection
42
+ open for events still to come.
43
+ """
44
+ async with clear("reading the daemon's events"):
45
+ async with client._query(
46
+ "events", method="GET", params={"since": int(since), "until": int(until)}
47
+ ) as response:
48
+ raw = await json_stream_list(response, raise_on_error=False)
49
+ return [dict(item) for item in raw]
50
+
51
+
52
+ async def events(args: EventFilter, client: Docker) -> Events:
53
+ """What the daemon has done lately: containers started, died or removed.
54
+
55
+ This is how to answer "when did it restart" and "what happened just
56
+ before it stopped", which no amount of reading the current state will
57
+ say. Ask for a wider `seconds` if nothing comes back.
58
+ """
59
+ now = epoch()
60
+ listed = [event_of(raw) for raw in await history(client, now - args.seconds, now)]
61
+ if args.container:
62
+ wanted = args.container.lower()
63
+ listed = [item for item in listed if wanted in item.subject.lower()]
64
+ kept = listed[-args.limit :]
65
+ return Events(events=kept, shown=len(kept), total=len(listed))
@@ -0,0 +1,99 @@
1
+ """Running a command inside a container.
2
+
3
+ Three things this owes a caller that `docker exec` does not give for free. The
4
+ two streams are kept apart, because the daemon interleaves them and merging
5
+ loses which was which. The command is given a deadline, so a call cannot be
6
+ held open by something that never finishes. And a command that only reads runs
7
+ without asking anybody -- see `consent.py` for where that line is drawn.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+
14
+ from aiodocker import Docker
15
+ from aiohttp_tiny_mcp import Exchange
16
+
17
+ from docker_tiny_mcp import daemon
18
+ from docker_tiny_mcp.consent import Policy, confirm, only_reads, refusal
19
+ from docker_tiny_mcp.errors import Conflict
20
+ from docker_tiny_mcp.models import ExecRequest, Executed
21
+ from docker_tiny_mcp.safety import checked_container
22
+
23
+ MAX_OUTPUT = 60_000
24
+
25
+
26
+ async def exec(args: ExecRequest, client: Docker, ex: Exchange, policy: Policy) -> Executed:
27
+ """Run a command inside a running container, and report what it wrote.
28
+
29
+ This is `docker exec`, not `docker run`: it needs a container that is
30
+ already running. Use `create` to start a new one.
31
+
32
+ A command that only reads -- `ls`, `cat`, `ps`, `df` and their like -- is
33
+ run without asking at all. Anything else may ask first, because a command
34
+ can do whatever the container can. It is given `seconds` to finish, and is
35
+ reported as timed out after that.
36
+ """
37
+ found = await daemon.find(client, args.container)
38
+ printable = " ".join(args.command)
39
+ if not only_reads(args.command) and not await confirm(
40
+ ex, policy, "exec", args.container, f"Run `{printable}` inside {args.container}?"
41
+ ):
42
+ return Executed(
43
+ container=args.container,
44
+ command=printable,
45
+ exit_code=-1,
46
+ stdout="",
47
+ stderr=f"not run: {refusal(ex)}",
48
+ )
49
+
50
+ state = await daemon.state_of(found)
51
+ if str(state.get("Status")) != "running":
52
+ raise Conflict(
53
+ f"{args.container} is {state.get('Status')}, and a command needs it running. "
54
+ "Start it first, or use `read` to see a file without running anything."
55
+ )
56
+
57
+ session = await found.exec(
58
+ args.command,
59
+ stdout=True,
60
+ stderr=True,
61
+ workdir=args.workdir,
62
+ user=args.user or "",
63
+ )
64
+ out: list[bytes] = []
65
+ err: list[bytes] = []
66
+
67
+ async def collect() -> None:
68
+ # aiodocker's Stream works as a context manager; its `__aexit__` is
69
+ # typed to return the exception instead of a boolean.
70
+ async with session.start(detach=False) as stream: # ty: ignore[invalid-context-manager]
71
+ while (message := await stream.read_out()) is not None:
72
+ (err if message.stream == 2 else out).append(message.data)
73
+
74
+ timed_out = False
75
+ try:
76
+ await asyncio.wait_for(collect(), args.seconds)
77
+ except asyncio.TimeoutError:
78
+ timed_out = True
79
+
80
+ result = {} if timed_out else await session.inspect()
81
+ stdout = b"".join(out).decode("utf-8", "replace")
82
+ stderr = b"".join(err).decode("utf-8", "replace")
83
+ return Executed(
84
+ container=args.container,
85
+ command=printable,
86
+ exit_code=-1 if timed_out else int(result.get("ExitCode") or 0),
87
+ stdout=stdout[-MAX_OUTPUT:],
88
+ stderr=stderr[-MAX_OUTPUT:],
89
+ truncated=len(stdout) > MAX_OUTPUT or len(stderr) > MAX_OUTPUT,
90
+ timed_out=timed_out,
91
+ )
92
+
93
+
94
+ async def exec_unprivileged(
95
+ args: ExecRequest, client: Docker, ex: Exchange, policy: Policy
96
+ ) -> Executed:
97
+ """Run a command after checking that the container has no host access."""
98
+ identity = await checked_container(client, args.container)
99
+ return await exec(args.model_copy(update={"container": identity}), client, ex, policy)
@@ -0,0 +1,71 @@
1
+ """Images, and the only question worth asking about one on a full disk.
2
+
3
+ `used_by` is that question. It is filled from the containers, not from the
4
+ image, because the daemon does not say it: an image reports its size and its
5
+ age and leaves the caller to work out whether removing it breaks anything.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping, Sequence
11
+ from typing import Any
12
+
13
+ from aiodocker import Docker
14
+
15
+ from docker_tiny_mcp import daemon
16
+ from docker_tiny_mcp.models import Image, ImageFilter, Images, short
17
+
18
+
19
+ def holders(containers: Sequence[dict[str, Any]]) -> dict[str, list[str]]:
20
+ """Which containers hold which image, by every name the image goes under.
21
+
22
+ A container names its image as a tag, and the daemon also reports the
23
+ digest it resolved to. Both are keys here, because a list of images is
24
+ matched against whichever one it happens to carry.
25
+ """
26
+ found: dict[str, list[str]] = {}
27
+ for raw in containers:
28
+ name = daemon.name_of(raw)
29
+ for key in (str(raw.get("Image", "")), str(raw.get("ImageID", ""))):
30
+ if key:
31
+ found.setdefault(key, []).append(name)
32
+ return found
33
+
34
+
35
+ def image_of(raw: dict[str, Any], users: Mapping[str, list[str]] | None = None) -> Image:
36
+ """One image, and what still holds it.
37
+
38
+ `used_by` is the answer to the only question worth asking about an image
39
+ on a full disk. It is empty exactly where the image can be removed.
40
+ """
41
+ identity = str(raw.get("Id", ""))
42
+ tags = [tag for tag in raw.get("RepoTags") or [] if tag != "<none>:<none>"]
43
+ holders = users or {}
44
+ return Image(
45
+ id=short(identity.removeprefix("sha256:")),
46
+ tags=tags,
47
+ size_mb=round(float(raw.get("Size", 0) or 0) / 1_000_000, 1),
48
+ created=daemon.when(raw.get("Created")) or "",
49
+ used_by=sorted({name for key in [identity, *tags] for name in holders.get(key, [])}),
50
+ )
51
+
52
+
53
+ async def images(args: ImageFilter, client: Docker) -> Images:
54
+ """List images held locally, with their sizes and what still holds them.
55
+
56
+ `used_by` is empty exactly where an image can be removed, so ask with
57
+ `unused` when looking for space. Check here before pulling, too.
58
+ """
59
+ found = await daemon.images(client)
60
+ users = holders(await daemon.containers(client, all=True))
61
+ listed = [image_of(raw, users) for raw in found]
62
+ if args.reference:
63
+ wanted = args.reference.strip("*").lower()
64
+ listed = [item for item in listed if any(wanted in tag.lower() for tag in item.tags)]
65
+ if args.unused:
66
+ listed = [item for item in listed if not item.used_by]
67
+ return Images(
68
+ images=listed,
69
+ total=len(listed),
70
+ reclaimable_mb=round(sum(item.size_mb for item in listed if not item.used_by), 1),
71
+ )
@@ -0,0 +1,51 @@
1
+ """Which daemon this is, before anything is blamed on it.
2
+
3
+ `endpoint` is here for one failure that costs an afternoon: a server pointed
4
+ at the wrong machine looks exactly like a machine with nothing on it.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Sequence
10
+ from typing import Any
11
+
12
+ from aiodocker import Docker
13
+
14
+ from docker_tiny_mcp import daemon
15
+ from docker_tiny_mcp.errors import clear
16
+ from docker_tiny_mcp.models import Info, Nothing
17
+
18
+
19
+ def info_of(
20
+ endpoint: str, version: dict[str, Any], containers: Sequence[dict[str, Any]], images: int
21
+ ) -> Info:
22
+ running = sum(1 for item in containers if item.get("State") == "running")
23
+ return Info(
24
+ endpoint=endpoint,
25
+ version=str(version.get("Version", "")),
26
+ api_version=str(version.get("ApiVersion", "")),
27
+ os=str(version.get("Os", "")),
28
+ architecture=str(version.get("Arch", "")),
29
+ containers_running=running,
30
+ containers_total=len(containers),
31
+ images=images,
32
+ )
33
+
34
+
35
+ async def version(client: Docker) -> dict[str, Any]:
36
+ async with clear("reading the daemon's version"):
37
+ return dict(await client.version())
38
+
39
+
40
+ async def info(args: Nothing, client: Docker) -> Info:
41
+ """The daemon itself: where it is, its version, and how much it holds.
42
+
43
+ Use this to confirm Docker is reachable before blaming anything else, and
44
+ to confirm it is the machine you meant.
45
+ """
46
+ return info_of(
47
+ str(client.docker_host),
48
+ await version(client),
49
+ await daemon.containers(client, all=True),
50
+ len(await daemon.images(client)),
51
+ )
@@ -0,0 +1,101 @@
1
+ """What a container wrote, dated, and readable a second time.
2
+
3
+ Two things are worth knowing here. The daemon can deliver both streams at
4
+ once but not labelled, so they are read separately and merged by time -- which
5
+ is the only reason a line knows whether it was a report or a failure. And
6
+ `cursor` is what makes a second read cheap: without it a caller asks for the
7
+ same tail again and cannot tell what is new.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from datetime import datetime, timezone
13
+ from typing import Any
14
+
15
+ from aiodocker import Docker
16
+ from aiodocker.containers import DockerContainer
17
+
18
+ from docker_tiny_mcp import daemon
19
+ from docker_tiny_mcp.errors import clear
20
+ from docker_tiny_mcp.models import LogLine, LogRequest, Logs, Stream
21
+
22
+ UNDATED = "~"
23
+
24
+ OVERSHOOT = 4
25
+
26
+ MOST_LINES = 5000
27
+
28
+
29
+ def timestamped(text: str, stream: Stream) -> LogLine:
30
+ """One line as Docker writes it with `timestamps=1`: a time, a space, the
31
+ line. A line without one is kept, because a log is worth reading even
32
+ where the daemon did not date it."""
33
+ head, _, rest = text.partition(" ")
34
+ if head.count("-") == 2 and head.count(":") >= 2:
35
+ return LogLine(at=head, stream=stream, text=rest)
36
+ return LogLine(at=None, stream=stream, text=text)
37
+
38
+
39
+ def as_epoch(text: str) -> str:
40
+ """One log timestamp, in the seconds `since` is actually counted in.
41
+
42
+ The daemon writes RFC 3339 with nanoseconds and reads back only a Unix
43
+ timestamp -- `since=2026-09-13T20:30:42.897161158Z` is refused as an
44
+ invalid number of seconds. The nanoseconds are carried across as the
45
+ fraction, because a cursor rounded to the second repeats a whole second
46
+ of the log on every read.
47
+ """
48
+ body = text.strip().rstrip("Z")
49
+ if not body or body.replace(".", "", 1).isdigit():
50
+ return body or "0"
51
+ head, _, fraction = body.partition(".")
52
+ moment = datetime.strptime(head, "%Y-%m-%dT%H:%M:%S").replace(tzinfo=timezone.utc)
53
+ seconds = int(moment.timestamp())
54
+ return f"{seconds}.{fraction}" if fraction else str(seconds)
55
+
56
+
57
+ async def log_lines(
58
+ container: DockerContainer, *, stream: Stream, lines: int, since: str | None
59
+ ) -> list[LogLine]:
60
+ """Read the tail of one stream, dated. The daemon delivers both streams together but
61
+ unlabelled, so each is read separately and the caller merges them.
62
+ """
63
+ params: dict[str, Any] = {"timestamps": True, "tail": lines}
64
+ if since:
65
+ params["since"] = as_epoch(since)
66
+ async with clear("reading the log"):
67
+ raw = await container.log(stdout=stream == "stdout", stderr=stream == "stderr", **params)
68
+ written = raw if isinstance(raw, list) else str(raw).splitlines()
69
+ return [timestamped(str(line).rstrip("\n"), stream) for line in written if str(line).strip()]
70
+
71
+
72
+ async def logs(args: LogRequest, client: Docker) -> Logs:
73
+ """Read what a container wrote, newest last.
74
+
75
+ The first place to look when something failed. Every line is dated, and
76
+ `cursor` comes back with the time of the last one -- pass it as `since` on
77
+ the next call to read only what is new, instead of the same tail again.
78
+ Narrow a noisy log with `contains` rather than by asking for more lines.
79
+ """
80
+ found = await daemon.find(client, args.container)
81
+ wanted: list[Stream] = ["stdout", "stderr"] if args.stream == "both" else [args.stream]
82
+ asked = args.lines if len(wanted) == 2 else min(args.lines * OVERSHOOT, MOST_LINES)
83
+ collected = []
84
+ for stream in wanted:
85
+ collected += await log_lines(found, stream=stream, lines=asked, since=args.since)
86
+ fetched = len(collected)
87
+ collected.sort(key=lambda line: line.at or UNDATED)
88
+ if args.since:
89
+ collected = [line for line in collected if (line.at or "") > args.since]
90
+ if args.contains:
91
+ needle = args.contains.lower()
92
+ collected = [line for line in collected if needle in line.text.lower()]
93
+ kept = collected[-args.lines :]
94
+ tagged = args.stream == "both"
95
+ return Logs(
96
+ container=args.container,
97
+ lines=[line.rendered(tagged=tagged) for line in kept],
98
+ shown=len(kept),
99
+ truncated=fetched >= asked or len(collected) > len(kept),
100
+ cursor=next((line.at for line in reversed(kept) if line.at), None),
101
+ )
@@ -0,0 +1,59 @@
1
+ """Networks, for the question no container's own state answers.
2
+
3
+ Two containers that cannot reach each other are usually not on one network,
4
+ and nothing in either container says so.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Mapping, Sequence
10
+ from typing import Any
11
+
12
+ from aiodocker import Docker
13
+
14
+ from docker_tiny_mcp import daemon
15
+ from docker_tiny_mcp.errors import clear
16
+ from docker_tiny_mcp.models import NameFilter, Network, Networks, short
17
+
18
+
19
+ def attachments(containers: Sequence[dict[str, Any]]) -> dict[str, list[str]]:
20
+ """Which containers are on which network.
21
+
22
+ Built from the containers, because the daemon will not say. `GET /networks`
23
+ omits `Containers` -- only inspecting one network reports it -- so reading
24
+ it from the list gives an answer that is always empty.
25
+ """
26
+ found: dict[str, list[str]] = {}
27
+ for raw in containers:
28
+ name = daemon.name_of(raw)
29
+ for network in (raw.get("NetworkSettings") or {}).get("Networks") or {}:
30
+ found.setdefault(str(network), []).append(name)
31
+ return found
32
+
33
+
34
+ def network_of(raw: dict[str, Any], attached: Mapping[str, list[str]] | None = None) -> Network:
35
+ config = (raw.get("IPAM") or {}).get("Config") or []
36
+ return Network(
37
+ id=short(str(raw.get("Id", ""))),
38
+ name=str(raw.get("Name", "")),
39
+ driver=str(raw.get("Driver", "")),
40
+ scope=str(raw.get("Scope", "")),
41
+ subnets=[str(item.get("Subnet")) for item in config if item.get("Subnet")],
42
+ containers=sorted((attached or {}).get(str(raw.get("Name", "")), [])),
43
+ )
44
+
45
+
46
+ async def networks(args: NameFilter, client: Docker) -> Networks:
47
+ """List networks, with their subnets and what is attached.
48
+
49
+ Use this when two containers cannot reach each other: the usual cause is
50
+ that they are not on one network.
51
+ """
52
+ attached = attachments(await daemon.containers(client, all=True))
53
+ async with clear("listing networks"):
54
+ found = await client.networks.list()
55
+ listed = [network_of(dict(raw), attached) for raw in found]
56
+ if args.name:
57
+ wanted = args.name.lower()
58
+ listed = [item for item in listed if wanted in item.name.lower()]
59
+ return Networks(networks=listed, total=len(listed))
@@ -0,0 +1,60 @@
1
+ """Removing everything of one kind that nothing uses.
2
+
3
+ The tool for a full disk, and the one that removes the most at once. Each kind
4
+ is a separate call rather than a single sweep, so the question names what will
5
+ go and a person can agree to one kind without agreeing to all four.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from aiodocker import Docker
11
+ from aiohttp_tiny_mcp import Exchange
12
+
13
+ from docker_tiny_mcp.consent import Policy, confirm, refusal
14
+ from docker_tiny_mcp.errors import Conflict, clear
15
+ from docker_tiny_mcp.events import publish
16
+ from docker_tiny_mcp.models import FixedNetworkPruneRequest, Pruned, PruneRequest
17
+
18
+
19
+ async def prune(args: PruneRequest, client: Docker, ex: Exchange, policy: Policy) -> Pruned:
20
+ """Remove everything of one kind that nothing uses. Asks before it does.
21
+
22
+ This is the tool for a full disk. It is also the one that removes the most
23
+ at once, so the question names what will go. Stopped containers, untagged
24
+ images, unattached volumes and empty networks are each a separate call.
25
+ """
26
+ filters = {"dangling": ["true"]} if args.what == "images" and args.dangling_only else None
27
+ if not await confirm(
28
+ ex,
29
+ policy,
30
+ "prune",
31
+ args.what,
32
+ f"Remove every unused {args.what.rstrip('s')}? This cannot be undone.",
33
+ ):
34
+ raise Conflict(f"nothing removed: {refusal(ex)}")
35
+ kinds = {
36
+ "containers": client.containers,
37
+ "images": client.images,
38
+ "volumes": client.volumes,
39
+ "networks": client.networks,
40
+ }
41
+ async with clear(f"removing unused {args.what}"):
42
+ reply = dict(await kinds[args.what].prune(filters=filters))
43
+ removed = [
44
+ str(item)
45
+ for key in ("ContainersDeleted", "ImagesDeleted", "VolumesDeleted", "NetworksDeleted")
46
+ for item in reply.get(key) or []
47
+ ]
48
+ await publish(ex.registry, f"docker://{args.what}")
49
+ return Pruned(
50
+ what=args.what,
51
+ removed=[item for item in removed if item],
52
+ reclaimed_mb=round(float(reply.get("SpaceReclaimed", 0) or 0) / 1_000_000, 1),
53
+ )
54
+
55
+
56
+ async def prune_fixed_network(
57
+ args: FixedNetworkPruneRequest, client: Docker, ex: Exchange, policy: Policy
58
+ ) -> Pruned:
59
+ """Remove unused containers, images or volumes. The server's fixed network is preserved."""
60
+ return await prune(args, client, ex, policy)
@@ -0,0 +1,36 @@
1
+ """Downloading an image, saying so as it goes.
2
+
3
+ Minutes of silence is indistinguishable from a hang. The layers are counted
4
+ rather than their bytes, because the daemon reports progress per layer and a
5
+ total it never states cannot be invented here.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from aiodocker import Docker
11
+ from aiohttp_tiny_mcp import Exchange
12
+
13
+ from docker_tiny_mcp.events import publish
14
+ from docker_tiny_mcp.models import PullRequest
15
+
16
+
17
+ async def pull(args: PullRequest, client: Docker, ex: Exchange) -> str:
18
+ """Download an image, reporting progress as it goes.
19
+
20
+ This can take minutes for a large image. Check `images` first.
21
+ """
22
+ await ex.log("info", f"pulling {args.image}", logger="pull")
23
+ layers: dict[str, str] = {}
24
+ async for line in client.images.pull(args.image, stream=True):
25
+ layer = str(line.get("id", ""))
26
+ status = str(line.get("status", ""))
27
+ if layer:
28
+ layers[layer] = status
29
+ done = sum(1 for value in layers.values() if "complete" in value.lower())
30
+ await ex.progress(done, max(len(layers), 1), message=status or "working")
31
+ if "error" in line:
32
+ await ex.log("error", str(line["error"]), logger="pull")
33
+ return f"failed: {line['error']}"
34
+ await ex.log("info", f"pulled {args.image}", logger="pull")
35
+ await publish(ex.registry, "docker://images")
36
+ return f"pulled {args.image} ({len(layers)} layers)"
@@ -0,0 +1,69 @@
1
+ """One file out of a container, through the archive endpoint.
2
+
3
+ Not `cat`. The archive works on a stopped container, which is when a
4
+ configuration file is most worth reading, and it needs no shell inside the
5
+ image, which a slim image does not have.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from aiodocker import Docker
11
+ from aiodocker.containers import DockerContainer
12
+
13
+ from docker_tiny_mcp import daemon
14
+ from docker_tiny_mcp.errors import Conflict, clear
15
+ from docker_tiny_mcp.models import FileContent, ReadRequest
16
+ from docker_tiny_mcp.safety import checked_container
17
+
18
+ MAX_FILE_BYTES = 256_000
19
+
20
+
21
+ async def read_file(container: DockerContainer, path: str) -> tuple[bytes, int, bool]:
22
+ """Read one file as an archive: bytes, size, and whether it was cut.
23
+
24
+ The archive endpoint works on a stopped container and needs no shell in the image.
25
+ """
26
+ async with clear("reading the file", subject=path):
27
+ archive = await container.get_archive(path)
28
+ members = archive.getmembers()
29
+ if len(members) != 1 or not members[0].isfile():
30
+ raise Conflict(f"{path} is a directory, not a file. Name a file inside it.")
31
+ handle = archive.extractfile(members[0])
32
+ content = handle.read(MAX_FILE_BYTES + 1) if handle is not None else b""
33
+ size = int(members[0].size)
34
+ return content[:MAX_FILE_BYTES], size, len(content) > MAX_FILE_BYTES
35
+
36
+
37
+ async def read(args: ReadRequest, client: Docker) -> FileContent:
38
+ """Read one file out of a container.
39
+
40
+ Works whether or not the container runs, and needs no shell inside it.
41
+ Use it for configuration the environment does not show, and for a log the
42
+ program wrote to a file instead of to its output.
43
+ """
44
+ found = await daemon.find(client, args.container)
45
+ content, size, cut = await read_file(found, args.path)
46
+ try:
47
+ text = content.decode("utf-8")
48
+ except UnicodeDecodeError:
49
+ return FileContent(
50
+ container=args.container,
51
+ path=args.path,
52
+ size_bytes=size,
53
+ text="",
54
+ truncated=cut,
55
+ binary=True,
56
+ )
57
+ return FileContent(
58
+ container=args.container,
59
+ path=args.path,
60
+ size_bytes=size,
61
+ text=text,
62
+ truncated=cut,
63
+ )
64
+
65
+
66
+ async def read_unprivileged(args: ReadRequest, client: Docker) -> FileContent:
67
+ """Read a file after checking that the container has no host access."""
68
+ identity = await checked_container(client, args.container)
69
+ return await read(args.model_copy(update={"container": identity}), client)
@@ -0,0 +1,36 @@
1
+ """Removing a container for good.
2
+
3
+ The first of the three that cannot be undone, and so one of the few the
4
+ default policy still asks about. The removal itself comes after the question,
5
+ because everything before it runs again when the answer arrives.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from aiodocker import Docker
11
+ from aiohttp_tiny_mcp import Exchange
12
+
13
+ from docker_tiny_mcp import daemon
14
+ from docker_tiny_mcp.consent import Policy, confirm, refusal
15
+ from docker_tiny_mcp.events import publish
16
+ from docker_tiny_mcp.models import RemoveRequest
17
+
18
+
19
+ async def remove(args: RemoveRequest, client: Docker, ex: Exchange, policy: Policy) -> str:
20
+ """Remove a container for good. Asks before it does.
21
+
22
+ This cannot be undone. Stop it first unless `force` is set; a running
23
+ container is not removed by accident.
24
+ """
25
+ found = await daemon.find(client, args.container)
26
+ if not await confirm(
27
+ ex,
28
+ policy,
29
+ "remove",
30
+ args.container,
31
+ f"Remove container {args.container}? This cannot be undone.",
32
+ ):
33
+ return f"not removed: {refusal(ex)}"
34
+ await found.delete(force=args.force, v=args.volumes)
35
+ await publish(ex.registry, "docker://containers")
36
+ return f"removed {args.container}"